Skip to content

Latest commit

 

History

History
754 lines (446 loc) · 25.3 KB

api.md

File metadata and controls

754 lines (446 loc) · 25.3 KB

📚 API reference

This page lists the main classes and their methods with their signatures. The guide pages linked from each section explain them in context, with more examples.

Every method that returns a node returns a new node, and leaves the one it was called on unchanged. this in a return type means "the same class as the node it was called on".

Shortcuts

More info.

C(name)

name: string | SqlColumn
Returns: SqlColumn

A quoted column reference. C.optionalQuotes(name) only quotes when needed.

T(name)

name: string | SqlTable
Returns: SqlTable

A quoted table reference. T.optionalQuotes(name) only quotes when needed.

N(name)

name: string | SqlNamespace
Returns: SqlNamespace

A quoted namespace (schema) reference, like N('sys'). N.optionalQuotes(name) only quotes when needed, and N(name).table(tableName) makes a table in it.

L(value)

value: LiteralValue | SqlLiteral
Returns: SqlLiteral

A literal. Constants: L.NULL, L.TRUE, L.FALSE.

F(name, ...args)

name: string
args: (SqlExpression | LiteralValue | undefined)[]
Returns: SqlFunction

A function call. Trailing undefined arguments are dropped. Helpers: F.count, F.countDistinct, F.sum, F.min, F.max, F.avg, F.cast, F.floor, F.timeFloor, F.timeCeil, F.timeShift, F.stringFormat, F.array, F.regexpLike, F.jsonValue, F.jsonObject.

sql`...`

Returns: SqlExpression

A template tag that parses its template, turning interpolations into literals (${x} and '${x}'), identifiers ("${x}") or inserted expressions (${expression}).

SqlBase

The base class of every node.

More info.

SqlBase.parseSql(input)

input: string | SqlBase
Returns: SqlBase

Parses anything the grammar accepts. Throws a SyntaxError with a location on invalid SQL.

SqlBase.setCapitalization(capitalization)

capitalization: 'upper' | 'lower' | 'title' | 'random'

Sets, globally, how new keywords are written. More info.

node.type

Type: string

The kind of node, such as 'column', 'function', 'query' or 'pipesQuery'.

node.toString()

Returns: string

The SQL text. For a parsed node this is exactly the text it was parsed from. More info.

node.equals(other)

other: SqlBase | undefined
Returns: boolean

Whether both are the same type and print the same text.

node.logicalEquals(other)

other: SqlBase | undefined
Returns: boolean

Like equals, but ignores whitespace, comments and keyword casing. More info.

node.walk(fn)

fn: Substitutor
Returns: SqlBase

Visits every node, parents before children, and replaces a node with whatever fn returns. A replacement is not walked into. Returning undefined stops the walk and returns the original. More info.

node.walkPostorder(fn)

fn: Substitutor
Returns: SqlBase

Like walk, but visits children before their parents.

node.some(fn), node.every(fn)

fn: (node: SqlBase, stack: SqlBase[]) => boolean
Returns: boolean

Whether any (or every) node in the tree matches.

node.find(fn), node.collect(fn)

fn: (node: SqlBase, stack: SqlBase[]) => node is T
Returns: T | undefined / T[]

The first matching node, or all of them.

node.getColumns(), node.getUsedColumnNames(), node.getFirstColumnName()

Returns: SqlColumn[] / string[] / string | undefined

The column references in the tree, their distinct names (sorted), or the first name.

node.getTables(), node.getUsedTableNames(), node.getFirstTableName(), node.getFirstSchema()

Returns: SqlTable[] / string[] / string | undefined / string | undefined

The table references in the tree, their distinct names (sorted), the first table name, or the first namespace used to qualify a table.

node.contains(thing), node.containsColumnName(name), node.containsFunction(name)

Returns: boolean

Whether the tree contains a node that equals thing, a column with that name, or a call to that function (compared in upper case).

node.prettify(options?)

options: PrettifyOptions
Returns: this

Reformats the whole tree in the default style. More info.

node.prettyTrim(maxLength)

maxLength: number
Returns: this

Shortens long literals and identifiers, for display.

node.addClarifyingParens()

Returns: this

Adds parentheses around an AND inside an OR and the other way round.

node.getParens(), node.hasParens(), node.changeParens(parens), node.addParens(), node.ensureParens(), node.removeOwnParenSpaces()

Read and change the parentheses around a node. ensureParens adds a pair only if there are none. More info.

node.getSpace(name, default?), node.changeSpace(name, space), node.changeSpaces(spaces), node.resetOwnSpacing()

Read and change the whitespace (and comments) in a node's named slots. More info.

node.apply(fn), node.applyIf(condition, thenFn, elseFn?), node.applyForEach(things, fn)

Call a function on the node, conditionally, or once per item (threading the result through), so edits can stay in one chain. More info.

SqlExpression

The base class of every expression, including queries. Extends SqlBase.

More info.

SqlExpression.parse(input)

input: string | SqlExpression
Returns: SqlExpression

Parses an expression or a query of any form. An already parsed expression is returned as is. More info.

SqlExpression.maybeParse(input)

input: string | SqlExpression
Returns: SqlExpression | undefined

Like parse, but returns undefined instead of throwing.

SqlExpression.wrap(value)

value: SqlExpression | LiteralValue
Returns: SqlExpression

Returns an expression as is and wraps a plain value with L.

SqlExpression.and(...expressions), SqlExpression.or(...expressions)

expressions: (SqlExpression | undefined)[]
Returns: SqlExpression

Joins the expressions with AND (or OR), skipping undefined and no-op TRUE (or FALSE) and flattening nested lists. One expression is returned as is, none gives TRUE (or FALSE). More info.

SqlExpression.add(...), .subtract(...), .multiply(...), .divide(...), .concat(...)

expressions: (SqlExpression | undefined)[]
Returns: SqlExpression

Arithmetic and ||, skipping undefined.

SqlExpression.fromTimeExpressionAndInterval(time, interval)

time: SqlExpression
interval: string | string[]
Returns: SqlExpression

start <= time AND time < end for an ISO interval like '2024-01-01/2024-02-01', or an OR of those for a list. More info.

SqlExpression.arrayOfLiterals(values)

values: LiteralValue[]
Returns: SqlExpression

ARRAY[...] of literals.

expression.equal(rhs), .unequal(rhs), .lessThan(rhs), .greaterThan(rhs), .lessThanOrEqual(rhs), .greaterThanOrEqual(rhs)

rhs: SqlExpression | LiteralValue
Returns: SqlComparison

=, <>, <, >, <=, >=. More info.

expression.isNull(), .isNotNull(), .isDistinctFrom(rhs), .isNotDistinctFrom(rhs)

Returns: SqlComparison

expression.in(values), .notIn(values)

values: (SqlExpression | LiteralValue)[]
Returns: SqlComparison

expression.like(pattern, escape?)

pattern: SqlExpression | string
escape: SqlExpression | string
Returns: SqlComparison

expression.between(start, end), .notBetween(start, end), .betweenSymmetric(start, end), .notBetweenSymmetric(start, end)

start, end: SqlExpression | LiteralValue
Returns: SqlComparison

expression.not()

Returns: SqlUnary

Wraps in NOT.

expression.negate()

Returns: SqlExpression

The logical opposite, flipping the operator where possible (= to <>, IN to NOT IN, IS NULL to IS NOT NULL, ...). More info.

expression.and(...expressions), .or(...expressions)

expressions: SqlExpression[]
Returns: SqlExpression

Same as the static versions, with this first.

expression.add(...), .subtract(...), .multiply(...), .divide(...), .concat(...)

expressions: SqlExpression[]
Returns: SqlExpression

expression.cast(type)

type: SqlType | string
Returns: SqlExpression

CAST(expression AS type).

expression.access(...path)

path: (string | number)[]
Returns: SqlColonAccess

Colon access, expression:a.b[0]. The expression gets parens unless it is a term. On a SqlColonAccess it extends the path (v:a becomes v:a.b).

expression.infixCast(type)

type: SqlType | string
Returns: SqlInfixCast

Infix cast, expression::type. The expression gets parens unless it is a term, a colon access or another infix cast.

expression.as(alias, forceQuotes?)

alias: string | RefName
forceQuotes: boolean
Returns: SqlAlias

Adds an alias. More info.

expression.setAlias(alias, forceQuotes?)

alias: string | RefName | undefined
Returns: SqlExpression

Sets the alias, or removes it when alias is undefined.

expression.ifUnnamedAliasAs(alias, forceQuotes?)

Returns: SqlExpression

Adds an alias only if there is none.

expression.getOutputName()

Returns: string | undefined

The name of the result column this expression produces as a select expression: the alias, the name of a bare column, the column an infix cast casts (x::BIGINT is "x") or the last field of a colon access (v:a.b is "b"). Druid drops the last two names when the select list has a * or another column of that name, which query.getOutputColumns() takes into account.

expression.getUnderlyingExpression(), expression.changeUnderlyingExpression(expression)

Returns: SqlExpression

The expression under an alias, or replace it (keeping the alias).

expression.toOrderByExpression(direction?)

direction: 'ASC' | 'DESC'
Returns: SqlOrderByExpression

expression.decomposeViaAnd(options?), expression.decomposeViaOr(options?)

options: DecomposeViaOptions
Returns: SqlExpression[]

The parts of an AND (or OR), or [expression] if it is not one. More info.

expression.filterAnd(fn)

fn: (ex: SqlExpression) => boolean
Returns: SqlExpression | undefined

Keeps the parts of an AND for which fn is true.

expression.removeColumnFromAnd(column)

column: string
Returns: SqlExpression | undefined

Removes the parts of an AND that use the column.

expression.flatten(op?)

Returns: SqlExpression

Flattens nested lists of the same operator: (a AND b) AND c becomes a AND b AND c.

expression.fillPlaceholders(values)

values: (SqlExpression | LiteralValue)[]
Returns: SqlExpression

Replaces ? placeholders, in order. More info.

expression.addFilterToAggregations(filter, knownAggregations)

filter: SqlExpression
knownAggregations: string[]
Returns: SqlExpression

Adds FILTER (WHERE filter) to every aggregation call. More info.

SqlQueryBase

The base class of every query. Extends SqlExpression.

More info.

SqlQueryBase.parse(input), SqlQueryBase.maybeParse(input)

input: string | SqlQueryBase
Returns: SqlQueryBase / SqlQueryBase | undefined

Parses any kind of query. parse throws Provided SQL was not a query for an expression that is not one.

SqlQueryBase.isPhonyOutputName(name)

Returns: boolean

Whether a name is one of Druid's made up EXPR$n names.

Output columns

Every kind of query answers these. TABLE t and FROM t answer like SELECT *, and a query whose output columns can not be told from its text (VALUES, a pipe query) answers with none. More info.

Method Returns
query.getSelectExpressionsArray() readonly SqlExpression[]
query.getSelectExpressionForIndex(index) SqlExpression | undefined
query.isValidSelectIndex(index) boolean
query.getOutputColumns() string[]
query.getSelectIndexForOutputColumn(name) number (-1 if none)
query.getSelectIndexForExpression(ex, allowAliasReferences) number
query.getSelectIndexesForColumn(column) number[]
query.isRealOutputColumnAtSelectIndex(index) boolean
query.hasStarInSelect() boolean
query.getOrderByForSelectIndex(index), query.getOrderByForOutputColumn(name) SqlOrderByExpression | undefined
query.getOrderedSelectExpressions(), query.getOrderedOutputColumns() SqlExpression[], string[]

Filters and grouping

Method Returns
query.hasWhere(), query.hasHaving() boolean
query.getWhereExpression(), query.getHavingExpression() SqlExpression | undefined
query.getEffectiveWhereExpression(), query.getEffectiveHavingExpression() SqlExpression (TRUE if none)
query.hasGroupBy() boolean
query.getGroupByExpressions() readonly SqlExpression[] | undefined, as written
query.getGroupingExpressions() SqlExpression[], with references resolved
query.getGroupingExpressionInfos() ExpressionInfo[]
query.isGroupedSelectIndex(index), query.isGroupedOutputColumn(name) boolean
query.getGroupedSelectExpressions(), query.getGroupedOutputColumns() SqlExpression[], string[]
query.getGroupedSelectIndexesForColumn(column) number[]
query.isAggregateSelectIndex(index), query.isAggregateOutputColumn(name) boolean
query.getAggregateSelectExpressions(), query.getAggregateOutputColumns() SqlExpression[], string[]

query.getContext(), query.hasContext()

Returns: Record<string, any> / boolean

The context set by the query's SET statements.

query.changeContext(context)

context: Record<string, any> | undefined
Returns: this

Replaces the SET statements. undefined or {} removes them. More info.

query.changeContextStatements(statements)

statements: SqlSetStatement[] | SeparatedArray<SqlSetStatement> | undefined
Returns: this

query.explain, query.changeExplain(explain), query.makeExplain()

explain: boolean
Returns: this

Adds or removes EXPLAIN PLAN FOR.

query.getInsertIntoTable(), query.changeInsertIntoTable(table)

table: SqlExpression | string | undefined

INSERT INTO table. changeInsertClause(clause) works on the whole clause.

query.getReplaceIntoTable(), query.changeReplaceIntoTable(table)

table: SqlExpression | string | undefined

REPLACE INTO table OVERWRITE ALL. changeReplaceClause(clause) works on the whole clause, for OVERWRITE WHERE ... use SqlReplaceClause.create(table, where).

query.getIngestTable()

Returns: SqlExpression | undefined

The INSERT or REPLACE target, if any.

query.changePartitionedByClause(clause), query.changeClusteredByClause(clause), query.changeClusteredByExpressions(expressions)

Set or remove (undefined) PARTITIONED BY and CLUSTERED BY. More info.

query.getOrderByClause(), query.changeOrderByClause(clause)

Returns: SqlOrderByClause | undefined / this

query.hasOrderBy(), query.getOrderByExpressions()

Returns: boolean / readonly SqlOrderByExpression[]

query.changeOrderByExpressions(expressions), query.changeOrderByExpression(expression)

expressions: SqlOrderByExpression[] | undefined
Returns: this

Replaces the ORDER BY list (undefined or [] removes it). More info.

query.addOrderBy(expression)

expression: SqlOrderByExpression
Returns: this

Adds a sort as the first one.

query.getOrderByForExpression(expression)

expression: SqlExpression
Returns: SqlOrderByExpression | undefined

query.getLimitValue(), query.hasLimit(), query.changeLimitValue(limit)

limit: number | SqlLiteral | undefined
Returns: number | undefined / boolean / this

undefined or Infinity removes the LIMIT, a negative number throws. More info.

query.getOffsetValue(), query.hasOffset(), query.changeOffsetValue(offset)

offset: number | SqlLiteral | undefined

query.getLimitClause(), query.changeLimitClause(clause), query.getOffsetClause(), query.changeOffsetClause(clause)

Work on the clauses themselves.

query.combineWithLimitClause(clause), query.combineWithOffsetClause(clause)

Returns: this

Applies another limit (keeping the smaller one) or offset (adding them up).

query.unionQuery, query.changeUnionQuery(query)

query: SqlQueryBase | undefined
Returns: this

The query after UNION ALL. More info.

query.flattenWith()

Returns: SqlQueryBase

Merges nested WITH clauses where that keeps the meaning. More info.

SqlQuery

A SELECT query. Extends SqlQueryBase.

More info.

SqlQuery.parse(input)

input: string | SqlQuery
Returns: SqlQuery

Parses a SELECT query. Throws Provided SQL was not a query for other kinds of query.

SqlQuery.maybeParse(input)

Returns: SqlQuery | undefined

SqlQuery.from(from), SqlQuery.selectStarFrom(from)

from: string | SqlExpression | SqlFromClause
Returns: SqlQuery

A query reading from a table or sub-query, with no select list (from) or SELECT * (selectStarFrom). SET statements of a sub-query move to the outer query.

The questions about its output columns, filters and grouping are on SqlQueryBase. The methods below change the query.

Select list

Method Returns
query.addSelect(ex, options?) this, see AddSelectOptions
query.changeSelect(index, ex) this
query.changeSelectExpressions(expressions) this
query.removeSelectIndex(index), query.removeSelectIndexes(indexes) this
query.removeOutputColumn(name) this
query.changeDecorator('DISTINCT' | 'ALL' | undefined) this

More info.

FROM and JOIN

Method Returns
query.hasFrom() boolean
query.getFromExpressions(), query.getFirstFromExpression() readonly SqlExpression[], SqlExpression | undefined
query.changeFromExpressions(expressions), query.changeFromClause(clause) this
query.hasJoin(), query.getJoins() boolean, readonly SqlJoinPart[]
query.addJoin(join) this
query.addLeftJoin(table, on), addRightJoin, addInnerJoin, addFullJoin this, on can be an array of conditions
query.addCrossJoin(table) this
query.removeAllJoins() this

More info.

WHERE and HAVING

Method Returns
query.addWhere(...ex), query.addHaving(...ex) this, AND-ed on
query.removeColumnFromWhere(column), query.removeFromHaving(column) this
query.changeWhereExpression(ex), query.changeHavingExpression(ex) this, undefined or TRUE removes
query.changeWhereClause(clause), query.changeHavingClause(clause) this

More info.

GROUP BY

Method Returns
query.addGroupBy(ex) this
query.changeGroupByExpressions(expressions), query.changeGroupByClause(clause) this, [] gives GROUP BY (), undefined removes

More info.

ORDER BY

Method Returns
query.removeOrderByForSelectIndex(index), query.removeOrderByForOutputColumn(name) this

More info.

WITH

Method Returns
query.getWithParts() readonly SqlWithPart[]
query.changeWithParts(parts), query.changeWithClause(clause) this
query.prependWith(name, query) this

query.inlineMaxDataTime(maxTime)

maxTime: number | undefined
Returns: SqlQuery

Replaces MAX_DATA_TIME() with a timestamp literal (the current time if maxTime is not given).

SqlPipesQuery

A pipe syntax query. Extends SqlQueryBase; its ORDER BY, LIMIT and OFFSET methods work on the trailing pipe operators.

More info.

SqlPipesQuery.create(query, pipeOperators)

query: SqlQueryBase
pipeOperators: SqlPipeOperator[]
Returns: SqlPipesQuery

pipesQuery.query, pipesQuery.changeQuery(query)

The starting query.

pipesQuery.withClause, pipesQuery.changeWithClause(withClause), pipesQuery.getWithParts()

The WITH in front of the starting query, which the operators can use the tables of. More info.

pipesQuery.getPipeOperators(), pipesQuery.getLastPipeOperator()

Returns: readonly SqlPipeOperator[] / SqlPipeOperator

pipesQuery.appendPipeOperator(op), pipesQuery.insertPipeOperator(index, op), pipesQuery.changePipeOperators(ops)

Returns: this

pipesQuery.removePipeOperator(index)

Returns: SqlQueryBase

Removing the last operator returns the starting query.

pipesQuery.unpipe()

Returns: SqlQuery

An equivalent query without pipes. Throws if a |> SET, |> DROP or |> RENAME has input with unknown columns. More info.

Other query classes

All of these extend SqlQueryBase.

  • SqlFromQuery: FROM ..., a whole FROM clause on its own (FROM t AS a JOIN u AS b ON ...). SqlFromQuery.create(from) (a table name, an expression or a SqlFromClause), optionalQuotes(table), fromClause, changeFromClause(fromClause), getFromExpressions(), getFirstFromExpression(), changeFromExpressions(expressions), hasJoin(), getJoins(), addJoin(join), removeAllJoins().
  • SqlTableQuery: TABLE t. SqlTableQuery.create(table), optionalQuotes(table), getTableName(), changeTableName(name), changeTable(table), getNamespaceName(), changeNamespace(namespace).
  • SqlValues: VALUES (...), (...). SqlValues.create(records), changeRecords(records).
  • SqlWithQuery: a WITH clause around a body that is not a plain SELECT: a query in parentheses, or a bare FROM, TABLE or VALUES. withClause, query, getWithParts(), changeWithParts(parts), prependWith(name, query), changeQuery(query).
  • SqlParensQuery: a query in parentheses with more of the statement outside of them, like (FROM t) UNION ALL (FROM u) or (SELECT ...) ORDER BY x. SqlParensQuery.create(query), query, changeQuery(query). A statement that is only a query in parentheses parses to that query.

Expression classes

The classes an expression parses into, and their own methods, are listed in Expressions. They are SqlColumn, SqlTable, SqlNamespace, SqlStar, SqlLiteral, SqlPlaceholder, SqlInterval, SqlType, SqlFunction, SqlComparison, SqlMulti, SqlUnary, SqlAlias, SqlCase, SqlRecord, SqlLabeledExpression, SqlKeyValue, SqlColonAccess and SqlInfixCast, plus the query classes above.

Types

LiteralValue

null | boolean | number | bigint | string | Date

A plain value that can become a SqlLiteral.

AddSelectOptions

Property Type Description
insertIndex number | 'last' | 'last-grouping' Where to insert. Defaults to 'last'.
addToGroupBy 'start' | 'end' Also group by the new column.
groupByExpression SqlExpression Group by this instead of the column's index.
addToOrderBy 'start' | 'end' Also order by the new column.
orderByExpression SqlOrderByExpression Order by this instead of the column's index.
direction 'ASC' | 'DESC' The direction for addToOrderBy.

DecomposeViaOptions

Property Type Description
flatten boolean Also split nested ANDs (or ORs).
preserveParens boolean Keep the parentheses around each part.

PrettifyOptions

Property Type Description
keywordCasing 'preserve' Keep the casing of keywords.
clarifyingParens 'disable' Do not add clarifying parentheses.

Substitutor

(node: SqlBase, stack: SqlBase[]) => SqlBase | undefined

The callback of walk and walkPostorder. stack holds the node's ancestors, nearest first.

ExpressionInfo

{ expression: SqlExpression, selectIndex: number, outputColumn?: string, orderByExpression?: SqlOrderByExpression }

Returned by getGroupingExpressionInfos(). selectIndex is -1 for a grouping expression that is not in the select list.


Top: Table of contents