import { parseExactJson } from '../exact-json.ts'; // The kernel's ClickHouse® SQL engine — deterministic, over rows a pack supplies (Tinybird's Data Sources and pipe nodes, // PostHog's events and persons). // // ── WHY AN ENGINE AND NOT A LOOKUP TABLE ──────────────────────────────────────────────────── // A Tinybird Pipe IS its SQL, and a HogQL query is ClickHouse SQL: the query a consumer writes tomorrow must be answered // by executing it, never by a per-query answer. So SQL is parsed into an AST and evaluated over the rows the pack's // catalog holds; coverage is a claim about the GRAMMAR and the FUNCTION LIBRARY, not about a list of blessed queries. // Anything outside them fails the way ClickHouse fails (an error naming the unknown function or the syntax), never with // a guessed answer. A pack keeps its own front: Tinybird's templates, HogQL's tables and property access. // // ── THE MODELED GRAMMAR ───────────────────────────────────────────────────────────────────── // query ::= select (UNION ALL select)* [FORMAT name] // select ::= [WITH (expr AS name | name AS (query)) , …] // SELECT [DISTINCT] item, … [,] // [FROM table_expr (join | , table_expr)*] // [PREWHERE expr] [WHERE expr] [GROUP BY expr, …] [HAVING expr] // [ORDER BY expr [ASC|DESC] [NULLS FIRST|LAST], …] [LIMIT n [OFFSET m] | LIMIT m, n] [OFFSET m] // table_expr ::= (name | (query)) [FINAL] [[AS] alias] // join ::= [GLOBAL] [ANY|ALL|SEMI|ANTI] [INNER|LEFT|RIGHT|FULL|CROSS] [OUTER] [ANY|ALL] JOIN // table_expr (ON expr | USING (col, …) | USING col) // expr ::= ClickHouse operators (OR AND NOT, = == != <> < <= > >=, [NOT] LIKE/ILIKE, [NOT] IN, // IS [NOT] NULL, [NOT] BETWEEN, ||, + - * / %, unary -, x[i]), literals, arrays // `[…]`, tuples, `CASE`, `INTERVAL n unit`, `CAST(x AS T)`, lambdas `x -> …`, // scalar subqueries, and an `AS alias` on any sub-expression. // Names resolve as ClickHouse's analyzer does: a SELECT alias is visible in every clause and wins // over a column of the same name, except inside its own definition (`toLowCardinality(country) // AS country`); `WITH expr AS name` defines a query-wide constant. // // ── MODELED SEMANTICS ─────────────────────────────────────────────────────────────────────── // • JOIN defaults to ALL strictness; ANY keeps the first match. A non-matching side is filled // with its columns' type defaults (ClickHouse's `join_use_nulls = 0`), which is why // `COALESCE(x.col, 0)` and a default `0` both read as zero. // • FINAL over a ReplacingMergeTree keeps, per sorting key, the row with the greatest version // column (the last inserted on a tie) and drops rows whose is-deleted column is 1. // • An un-grouped aggregate returns exactly one row even over zero rows; `count()` is UInt64. // • `arrayJoin(arr)` in the SELECT list multiplies each row by the array's elements. // • Comparisons with NULL are NULL, and WHERE keeps only true rows. A string literal meeting a // DateTime is parsed in that DateTime's zone. // // `statistics.elapsed` is DERIVED from the scan (`rows_read * 1e-6 + 1.23e-4`), never timed: a // wall-clock number would make every verify non-deterministic. import { digest } from '../signing.ts'; import { AggState, baseType, ChMap, castDateTime, fromStored, civilFromDays, compareValues, daysFromCivil, DDate, defaultOf, DT, formatDateTimePattern, instantOf, Interval, isFloatType, isIntegerType, isNullableType, isNumberType, isUnsignedType, parseDateText, SERVER_TZ, toOutput, typeArgs, typeHead, typeScale, typeZone, valueKey, valueKeyAs, valuesEqual, valueToText, wallOf, type IntervalUnit, aggKind, makeDT, normInt, stringifyJson, toBigInt, wrapInt, } from './values.ts'; import { isModeledSchemaType, type ClickHouseColumn } from './types.ts'; import { ClickHouseError } from './values.ts'; export { ClickHouseError }; function fail(message: string): never { throw new ClickHouseError(message); } // ── lexer ─────────────────────────────────────────────────────────────────────────────────── type Tok = | { k: 'word'; v: string; up: string } | { k: 'qid'; v: string } // `quoted` or "quoted" identifier | { k: 'num'; v: number | bigint; text: string } | { k: 'str'; v: string } | { k: 'op'; v: string } | { k: 'end' }; function unescapeClickHouseString(body: string): string { let out = ''; for (let i = 0; i < body.length; i++) { const c = body[i]!; if (c !== '\\') { out += c; continue; } const e = body[++i]; if (e === undefined) break; switch (e) { case 'n': out += '\n'; break; case 't': out += '\t'; break; case 'r': out += '\r'; break; case '0': out += '\0'; break; case 'b': out += '\b'; break; case 'f': out += '\f'; break; case 'a': out += '\x07'; break; case 'v': out += '\v'; break; case 'e': out += '\x1b'; break; case 'x': { out += String.fromCharCode(Number.parseInt(body.slice(i + 1, i + 3), 16)); i += 2; break; } case '\\': case "'": case '"': case '`': case '/': case '=': out += e; break; // ClickHouse keeps the backslash of an unknown escape (`\%` and `\_` stay LIKE escapes). default: out += `\\${e}`; } } return out; } function lex(sql: string): Tok[] { const out: Tok[] = []; let i = 0; const n = sql.length; while (i < n) { const c = sql[i]!; if (/\s/.test(c)) { i++; continue; } if (c === '-' && sql[i + 1] === '-') { while (i < n && sql[i] !== '\n') i++; continue; } if (c === '#' && (sql[i + 1] === ' ' || sql[i + 1] === '!')) { while (i < n && sql[i] !== '\n') i++; continue; } if (c === '/' && sql[i + 1] === '*') { const end = sql.indexOf('*/', i + 2); i = end < 0 ? n : end + 2; continue; } if (c === "'") { let j = i + 1; let body = ''; for (;;) { if (j >= n) fail('Syntax error: unterminated string literal'); const d = sql[j]!; if (d === '\\') { body += d + (sql[j + 1] ?? ''); j += 2; continue; } if (d === "'") { if (sql[j + 1] === "'") { body += "\\'"; j += 2; continue; } break; } body += d; j++; } out.push({ k: 'str', v: unescapeClickHouseString(body) }); i = j + 1; continue; } if (c === '`' || c === '"') { const end = sql.indexOf(c, i + 1); if (end < 0) fail('Syntax error: unterminated quoted identifier'); out.push({ k: 'qid', v: sql.slice(i + 1, end) }); i = end + 1; continue; } if (/[0-9]/.test(c) || (c === '.' && /[0-9]/.test(sql[i + 1] ?? '') && !prevIsValue(out))) { const m = /^(0x[0-9a-fA-F]+|\d+\.?\d*(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?)/.exec(sql.slice(i))!; const text = m[0]; // An integer literal is exact: beyond 2^53 it is a bigint (ClickHouse reads it as UInt64/Int64). const isInt = text.startsWith('0x') || /^\d+$/.test(text); out.push({ k: 'num', v: isInt ? normInt(BigInt(text)) : Number(text), text }); i += text.length; continue; } if (/[A-Za-z_]/.test(c)) { let j = i + 1; while (j < n && /[A-Za-z0-9_$]/.test(sql[j]!)) j++; const v = sql.slice(i, j); out.push({ k: 'word', v, up: v.toUpperCase() }); i = j; continue; } const three = sql.slice(i, i + 3); const two = sql.slice(i, i + 2); if (three === '<=>') { out.push({ k: 'op', v: three }); i += 3; continue; } if (['==', '!=', '<>', '<=', '>=', '||', '->', '::'].includes(two)) { out.push({ k: 'op', v: two }); i += 2; continue; } if ('()[]{},.;=<>+-*/%?:'.includes(c)) { out.push({ k: 'op', v: c }); i++; continue; } fail(`Syntax error: unexpected character '${c}'`); } out.push({ k: 'end' }); return out; } /** ClickHouse's type for an integer literal: the smallest UInt that holds it, or Int when negative. */ function literalIntType(v: number | bigint): string { const n = BigInt(v); if (n >= 0n) return n < 256n ? 'UInt8' : n < 65536n ? 'UInt16' : n < 4294967296n ? 'UInt32' : n < 18446744073709551616n ? 'UInt64' : n < (1n << 128n) ? 'UInt128' : 'UInt256'; return n >= -128n ? 'Int8' : n >= -32768n ? 'Int16' : n >= -2147483648n ? 'Int32' : n >= -(1n << 63n) ? 'Int64' : n >= -(1n << 127n) ? 'Int128' : 'Int256'; } function prevIsValue(out: Tok[]): boolean { const p = out[out.length - 1]; return p !== undefined && (p.k === 'word' || p.k === 'qid' || (p.k === 'op' && (p.v === ')' || p.v === ']'))); } // ── AST ───────────────────────────────────────────────────────────────────────────────────── export type Expr = | { k: 'lit'; v: unknown; type: string; text: string } | { k: 'id'; parts: string[] } | { k: 'star'; qualifier?: string } | { k: 'fn'; name: string; args: Expr[]; params?: Expr[]; distinct?: boolean } | { k: 'lambda'; params: string[]; body: Expr } | { k: 'bin'; op: string; a: Expr; b: Expr } | { k: 'not'; a: Expr } | { k: 'neg'; a: Expr } | { k: 'isnull'; a: Expr; not: boolean } | { k: 'between'; a: Expr; lo: Expr; hi: Expr; not: boolean } | { k: 'case'; operand?: Expr; whens: Array<[Expr, Expr]>; else?: Expr } | { k: 'alias'; name: string; e: Expr } | { k: 'subquery'; q: Query } | { k: 'array'; items: Expr[] } | { k: 'tuple'; items: Expr[] } | { k: 'index'; a: Expr; i: Expr } | { k: 'interval'; n: Expr; unit: IntervalUnit } | { k: 'cast'; e: Expr; type: string } /** A ClickHouse query parameter `{name: Type}` (what `tb_secret` renders at publish). */ | { k: 'param'; name: string; type: string }; type JoinKind = 'inner' | 'left' | 'right' | 'full' | 'cross'; type Strictness = 'all' | 'any' | 'semi' | 'anti'; export type TableSource = { kind: 'table'; name: string } | { kind: 'sub'; query: Query }; export type FromItem = { source: TableSource; final: boolean; alias?: string; join?: { kind: JoinKind; strictness: Strictness; on?: Expr; using?: string[] }; }; export type OrderItem = { e: Expr; desc: boolean; nullsFirst: boolean }; export type WithItem = { name: string; expr?: Expr; query?: Query }; export type Select = { with: WithItem[]; distinct: boolean; items: Expr[]; from: FromItem[]; prewhere?: Expr; where?: Expr; groupBy: Expr[]; having?: Expr; orderBy: OrderItem[]; limit?: Expr; offset?: Expr; }; export type Query = { selects: Select[]; format?: string }; // ── parser ────────────────────────────────────────────────────────────────────────────────── const CLAUSE_WORDS = new Set([ 'FROM', 'WHERE', 'PREWHERE', 'GROUP', 'ORDER', 'LIMIT', 'HAVING', 'UNION', 'FORMAT', 'SETTINGS', 'OFFSET', 'EXCEPT', 'INTERSECT', 'INTO', 'WINDOW', 'QUALIFY', 'WITH', 'SELECT', ]); const TABLE_ALIAS_STOP = new Set([ ...CLAUSE_WORDS, 'LEFT', 'RIGHT', 'INNER', 'FULL', 'CROSS', 'JOIN', 'ANY', 'ALL', 'SEMI', 'ANTI', 'ASOF', 'GLOBAL', 'ARRAY', 'ON', 'USING', 'FINAL', 'SAMPLE', 'AS', 'OUTER', 'PASTE', 'LOCAL', ]); const INTERVAL_UNITS: Record = { MILLISECOND: 'millisecond', MILLISECONDS: 'millisecond', SECOND: 'second', SECONDS: 'second', MINUTE: 'minute', MINUTES: 'minute', HOUR: 'hour', HOURS: 'hour', DAY: 'day', DAYS: 'day', WEEK: 'week', WEEKS: 'week', MONTH: 'month', MONTHS: 'month', QUARTER: 'quarter', QUARTERS: 'quarter', YEAR: 'year', YEARS: 'year', }; // The tokens after a FROM that make it a column named `from` (ClickHouse's ParserExpressionImpl::operators_table, plus the // comma, a second FROM and an explicit alias its trailing-comma check tests first). const FROM_COLUMN_OPS = new Set([',', '->', '?', ':', '==', '!=', '<=>', '<>', '<=', '>=', '<', '>', '=', '~', '~*', '!~', '!~*', '||', '+', '-', '−', '*', '/', '%', '.', '[', '::']); const FROM_COLUMN_WORDS = new Set(['FROM', 'AS', 'OR', 'AND', 'IS', 'BETWEEN', 'LIKE', 'ILIKE', 'REGEXP', 'IN', 'MOD', 'DIV']); class Parser { private i = 0; constructor(private readonly t: Tok[]) {} private peek(o = 0): Tok { return this.t[this.i + o] ?? { k: 'end' }; } private next(): Tok { return this.t[this.i++] ?? { k: 'end' }; } private isWord(w: string, o = 0): boolean { const t = this.peek(o); return t.k === 'word' && t.up === w; } private isOp(v: string, o = 0): boolean { const t = this.peek(o); return t.k === 'op' && t.v === v; } private acceptWord(w: string): boolean { if (this.isWord(w)) { this.i++; return true; } return false; } private acceptOp(v: string): boolean { if (this.isOp(v)) { this.i++; return true; } return false; } /** Whether the FROM at the cursor is a column named `from` rather than the FROM clause: ClickHouse's trailing-comma * test reads it so when the next token is a comma, a second FROM, `AS` or one of its operators_table entries. */ private fromIsColumn(): boolean { const t = this.peek(1); if (t.k === 'op') return FROM_COLUMN_OPS.has(t.v); if (t.k !== 'word') return false; if (t.up === 'NOT') return this.isWord('BETWEEN', 2) || this.isWord('LIKE', 2) || this.isWord('ILIKE', 2) || this.isWord('IN', 2); if (t.up === 'GLOBAL') return this.isWord('IN', 2) || this.isWord('NOT', 2); if (t.up === 'AT') return this.isWord('TIME', 2); return FROM_COLUMN_WORDS.has(t.up); } private expectWord(w: string): void { if (!this.acceptWord(w)) this.syntax(`expected ${w}`); } private expectOp(v: string): void { if (!this.acceptOp(v)) this.syntax(`expected '${v}'`); } private syntax(what: string): never { const t = this.peek(); const near = t.k === 'end' ? 'end of query' : t.k === 'word' || t.k === 'qid' || t.k === 'op' ? `'${t.v}'` : t.k === 'num' ? t.text : `'${t.v}'`; return fail(`Syntax error: ${what}, near ${near}`); } private name(): string { const t = this.next(); if (t.k === 'word' || t.k === 'qid') return t.v; this.i--; return this.syntax('expected identifier'); } parseQuery(): Query { const q = this.query(); this.acceptOp(';'); if (this.peek().k !== 'end') this.syntax('unexpected trailing input'); return q; } private query(): Query { const selects: Select[] = [this.select()]; while (this.isWord('UNION')) { this.i++; if (!this.acceptWord('ALL')) { if (this.acceptWord('DISTINCT')) fail('UNION DISTINCT is not supported by this twin'); fail('UNION without ALL is not supported by this twin (ClickHouse requires a union mode)'); } selects.push(this.select()); } let format: string | undefined; if (this.acceptWord('FORMAT')) format = this.name(); if (this.isWord('SETTINGS')) fail('SETTINGS clauses are not supported by this twin'); return { selects, ...(format !== undefined ? { format } : {}) }; } private select(): Select { if (this.acceptOp('(')) { const inner = this.query(); this.expectOp(')'); if (inner.selects.length !== 1) fail('parenthesised UNION is not supported by this twin'); return inner.selects[0]!; } const withItems: WithItem[] = []; if (this.acceptWord('WITH')) { do { // `name AS (SELECT …)` is a common table expression; anything else is `expr AS name`. if ((this.peek().k === 'word' || this.peek().k === 'qid') && this.isWord('AS', 1) && this.isOp('(', 2) && (this.isWord('SELECT', 3) || this.isWord('WITH', 3))) { const name = this.name(); this.i++; this.expectOp('('); const query = this.query(); this.expectOp(')'); withItems.push({ name, query }); } else { const e = this.expr(); if (e.k !== 'alias') { if (e.k === 'id' && e.parts.length === 1) fail('WITH without AS is not supported by this twin'); fail('WITH expressions need an alias'); } withItems.push({ name: e.name, expr: e.e }); } } while (this.acceptOp(',')); } this.expectWord('SELECT'); const distinct = this.acceptWord('DISTINCT'); if (this.isWord('TOP')) fail('SELECT TOP is not supported by this twin'); const items: Expr[] = []; // A trailing comma may end the list: ClickHouse allows `SELECT a, b, FROM t` (ClickHouse/ClickHouse#48438, "Allow // trailing commas in expression list of SELECT query"), and Dub's v3_usage pipe renders one when grouped. Its parser // (ExpressionListParsers.cpp) takes the comma as trailing only at the "End of query" (the end, or its `;`) or before // a FROM, and then eliminates "WITH 1 AS from SELECT 2, from", "SELECT to, from FROM table", "SELECT to, from AS // alias FROM table" and "SELECT to, from + to, from IN [1,2,3], FROM table": a FROM followed by a comma, a second // FROM, an explicit alias or an operator is a column named `from`. Its test 02676_trailing_commas runs `SELECT 1,;` // and `SELECT n, FROM (SELECT 1 AS n)`; a comma before `)` is none of these and stays a syntax error. const listEnds = (): boolean => this.peek().k === 'end' || this.isOp(';') || (this.isWord('FROM') && !this.fromIsColumn()); do { items.push(this.selectItem()); } while (this.acceptOp(',') && !listEnds()); const sel: Select = { with: withItems, distinct, items, from: [], groupBy: [], orderBy: [] }; if (this.acceptWord('FROM')) sel.from = this.fromClause(); if (this.isWord('ARRAY') && this.isWord('JOIN', 1)) fail('ARRAY JOIN is not supported by this twin'); if (this.acceptWord('PREWHERE')) sel.prewhere = this.expr(); if (this.acceptWord('WHERE')) sel.where = this.expr(); if (this.acceptWord('GROUP')) { this.expectWord('BY'); if ((this.isWord('ROLLUP') || this.isWord('CUBE')) && this.isOp('(', 1)) fail(`GROUP BY ${(this.peek() as { v: string }).v}(…) is not supported by this twin`); if (this.isWord('GROUPING') && this.isWord('SETS', 1)) fail('GROUP BY GROUPING SETS is not supported by this twin'); do sel.groupBy.push(this.expr()); while (this.acceptOp(',')); if (this.isWord('WITH')) fail('GROUP BY … WITH ROLLUP/CUBE/TOTALS is not supported by this twin'); } if (this.acceptWord('HAVING')) sel.having = this.expr(); if (this.isWord('WINDOW') || this.isWord('QUALIFY')) fail(`${(this.peek() as { v: string }).v} is not supported by this twin`); if (this.acceptWord('ORDER')) { this.expectWord('BY'); do { const e = this.expr(); let desc = false; if (this.acceptWord('DESC') || this.acceptWord('DESCENDING')) desc = true; else if (this.acceptWord('ASC') || this.acceptWord('ASCENDING')) desc = false; let nullsFirst = false; if (this.acceptWord('NULLS')) { if (this.acceptWord('FIRST')) nullsFirst = true; else { this.expectWord('LAST'); nullsFirst = false; } } if (this.isWord('COLLATE') || this.isWord('WITH')) fail('ORDER BY … COLLATE / WITH FILL is not supported by this twin'); sel.orderBy.push({ e, desc, nullsFirst }); } while (this.acceptOp(',')); } if (this.acceptWord('LIMIT')) { const first = this.expr(); if (this.acceptOp(',')) { sel.offset = first; sel.limit = this.expr(); } else { sel.limit = first; if (this.acceptWord('OFFSET')) sel.offset = this.expr(); } if (this.isWord('BY')) fail('LIMIT … BY is not supported by this twin'); if (this.isWord('WITH')) fail('LIMIT … WITH TIES is not supported by this twin'); } if (this.acceptWord('OFFSET')) { sel.offset = this.expr(); this.acceptWord('ROW') || this.acceptWord('ROWS'); if (this.acceptWord('FETCH')) fail('OFFSET … FETCH is not supported by this twin'); } return sel; } private selectItem(): Expr { const e = this.expr(); if (e.k === 'alias') return e; // An implicit alias: `toLowCardinality(country) country`. const t = this.peek(); if ((t.k === 'word' && !CLAUSE_WORDS.has(t.up) && t.up !== 'AS') || t.k === 'qid') { this.i++; return { k: 'alias', name: t.v, e }; } return e; } private fromClause(): FromItem[] { const items: FromItem[] = [this.tableExpr()]; for (;;) { if (this.acceptOp(',')) { items.push({ ...this.tableExpr(), join: { kind: 'cross', strictness: 'all' } }); continue; } const start = this.i; let strictness: Strictness | undefined; let kind: JoinKind | undefined; let sawJoinWord = false; for (let guard = 0; guard < 6; guard++) { if (this.acceptWord('GLOBAL') || this.acceptWord('LOCAL')) continue; if (this.isWord('ASOF')) fail('ASOF JOIN is not supported by this twin'); if (this.isWord('PASTE')) fail('PASTE JOIN is not supported by this twin'); if (this.acceptWord('ANY')) { strictness = 'any'; continue; } if (this.acceptWord('ALL')) { strictness = 'all'; continue; } if (this.acceptWord('SEMI')) { strictness = 'semi'; continue; } if (this.acceptWord('ANTI')) { strictness = 'anti'; continue; } if (this.acceptWord('INNER')) { kind = 'inner'; continue; } if (this.acceptWord('LEFT')) { kind = 'left'; continue; } if (this.acceptWord('RIGHT')) { kind = 'right'; continue; } if (this.acceptWord('FULL')) { kind = 'full'; continue; } if (this.acceptWord('CROSS')) { kind = 'cross'; continue; } if (this.acceptWord('OUTER')) continue; if (this.acceptWord('JOIN')) { sawJoinWord = true; break; } break; } if (!sawJoinWord) { this.i = start; break; } const item = this.tableExpr(); const join: NonNullable = { kind: kind ?? 'inner', strictness: strictness ?? 'all' }; if (join.kind !== 'cross') { if (this.acceptWord('ON')) join.on = this.expr(); else if (this.acceptWord('USING')) { const using: string[] = []; if (this.acceptOp('(')) { do using.push(this.name()); while (this.acceptOp(',')); this.expectOp(')'); } else { do using.push(this.name()); while (this.acceptOp(',')); } join.using = using; } else this.syntax('expected ON or USING after JOIN'); } items.push({ ...item, join }); } return items; } private tableExpr(): FromItem { let source: TableSource; if (this.acceptOp('(')) { const query = this.query(); this.expectOp(')'); source = { kind: 'sub', query }; } else { let name = this.name(); if (this.acceptOp('.')) name = `${name}.${this.name()}`; if (this.isOp('(')) fail(`table functions (${name}(…)) are not supported by this twin`); source = { kind: 'table', name }; } let final = this.acceptWord('FINAL'); let alias: string | undefined; if (this.acceptWord('AS')) alias = this.name(); else { const t = this.peek(); if ((t.k === 'word' && !TABLE_ALIAS_STOP.has(t.up)) || t.k === 'qid') { alias = t.v; this.i++; } } if (this.acceptWord('FINAL')) final = true; if (this.isWord('SAMPLE')) fail('SAMPLE is not supported by this twin'); return { source, final, ...(alias !== undefined ? { alias } : {}) }; } // ── expressions ── expr(allowAlias = true): Expr { // A lambda: `x -> body` or `(x, y) -> body`. if ((this.peek().k === 'word' || this.peek().k === 'qid') && this.isOp('->', 1)) { const p = this.name(); this.i++; return { k: 'lambda', params: [p], body: this.expr() }; } if (this.isOp('(')) { let j = 1; const params: string[] = []; let ok = true; for (;;) { const t = this.peek(j); if (t.k !== 'word' && t.k !== 'qid') { ok = false; break; } params.push(t.v); j++; if (this.isOp(',', j)) { j++; continue; } if (this.isOp(')', j)) { j++; break; } ok = false; break; } if (ok && this.isOp('->', j)) { this.i += j + 1; return { k: 'lambda', params, body: this.expr() }; } } let e = this.or(); if (this.isOp('?')) fail('the ternary operator ?: is not supported by this twin'); // Inside CAST(… AS T) the AS introduces the type, never an alias. while (allowAlias && this.acceptWord('AS')) e = { k: 'alias', name: this.name(), e }; return e; } private or(): Expr { let a = this.and(); while (this.acceptWord('OR')) a = { k: 'bin', op: 'or', a, b: this.and() }; return a; } private and(): Expr { let a = this.not(); while (this.acceptWord('AND')) a = { k: 'bin', op: 'and', a, b: this.not() }; return a; } private not(): Expr { if (this.isWord('NOT') && !this.isOp('(', 1)) { this.i++; return { k: 'not', a: this.not() }; } if (this.isWord('NOT') && this.isOp('(', 1)) { this.i++; const inner = this.comparison(); return { k: 'not', a: inner }; } return this.comparison(); } private comparison(): Expr { let a = this.concat(); for (;;) { const t = this.peek(); if (t.k === 'op' && ['=', '==', '!=', '<>', '<', '<=', '>', '>=', '<=>'].includes(t.v)) { this.i++; const op = t.v === '==' ? '=' : t.v === '<>' ? '!=' : t.v; a = { k: 'bin', op, a, b: this.concat() }; continue; } let neg = false; if (this.isWord('NOT') && (this.isWord('LIKE', 1) || this.isWord('ILIKE', 1) || this.isWord('IN', 1) || this.isWord('BETWEEN', 1))) { this.i++; neg = true; } if (this.acceptWord('LIKE')) { a = { k: 'bin', op: neg ? 'notlike' : 'like', a, b: this.concat() }; continue; } if (this.acceptWord('ILIKE')) { a = { k: 'bin', op: neg ? 'notilike' : 'ilike', a, b: this.concat() }; continue; } if (this.isWord('GLOBAL') && (this.isWord('IN', 1) || (this.isWord('NOT', 1) && this.isWord('IN', 2)))) { this.i++; continue; } if (this.acceptWord('IN')) { a = { k: 'bin', op: neg ? 'notin' : 'in', a, b: this.concat() }; continue; } if (this.acceptWord('BETWEEN')) { const lo = this.concat(); this.expectWord('AND'); const hi = this.concat(); a = { k: 'between', a, lo, hi, not: neg }; continue; } if (this.isWord('IS')) { this.i++; const isNot = this.acceptWord('NOT'); if (this.acceptWord('NULL')) { a = { k: 'isnull', a, not: isNot }; continue; } if (this.isWord('DISTINCT')) fail('IS [NOT] DISTINCT FROM is not supported by this twin'); this.syntax('expected NULL after IS'); } return a; } } private concat(): Expr { let a = this.additive(); while (this.acceptOp('||')) a = { k: 'fn', name: 'concat', args: [a, this.additive()] }; return a; } private additive(): Expr { let a = this.term(); for (;;) { if (this.acceptOp('+')) { a = { k: 'bin', op: '+', a, b: this.term() }; continue; } if (this.acceptOp('-')) { a = { k: 'bin', op: '-', a, b: this.term() }; continue; } return a; } } private term(): Expr { let a = this.unary(); for (;;) { if (this.acceptOp('*')) { a = { k: 'bin', op: '*', a, b: this.unary() }; continue; } if (this.acceptOp('/')) { a = { k: 'bin', op: '/', a, b: this.unary() }; continue; } if (this.acceptOp('%')) { a = { k: 'bin', op: '%', a, b: this.unary() }; continue; } if (this.isWord('DIV')) { this.i++; a = { k: 'fn', name: 'intDiv', args: [a, this.unary()] }; continue; } if (this.isWord('MOD')) { this.i++; a = { k: 'bin', op: '%', a, b: this.unary() }; continue; } return a; } } private unary(): Expr { if (this.acceptOp('-')) { const inner = this.unary(); if (inner.k === 'lit' && (typeof inner.v === 'number' || typeof inner.v === 'bigint')) { const v = typeof inner.v === 'bigint' ? normInt(-inner.v) : -inner.v; return { k: 'lit', v, type: inner.type === 'Float64' ? 'Float64' : literalIntType(v), text: `-${inner.text}` }; } return { k: 'neg', a: inner }; } if (this.acceptOp('+')) return this.unary(); return this.postfix(); } private postfix(): Expr { let e = this.primary(); for (;;) { if (this.isOp('[')) { this.i++; const idx = this.expr(); this.expectOp(']'); e = { k: 'index', a: e, i: idx }; continue; } if (this.isOp('::')) { this.i++; e = { k: 'cast', e, type: this.typeName() }; continue; } if (this.isOp('.') && this.peek(1).k === 'num') { fail('tuple element access (t.1) is not supported by this twin'); } return e; } } private typeName(): string { let s = this.name(); if (this.acceptOp('(')) { let depth = 1; s += '('; while (depth > 0) { const t = this.next(); if (t.k === 'end') return this.syntax('unterminated type'); if (t.k === 'op' && t.v === '(') depth++; if (t.k === 'op' && t.v === ')') { depth--; if (depth === 0) break; } s += t.k === 'str' ? `'${t.v}'` : t.k === 'num' ? t.text : t.v; if (t.k === 'op' && t.v === ',') s += ' '; } s += ')'; } return s; } private primary(): Expr { const t = this.next(); if (t.k === 'num') { const isFloat = /[.eE]/.test(t.text) && !t.text.startsWith('0x'); return { k: 'lit', v: t.v, type: isFloat ? 'Float64' : literalIntType(t.v), text: t.text }; } if (t.k === 'str') return { k: 'lit', v: t.v, type: 'String', text: `'${t.v}'` }; if (t.k === 'op') { if (t.v === '*') return { k: 'star' }; if (t.v === '(') { if (this.isWord('SELECT') || this.isWord('WITH')) { const q = this.query(); this.expectOp(')'); return { k: 'subquery', q }; } if (this.acceptOp(')')) return { k: 'tuple', items: [] }; const first = this.expr(); if (this.acceptOp(',')) { const items = [first]; do items.push(this.expr()); while (this.acceptOp(',')); this.expectOp(')'); return { k: 'tuple', items }; } this.expectOp(')'); return first; } if (t.v === '[') { const items: Expr[] = []; if (!this.acceptOp(']')) { do items.push(this.expr()); while (this.acceptOp(',')); this.expectOp(']'); } return { k: 'array', items }; } if (t.v === '{') { const name = this.name(); this.expectOp(':'); const type = this.typeName(); this.expectOp('}'); return { k: 'param', name, type }; } this.i--; return this.syntax('unexpected token'); } if (t.k === 'end') { this.i--; return this.syntax('unexpected end of query'); } if (t.k === 'qid') return this.identifierTail(t.v); // A word. switch (t.up) { case 'NULL': return { k: 'lit', v: null, type: 'Nullable(Nothing)', text: 'NULL' }; case 'TRUE': return { k: 'lit', v: true, type: 'Bool', text: 'true' }; case 'FALSE': return { k: 'lit', v: false, type: 'Bool', text: 'false' }; case 'CASE': return this.caseExpr(); case 'INTERVAL': { // `interval` is also an ordinary column name (`GROUP BY interval`); only a following // value makes it an interval literal. const nx = this.peek(); if (!(nx.k === 'num' || nx.k === 'str' || (nx.k === 'op' && (nx.v === '(' || nx.v === '-')))) break; const n = this.additive(); const u = this.next(); if (u.k !== 'word' || !INTERVAL_UNITS[u.up]) { this.i--; this.syntax('expected an interval unit'); } return { k: 'interval', n, unit: INTERVAL_UNITS[(u as { up: string }).up]! }; } case 'CAST': { if (!this.isOp('(')) break; this.i++; const e = this.expr(false); let type: string; if (this.acceptWord('AS')) type = this.typeName(); else { this.expectOp(','); const s = this.next(); if (s.k !== 'str') this.syntax('expected a type string'); type = (s as { v: string }).v; } this.expectOp(')'); return { k: 'cast', e, type }; } case 'EXISTS': return fail('EXISTS is not supported by this twin'); case 'DATE': case 'TIMESTAMP': if (this.peek().k === 'str') { const s = this.next() as { v: string }; return { k: 'fn', name: t.up === 'DATE' ? 'toDate' : 'toDateTime', args: [{ k: 'lit', v: s.v, type: 'String', text: `'${s.v}'` }] }; } break; default: break; } return this.identifierTail(t.v); } private identifierTail(first: string): Expr { if (this.isOp('(')) return this.call(first); const parts = [first]; while (this.isOp('.') && (this.peek(1).k === 'word' || this.peek(1).k === 'qid' || (this.peek(1).k === 'op' && (this.peek(1) as { v: string }).v === '*'))) { this.i++; const t = this.next(); if (t.k === 'op') return { k: 'star', qualifier: parts.join('.') }; parts.push((t as { v: string }).v); } return { k: 'id', parts }; } private call(name: string): Expr { this.expectOp('('); const args = this.argList(')'); // Parametric aggregate: quantile(0.5)(x). if (this.isOp('(')) { this.i++; const real = this.argList(')'); return { k: 'fn', name, params: args.list, args: real.list, ...(real.distinct ? { distinct: true } : {}) }; } if (this.isWord('OVER')) fail('window functions (OVER) are not supported by this twin'); return { k: 'fn', name, args: args.list, ...(args.distinct ? { distinct: true } : {}) }; } private argList(close: string): { list: Expr[]; distinct: boolean } { const list: Expr[] = []; let distinct = false; if (this.acceptOp(close)) return { list, distinct }; if (this.acceptWord('DISTINCT')) distinct = true; do list.push(this.expr()); while (this.acceptOp(',')); this.expectOp(close); return { list, distinct }; } private caseExpr(): Expr { let operand: Expr | undefined; if (!this.isWord('WHEN')) operand = this.expr(); const whens: Array<[Expr, Expr]> = []; while (this.acceptWord('WHEN')) { const c = this.expr(); this.expectWord('THEN'); whens.push([c, this.expr()]); } let otherwise: Expr | undefined; if (this.acceptWord('ELSE')) otherwise = this.expr(); this.expectWord('END'); if (whens.length === 0) this.syntax('CASE needs at least one WHEN'); return { k: 'case', ...(operand ? { operand } : {}), whens, ...(otherwise ? { else: otherwise } : {}) }; } } /** Parse one SQL statement (a SELECT, possibly with UNION ALL and a trailing FORMAT). */ export function parseSql(sql: string): Query { const trimmed = sql.trim(); // Leading comments (the `-- max_threads 2` a template hint renders) are not the statement. const statement = trimmed.replace(/^(?:\s+|--[^\n]*(?:\n|$)|#[ !][^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*/, ''); if (!/^(\(?\s*)*(SELECT|WITH)\b/i.test(statement)) { const word = /^\w+/.exec(statement)?.[0] ?? statement.slice(0, 12); fail(`Only SELECT queries are supported (got '${word}')`); } const q = new Parser(lex(trimmed)).parseQuery(); resolvePositional(q); return q; } /** * `GROUP BY 1` / `ORDER BY 2 DESC`: ClickHouse's `enable_positional_arguments` (on by default) makes * an integer literal there name the SELECT item at that 1-based position. */ function resolvePositional(q: Query): void { const visitQuery = (query: Query): void => query.selects.forEach(visitSelect); const visitSelect = (sel: Select): void => { const at = (e: Expr): Expr => { if (e.k !== 'lit' || !(typeof e.v === 'bigint' || (typeof e.v === 'number' && Number.isInteger(e.v))) || e.type === 'Float64') return e; const n = Number(e.v); if (n < 1 || n > sel.items.length) fail(`Positional argument number ${n} is out of bounds. Expected in range [1, ${sel.items.length}]`); const item = sel.items[n - 1]!; if (item.k === 'star') fail('Positional argument refers to an asterisk, which is not supported by this twin'); return item; }; sel.groupBy = sel.groupBy.map(at); sel.orderBy = sel.orderBy.map((o) => ({ ...o, e: at(o.e) })); for (const w of sel.with) if (w.query) visitQuery(w.query); for (const f of sel.from) if (f.source.kind === 'sub') visitQuery(f.source.query); }; visitQuery(q); } // ── relations and catalog ─────────────────────────────────────────────────────────────────── /** A relation; `declared` marks a Data Source's own columns (their types are schema, not inference). */ export type Relation = { columns: ClickHouseColumn[]; rows: unknown[][]; declared?: boolean }; /** Where a FROM name resolves: pipe nodes, Data Sources, CTEs. */ export interface Catalog { /** A named relation, or undefined when the name is unknown. `final` requests FINAL semantics. */ table(name: string, final: boolean): Relation | undefined; } type Source = { alias?: string; name?: string; columns: ClickHouseColumn[]; index: Map; declared?: boolean }; type JRow = unknown[][]; function makeSource(rel: Relation, alias: string | undefined, name: string | undefined): Source { const index = new Map(); rel.columns.forEach((c, i) => { if (!index.has(c.name)) index.set(c.name, i); }); return { ...(alias !== undefined ? { alias } : {}), ...(name !== undefined ? { name } : {}), columns: rel.columns, index, ...(rel.declared ? { declared: true } : {}) }; } // ── evaluation environment ────────────────────────────────────────────────────────────────── type Scope = { sources: Source[]; usingKeys: Set; aliases: Map; withExprs: Map; withCache: Map; exec: Executor; subCache: Map; outer?: Scope; }; type Env = { scope: Scope; row: JRow; group?: JRow[]; aliasCache: Map; evaluating: Set; lambda?: Map; aj?: Map; }; const AGG_BASES = new Set([ 'count', 'sum', 'avg', 'min', 'max', 'any', 'anylast', 'uniq', 'uniqexact', 'uniqcombined', 'uniqcombined64', 'uniqhll12', 'argmin', 'argmax', 'grouparray', 'grouparraysample', 'groupuniqarray', 'quantile', 'quantileexact', 'quantiles', 'quantilesexact', 'median', 'medianexact', 'countdistinct', ]); type AggregateName = { base: string; mode: 'plain' | 'state' | 'merge'; cond: boolean }; /** An aggregate function name with its combinators (`-If`, `-State`, `-Merge`), or undefined. */ function parseAggregate(name: string): AggregateName | undefined { let n = name.toLowerCase(); // "first_value … is an alias for any" (https://clickhouse.com/docs/sql-reference/aggregate-functions/reference/first_value): // the first value met, NULLs ignored as every aggregate ignores them if (n === 'first_value') n = 'any'; let mode: AggregateName['mode'] = 'plain'; if (n.endsWith('merge') && n.length > 5) { n = n.slice(0, -5); mode = 'merge'; } else if (n.endsWith('state') && n.length > 5) { n = n.slice(0, -5); mode = 'state'; } let cond = false; if (!AGG_BASES.has(n) && n.endsWith('if') && AGG_BASES.has(n.slice(0, -2))) { n = n.slice(0, -2); cond = true; } if (!AGG_BASES.has(n) || (cond && mode === 'merge')) return undefined; return { base: n, mode, cond }; } const isAggregateName = (name: string) => parseAggregate(name) !== undefined; /** The name an `AggregateFunction(…)` state carries: the function plus its parameters. */ function stateName(base: string, params: unknown[]): string { return params.length ? `${base}(${params.map(valueToText).join(',')})` : base; } /** The result type of an aggregate call (ClickHouse's, including the -Null / -State / -Merge rules). */ function aggregateType(e: Extract, T: (x: Expr) => string): string { const agg = parseAggregate(e.name)!; const { base } = agg; const a0 = e.args[0]; const params = (e.params ?? []).map((p) => (p.k === 'lit' ? p.v : exprText(p))); let argT = a0 && a0.k !== 'star' ? T(a0) : 'UInt64'; if (agg.mode === 'state') { const argTypes = e.args.slice(0, agg.cond ? -1 : undefined).map((x) => (x.k === 'star' ? 'UInt64' : T(x))); return `AggregateFunction(${stateName(base, params)}${argTypes.length ? `, ${argTypes.join(', ')}` : ''})`; } if (agg.mode === 'merge') argT = typeArgs(argT)[1] ?? 'String'; const inner = stripNullable(argT); let out: string; switch (base) { case 'count': case 'uniq': case 'uniqexact': case 'uniqcombined': case 'uniqcombined64': case 'uniqhll12': case 'countdistinct': return 'UInt64'; case 'grouparray': case 'grouparraysample': case 'groupuniqarray': return `Array(${inner})`; case 'sum': out = isFloatType(inner) ? 'Float64' : isUnsignedType(inner) ? 'UInt64' : 'Int64'; break; case 'avg': case 'quantile': case 'median': out = 'Float64'; break; case 'quantiles': return 'Array(Float64)'; case 'quantilesexact': return `Array(${inner})`; default: out = inner; } return isNullableType(argT) && agg.mode !== 'merge' ? `Nullable(${out})` : out; } function containsAggregate(e: Expr, aliases?: Map, seen = new Set()): boolean { switch (e.k) { case 'fn': if (isAggregateName(e.name)) return true; return e.args.some((a) => containsAggregate(a, aliases, seen)); case 'alias': return containsAggregate(e.e, aliases, seen); case 'bin': return containsAggregate(e.a, aliases, seen) || containsAggregate(e.b, aliases, seen); case 'not': case 'neg': return containsAggregate(e.a, aliases, seen); case 'isnull': return containsAggregate(e.a, aliases, seen); case 'between': return [e.a, e.lo, e.hi].some((x) => containsAggregate(x, aliases, seen)); case 'case': return (e.operand ? containsAggregate(e.operand, aliases, seen) : false) || e.whens.some(([a, b]) => containsAggregate(a, aliases, seen) || containsAggregate(b, aliases, seen)) || (e.else ? containsAggregate(e.else, aliases, seen) : false); case 'array': case 'tuple': return e.items.some((x) => containsAggregate(x, aliases, seen)); case 'index': return containsAggregate(e.a, aliases, seen) || containsAggregate(e.i, aliases, seen); case 'interval': return containsAggregate(e.n, aliases, seen); case 'cast': return containsAggregate(e.e, aliases, seen); case 'lambda': return containsAggregate(e.body, aliases, seen); case 'id': { if (!aliases || e.parts.length !== 1) return false; const name = e.parts[0]!; const target = aliases.get(name); if (!target || seen.has(name)) return false; seen.add(name); const r = containsAggregate(target, aliases, seen); seen.delete(name); return r; } default: return false; } } function collectAliases(e: Expr, out: Map): void { switch (e.k) { case 'alias': { const prev = out.get(e.name); // ClickHouse allows a name to alias the SAME expression twice, never two different ones. if (prev && !sameExpr(prev, e.e)) fail(`Different expressions with the same alias ${e.name}`); if (!prev) out.set(e.name, e.e); collectAliases(e.e, out); return; } case 'fn': e.args.forEach((a) => collectAliases(a, out)); return; case 'bin': collectAliases(e.a, out); collectAliases(e.b, out); return; case 'not': case 'neg': case 'isnull': collectAliases(e.a, out); return; case 'between': collectAliases(e.a, out); collectAliases(e.lo, out); collectAliases(e.hi, out); return; case 'case': if (e.operand) collectAliases(e.operand, out); e.whens.forEach(([a, b]) => { collectAliases(a, out); collectAliases(b, out); }); if (e.else) collectAliases(e.else, out); return; case 'array': case 'tuple': e.items.forEach((x) => collectAliases(x, out)); return; case 'index': collectAliases(e.a, out); collectAliases(e.i, out); return; case 'interval': collectAliases(e.n, out); return; case 'cast': collectAliases(e.e, out); return; default: return; } } function unalias(e: Expr): Expr { return e.k === 'alias' ? unalias(e.e) : e; } /** The output column name ClickHouse gives an expression. */ function exprName(e: Expr): string { switch (e.k) { case 'alias': return e.name; case 'id': return e.parts[e.parts.length - 1]!; case 'lit': return e.text; case 'star': return '*'; case 'fn': return `${e.name}${e.params ? `(${e.params.map(exprText).join(', ')})` : ''}(${e.distinct ? 'DISTINCT ' : ''}${e.args.map(exprText).join(', ')})`; default: return exprText(e); } } function exprText(e: Expr): string { switch (e.k) { case 'alias': return e.name; case 'id': return e.parts.join('.'); case 'lit': return e.text; case 'star': return e.qualifier ? `${e.qualifier}.*` : '*'; case 'fn': return `${e.name}${e.params ? `(${e.params.map(exprText).join(', ')})` : ''}(${e.distinct ? 'DISTINCT ' : ''}${e.args.map(exprText).join(', ')})`; case 'lambda': return `lambda(tuple(${e.params.join(', ')}), ${exprText(e.body)})`; case 'bin': { const names: Record = { '+': 'plus', '-': 'minus', '*': 'multiply', '/': 'divide', '%': 'modulo', '=': 'equals', '!=': 'notEquals', '<': 'less', '<=': 'lessOrEquals', '>': 'greater', '>=': 'greaterOrEquals', and: 'and', or: 'or', like: 'like', notlike: 'notLike', ilike: 'ilike', notilike: 'notILike', in: 'in', notin: 'notIn', '<=>': 'isNotDistinctFrom', }; return `${names[e.op] ?? e.op}(${exprText(e.a)}, ${exprText(e.b)})`; } case 'not': return `not(${exprText(e.a)})`; case 'neg': return `negate(${exprText(e.a)})`; case 'isnull': return `${e.not ? 'isNotNull' : 'isNull'}(${exprText(e.a)})`; case 'between': return `${e.not ? 'not' : ''}between(${exprText(e.a)}, ${exprText(e.lo)}, ${exprText(e.hi)})`; case 'case': return 'multiIf(…)'; case 'subquery': return '_subquery'; case 'array': return `[${e.items.map(exprText).join(', ')}]`; case 'tuple': return `(${e.items.map(exprText).join(', ')})`; case 'index': return `arrayElement(${exprText(e.a)}, ${exprText(e.i)})`; case 'interval': return `toInterval${e.unit[0]!.toUpperCase()}${e.unit.slice(1)}(${exprText(e.n)})`; case 'cast': return `CAST(${exprText(e.e)}, '${e.type}')`; case 'param': return `{${e.name}:${e.type}}`; } } function sameExpr(a: Expr, b: Expr): boolean { return JSON.stringify(unalias(a)) === JSON.stringify(unalias(b)); } // ── identifier resolution ─────────────────────────────────────────────────────────────────── function findColumn(scope: Scope, name: string): { s: number; c: number } | undefined { for (let s = 0; s < scope.sources.length; s++) { const c = scope.sources[s]!.index.get(name); if (c !== undefined) return { s, c }; } return undefined; } function findSource(scope: Scope, qualifier: string): number | undefined { const byAlias = scope.sources.findIndex((s) => s.alias === qualifier); if (byAlias >= 0) return byAlias; const byName = scope.sources.findIndex((s) => s.alias === undefined && s.name === qualifier); if (byName >= 0) return byName; const byTableName = scope.sources.findIndex((s) => s.name === qualifier); return byTableName >= 0 ? byTableName : undefined; } function resolveId(parts: string[], env: Env): unknown { const scope = env.scope; if (parts.length === 1) { const name = parts[0]!; if (env.lambda?.has(name)) return env.lambda.get(name); const alias = scope.aliases.get(name); if (alias && !env.evaluating.has(name)) { if (env.aliasCache.has(name)) return env.aliasCache.get(name); env.evaluating.add(name); try { const v = evalExpr(alias, env); env.aliasCache.set(name, v); return v; } finally { env.evaluating.delete(name); } } const col = findColumn(scope, name); if (col) return env.row[col.s]![col.c]; if (scope.withExprs.has(name)) return withValue(scope, name); if (scope.outer) { const outerEnv: Env = { scope: scope.outer, row: [], aliasCache: new Map(), evaluating: new Set() }; return resolveId(parts, outerEnv); } return fail(`Missing columns: '${name}' while processing query`); } const qualifier = parts.slice(0, -1).join('.'); const column = parts[parts.length - 1]!; const s = findSource(scope, qualifier); if (s !== undefined) { const c = scope.sources[s]!.index.get(column); if (c === undefined) { const whole = scope.sources[s]!.index.get(parts.join('.')); if (whole !== undefined) return env.row[s]![whole]; return fail(`Missing columns: '${parts.join('.')}' while processing query`); } return env.row[s]![c]; } // A column literally named `q.c` (a subquery's output), then the bare column. const whole = findColumn(scope, parts.join('.')); if (whole) return env.row[whole.s]![whole.c]; return resolveId([column], env); } function withValue(scope: Scope, name: string): unknown { if (scope.withCache.has(name)) return scope.withCache.get(name); const e = scope.withExprs.get(name)!; // A WITH constant sees the other WITH names but no row. const env: Env = { scope: { ...scope, sources: [], aliases: new Map() }, row: [], aliasCache: new Map(), evaluating: new Set([name]) }; const v = evalExpr(e, env); scope.withCache.set(name, v); return v; } // ── type inference (static) ───────────────────────────────────────────────────────────────── function columnType(scope: Scope, parts: string[], seen: Set): string | undefined { if (parts.length === 1) { const name = parts[0]!; const alias = scope.aliases.get(name); if (alias && !seen.has(name)) { seen.add(name); const t = typeOf(alias, scope, seen); seen.delete(name); return t; } const col = findColumn(scope, name); if (col) return scope.sources[col.s]!.columns[col.c]!.type; const w = scope.withExprs.get(name); if (w && !seen.has(name)) { seen.add(name); const t = typeOf(w, { ...scope, aliases: new Map() }, seen); seen.delete(name); return t; } return undefined; } const s = findSource(scope, parts.slice(0, -1).join('.')); if (s !== undefined) { const c = scope.sources[s]!.index.get(parts[parts.length - 1]!); return c === undefined ? undefined : scope.sources[s]!.columns[c]!.type; } const whole = findColumn(scope, parts.join('.')); if (whole) return scope.sources[whole.s]!.columns[whole.c]!.type; return columnType(scope, [parts[parts.length - 1]!], seen); } const stripNullable = (t: string) => { const b = baseType(t); return /^LowCardinality\(/.test(t) && !b.nullable ? t : b.base; }; const nullableOf = (t: string) => (isNullableType(t) || /^(Array|AggregateFunction|Nullable)\(/.test(t) ? t : `Nullable(${t.replace(/^LowCardinality\((.*)\)$/s, '$1')})`); function arrayElementType(t: string | undefined): string { if (!t) return 'String'; const { base } = baseType(t); return /^Array\(/.test(base) ? typeArgs(base)[0] ?? 'String' : 'String'; } function typeOf(e: Expr, scope: Scope, seen = new Set(), lambdaTypes?: Map): string { const T = (x: Expr) => typeOf(x, scope, seen, lambdaTypes); switch (e.k) { case 'lit': return e.type; case 'alias': { if (seen.has(e.name)) return T(e.e); seen.add(e.name); const t = T(e.e); seen.delete(e.name); return t; } case 'id': { if (e.parts.length === 1 && lambdaTypes?.has(e.parts[0]!)) return lambdaTypes.get(e.parts[0]!)!; return columnType(scope, e.parts, seen) ?? 'String'; } case 'star': return 'String'; case 'not': case 'isnull': case 'between': return 'UInt8'; case 'neg': { const t = T(e.a); return isUnsignedType(t) ? t.replace('UInt', 'Int') : t; } case 'bin': { if (['=', '!=', '<', '<=', '>', '>=', 'like', 'notlike', 'ilike', 'notilike', 'in', 'notin', 'and', 'or', '<=>'].includes(e.op)) return 'UInt8'; const a = T(e.a); const b = T(e.b); const ha = typeHead(a); if (ha === 'DateTime' || ha === 'DateTime64' || ha === 'Date' || ha === 'Date32') return stripNullable(a); if (e.op === '/') return 'Float64'; if (isFloatType(a) || isFloatType(b)) return 'Float64'; return 'Int64'; } case 'case': return e.whens.length ? T(e.whens[0]![1]) : 'String'; case 'subquery': return 'String'; case 'array': return `Array(${e.items.length ? stripNullable(T(e.items[0]!)) : 'Nothing'})`; case 'tuple': return `Tuple(${e.items.map(T).join(', ')})`; case 'index': return arrayElementType(T(e.a)); case 'interval': return `Interval${e.unit[0]!.toUpperCase()}${e.unit.slice(1)}`; case 'cast': case 'param': return e.type; case 'lambda': return 'Function'; case 'fn': return fnType(e, scope, seen, lambdaTypes); } } function fnType(e: Extract, scope: Scope, seen: Set, lambdaTypes?: Map): string { const T = (x: Expr) => typeOf(x, scope, seen, lambdaTypes); const name = e.name.toLowerCase(); const a0 = e.args[0]; if (isAggregateName(name)) return aggregateType(e, T); switch (name) { case 'length': return 'UInt64'; case 'if': return e.args[1] ? T(e.args[1]) : 'String'; case 'multiif': return e.args[1] ? T(e.args[1]) : 'String'; case 'coalesce': case 'ifnull': { const t = e.args.map(T).find((x) => !isNullableType(x)) ?? (a0 ? T(a0) : 'String'); return stripNullable(t); } case 'assumenotnull': return a0 ? stripNullable(T(a0)) : 'String'; case 'nullif': return nullableOf(a0 ? T(a0) : 'String'); case 'touuid': return 'UUID'; case 'touuidornull': return 'Nullable(UUID)'; case 'isnull': case 'isnotnull': case 'startswith': case 'endswith': case 'has': case 'hasany': case 'hasall': case 'empty': case 'notempty': case 'like': case 'match': case 'equals': case 'notequals': return 'UInt8'; case 'tolowcardinality': { const t = a0 ? T(a0) : 'String'; return /^LowCardinality/.test(t) ? t : `LowCardinality(${t})`; } case 'tostring': case 'concat': case 'replace': case 'replaceall': case 'replaceone': case 'replaceregexpall': case 'replaceregexpone': case 'lower': case 'upper': case 'lowerutf8': case 'upperutf8': case 'substring': case 'substr': case 'trim': case 'trimboth': case 'trimleft': case 'trimright': case 'encodeurlformcomponent': case 'decodeurlformcomponent': case 'encodeurlcomponent': case 'decodeurlcomponent': case 'extract': case 'extracturlparameter': case 'jsonextractstring': case 'jsonextractraw': case 'formatdatetime': case 'domain': case 'domainwithoutwww': case 'path': case 'cutquerystring': case 'leftpad': case 'rightpad': case 'reverse': case 'base64encode': case 'base64decode': case 'hex': return 'String'; case 'splitbystring': case 'splitbychar': case 'extracturlparameters': case 'extracturlparameternames': return 'Array(String)'; case 'mapfilter': return e.args[1] ? T(e.args[1]) : 'Map(String, String)'; case 'mapkeys': case 'mapvalues': { const m = a0 ? stripNullable(T(a0)) : 'Map(String, String)'; const [k, v] = typeArgs(m); return `Array(${(name === 'mapkeys' ? k : v) ?? 'String'})`; } case 'mapcontains': case 'mapcontainskey': return 'UInt8'; case 'totypename': return 'String'; case 'lengthutf8': case 'char_length': case 'position': case 'locate': return 'UInt64'; case 'greatest': case 'least': return a0 ? T(a0) : 'String'; case 'totimezone': { const tz = e.args[1]?.k === 'lit' ? String(e.args[1].v) : undefined; return tz ? `DateTime('${tz}')` : 'DateTime'; } case 'toyyyymmdd': return 'UInt32'; case 'toyyyymmddhhmmss': return 'UInt64'; case 'toquarter': return 'UInt8'; case 'todayofyear': return 'UInt16'; case 'tounixtimestamp64nano': return 'Int64'; case 'fromunixtimestamp64micro': case 'fromunixtimestamp64nano': { const tz = e.args[1]?.k === 'lit' ? String(e.args[1].v) : undefined; const scale = name.endsWith('micro') ? 6 : 9; return tz ? `DateTime64(${scale}, '${tz}')` : `DateTime64(${scale})`; } case 'tostartofinterval': case 'time_bucket': case 'date_bin': { const iv = e.args[1]; const unit = iv?.k === 'interval' ? iv.unit : iv?.k === 'fn' && /^tointerval/i.test(iv.name) ? iv.name.slice(10).toLowerCase() : 'second'; const argT = a0 ? stripNullable(T(a0)) : 'DateTime'; const tzLit = e.args[2]?.k === 'lit' ? String(e.args[2].v) : typeZone(argT); const zoned = (t: string) => (tzLit ? `${t}('${tzLit}')` : t); if (unit === 'millisecond') return tzLit ? `DateTime64(3, '${tzLit}')` : 'DateTime64(3)'; if (unit === 'week' || unit === 'month' || unit === 'quarter' || unit === 'year') return 'Date'; if (unit === 'day' && /^Date/.test(argT) && !/^DateTime/.test(argT)) return 'DateTime'; return zoned('DateTime'); } case 'tofloat64': case 'tofloat32': case 'tofloat64orzero': case 'round': case 'floor': case 'ceil': case 'jsonextractfloat': case 'sqrt': case 'exp': case 'log': case 'pow': case 'power': case 'divide': if (name === 'round' || name === 'floor' || name === 'ceil') return a0 ? stripNullable(T(a0)) : 'Float64'; return name === 'tofloat32' ? 'Float32' : 'Float64'; case 'abs': return a0 ? T(a0) : 'Float64'; case 'jsonextractint': return 'Int64'; case 'jsonextractbool': case 'jsonhas': return 'UInt8'; case 'tounixtimestamp64milli': case 'tounixtimestamp64micro': case 'datediff': case 'date_diff': case 'intdiv': return 'Int64'; case 'tounixtimestamp': return 'UInt32'; case 'toyyyymm': return 'UInt32'; case 'toyear': return 'UInt16'; case 'tomonth': case 'todayofmonth': case 'tohour': case 'tominute': case 'tosecond': case 'todayofweek': return 'UInt8'; case 'todatetime64': case 'todatetime64orzero': case 'parsedatetime64besteffort': case 'parsedatetime64besteffortornull': case 'parsedatetime64besteffortorzero': { const scale = e.args[1]?.k === 'lit' ? Number(e.args[1].v) : 3; const tz = e.args[2]?.k === 'lit' ? String(e.args[2].v) : undefined; const type = tz ? `DateTime64(${scale}, '${tz}')` : `DateTime64(${scale})`; return name.endsWith('ornull') ? `Nullable(${type})` : type; } case 'todatetime': case 'now': case 'tostartofday': case 'tostartofhour': case 'tostartofminute': case 'tostartoffiveminutes': case 'tostartoffifteenminutes': case 'tostartofsecond': case 'parsedatetimebesteffort': case 'parsedatetimebesteffortornull': { const tzArg = name === 'now' ? a0 : e.args[1]; const tz = tzArg?.k === 'lit' ? String(tzArg.v) : undefined; const type = tz ? `DateTime('${tz}')` : 'DateTime'; return name.endsWith('ornull') ? `Nullable(${type})` : type; } case 'now64': return 'DateTime64(3)'; case 'todate': case 'today': case 'tostartofmonth': case 'tostartofweek': case 'tostartofyear': case 'tostartofquarter': case 'tomonday': case 'yesterday': return 'Date'; case 'arrayjoin': return arrayElementType(a0 ? T(a0) : undefined); case 'arrayelement': return arrayElementType(a0 ? T(a0) : undefined); case 'array': return `Array(${a0 ? stripNullable(T(a0)) : 'Nothing'})`; case 'range': return 'Array(UInt64)'; case 'arrayfilter': case 'arraydistinct': case 'arraysort': case 'arrayreversesort': case 'arrayslice': case 'arrayreverse': case 'arrayconcat': case 'arraypushback': case 'arraypushfront': return name === 'arrayfilter' ? (e.args[1] ? T(e.args[1]) : 'Array(String)') : a0 ? T(a0) : 'Array(String)'; case 'arrayintersect': return a0 ? T(a0) : 'Array(String)'; case 'arraymap': { const lam = a0; const arrT = e.args[1] ? T(e.args[1]) : 'Array(String)'; if (lam?.k === 'lambda') { const lt = new Map(lambdaTypes ?? []); lam.params.forEach((p, i) => lt.set(p, arrayElementType(e.args[i + 1] ? T(e.args[i + 1]!) : arrT))); return `Array(${typeOf(lam.body, scope, seen, lt)})`; } return arrT; } case 'indexof': case 'arraycount': return 'UInt64'; case 'arraysum': return 'Float64'; default: { if (name.startsWith('tointerval')) return `Interval${e.name.slice(10)}`; const conv = /^to(u?int(?:8|16|32|64|128|256)|float(?:32|64))(orzero|ornull)?$/.exec(name); if (conv) { const t = conv[1]!.replace(/^u?int|^float/, (m) => (m === 'uint' ? 'UInt' : m === 'int' ? 'Int' : 'Float')); return conv[2] === 'ornull' ? `Nullable(${t})` : t; } return 'String'; } } } // ── scalar evaluation ─────────────────────────────────────────────────────────────────────── function truth(v: unknown): boolean | null { if (v === null || v === undefined) return null; if (typeof v === 'boolean') return v; if (typeof v === 'number') return v !== 0; if (typeof v === 'bigint') return v !== 0n; if (typeof v === 'string') { if (v === '' || v === '0') return false; const n = Number(v); if (!Number.isNaN(n)) return n !== 0; return fail(`Cannot convert string '${v}' to a boolean condition`); } return true; } function asNumber(v: unknown): number | null { if (v === null || v === undefined) return null; if (typeof v === 'number') return v; if (typeof v === 'bigint') return Number(v); if (typeof v === 'boolean') return v ? 1 : 0; if (v instanceof DT) return v.ms / 1000 + v.ns / 1e9; if (v instanceof DDate) return v.days; if (typeof v === 'string') { const n = Number(v); if (v.trim() === '' || Number.isNaN(n)) return fail(`Cannot parse number from string '${v}'`); return n; } return fail(`Illegal type for arithmetic: ${valueToText(v)}`); } /** An arithmetic operand that is an exact integer (a safe-integer number or a bigint)? */ const isExactInt = (v: unknown): v is number | bigint => typeof v === 'bigint' || (typeof v === 'number' && Number.isInteger(v)) || typeof v === 'boolean'; function likeToRegex(pattern: string, insensitive: boolean): RegExp { let re = '^'; for (let i = 0; i < pattern.length; i++) { const c = pattern[i]!; if (c === '\\' && i + 1 < pattern.length) { re += pattern[++i]!.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); continue; } if (c === '%') re += '[\\s\\S]*'; else if (c === '_') re += '[\\s\\S]'; else re += c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } return new RegExp(`${re}$`, insensitive ? 'i' : ''); } const LIKE_CACHE = new Map(); function likeMatch(value: string, pattern: string, insensitive: boolean): boolean { const key = `${insensitive ? 'i' : 's'}:${pattern}`; let re = LIKE_CACHE.get(key); if (!re) { re = likeToRegex(pattern, insensitive); LIKE_CACHE.set(key, re); } return re.test(value); } function addInterval(v: unknown, iv: Interval, sign: number): unknown { const n = iv.n * sign; if (v instanceof DDate) { if (iv.unit === 'day') return new DDate(v.days + n); if (iv.unit === 'week') return new DDate(v.days + 7 * n); if (iv.unit === 'month' || iv.unit === 'quarter' || iv.unit === 'year') { const months = iv.unit === 'month' ? n : iv.unit === 'quarter' ? 3 * n : 12 * n; const c = civilFromDays(v.days); return new DDate(addMonthsCivil(c.y, c.mo, c.d, months)); } return addInterval(castDateTime(v, 0, SERVER_TZ), iv, sign); } if (v instanceof DT) { const tz = v.tz ?? SERVER_TZ; switch (iv.unit) { case 'millisecond': return new DT(v.ms + n, v.scale, v.tz, v.ns); case 'second': return new DT(v.ms + n * 1000, v.scale, v.tz, v.ns); case 'minute': return new DT(v.ms + n * 60_000, v.scale, v.tz, v.ns); case 'hour': return new DT(v.ms + n * 3_600_000, v.scale, v.tz, v.ns); case 'day': case 'week': { const w = wallOf(v.ms, tz); const days = daysFromCivil(w.y, w.mo, w.d) + (iv.unit === 'day' ? n : 7 * n); const c = civilFromDays(days); return new DT(instantOf({ ...w, ...c }, tz), v.scale, v.tz, v.ns); } default: { const months = iv.unit === 'month' ? n : iv.unit === 'quarter' ? 3 * n : 12 * n; const w = wallOf(v.ms, tz); const c = civilFromDays(addMonthsCivil(w.y, w.mo, w.d, months)); return new DT(instantOf({ ...w, ...c }, tz), v.scale, v.tz, v.ns); } } } if (typeof v === 'string') return addInterval(castDateTime(v, 0), iv, sign); return fail(`Illegal types for interval arithmetic: ${valueToText(v)}`); } function addMonthsCivil(y: number, mo: number, d: number, months: number): number { const total = y * 12 + (mo - 1) + months; const ny = Math.floor(total / 12); const nm = total - ny * 12 + 1; const dim = new Date(Date.UTC(ny, nm, 0)).getUTCDate(); return daysFromCivil(ny, nm, Math.min(d, dim)); } function arithmetic(op: string, a: unknown, b: unknown): unknown { if (a === null || b === null || a === undefined || b === undefined) return null; if (b instanceof Interval && (op === '+' || op === '-')) return addInterval(a, b, op === '+' ? 1 : -1); if (a instanceof Interval && op === '+') return addInterval(b, a, 1); if ((a instanceof DT || a instanceof DDate) && typeof b === 'number' && (op === '+' || op === '-')) { // DateTime ± n is seconds; Date ± n is days. return a instanceof DT ? new DT(a.ms + (op === '+' ? 1 : -1) * b * 1000, a.scale, a.tz, a.ns) : new DDate(a.days + (op === '+' ? 1 : -1) * b); } if (op === '-' && a instanceof DT && b instanceof DT) return (a.ms - b.ms) / 1000 + (a.ns - b.ns) / 1e9; if (op === '-' && a instanceof DDate && b instanceof DDate) return a.days - b.days; // Integer arithmetic is exact (ClickHouse's Int64/UInt64 never round through a double). if (isExactInt(a) && isExactInt(b) && op !== '/') { const x = toBigInt(a); const y = toBigInt(b); if (op === '+') return normInt(x + y); if (op === '-') return normInt(x - y); if (op === '*') return normInt(x * y); if (op === '%') { if (y === 0n) return fail('Division by zero'); return normInt(x % y); } } const x = asNumber(a)!; const y = asNumber(b)!; switch (op) { case '+': return x + y; case '-': return x - y; case '*': return x * y; case '/': return x / y; case '%': { if (y === 0) return fail('Division by zero'); return x % y; } } return fail(`Unknown operator ${op}`); } function toSetKeys(v: unknown): unknown[] { if (Array.isArray(v)) return v; return [v]; } function evalIn(e: Extract, env: Env): unknown { const left = evalExpr(e.a, env); let members: unknown[]; const rhs = e.b; if (rhs.k === 'subquery') { let cached = env.scope.subCache.get(rhs) as unknown[] | undefined; if (!cached) { const rel = env.scope.exec.run(rhs.q, env.scope); cached = rel.rows.map((r) => (r.length === 1 ? r[0] : r)); env.scope.subCache.set(rhs, cached); } members = cached; } else if (rhs.k === 'tuple') { members = rhs.items.map((x) => evalExpr(x, env)); } else if (rhs.k === 'id' && rhs.parts.length === 1 && !findColumn(env.scope, rhs.parts[0]!) && !env.scope.aliases.has(rhs.parts[0]!) && !env.scope.withExprs.has(rhs.parts[0]!)) { // `x IN table_or_node` — the relation's first column. let cached = env.scope.subCache.get(rhs) as unknown[] | undefined; if (!cached) { const rel = env.scope.exec.table(rhs.parts[0]!, false, env.scope); cached = rel.rows.map((r) => r[0]); env.scope.subCache.set(rhs, cached); } members = cached; } else { members = toSetKeys(evalExpr(rhs, env)); } if (left === null || left === undefined) return null; // ClickHouse's `transform_null_in = 0`: NULL members never match. const hit = members.some((m) => m !== null && m !== undefined && valueKeyAs(m, left) === valueKey(left)); const negate = e.op === 'notin'; return hit !== negate ? 1 : 0; } export function evalExpr(e: Expr, env: Env): unknown { switch (e.k) { case 'lit': return e.v; case 'alias': { // Inside its own definition a name means the column, never the alias (`f(x) AS x`). if (env.evaluating.has(e.name)) return evalExpr(e.e, env); env.evaluating.add(e.name); try { return evalExpr(e.e, env); } finally { env.evaluating.delete(e.name); } } case 'id': return resolveId(e.parts, env); case 'star': return fail('* is only allowed in a SELECT list or count(*)'); case 'not': { const t = truth(evalExpr(e.a, env)); return t === null ? null : t ? 0 : 1; } case 'neg': { const v = evalExpr(e.a, env); if (v === null) return null; if (v instanceof Interval) return new Interval(v.unit, -v.n); if (typeof v === 'bigint') return normInt(-v); return -asNumber(v)!; } case 'isnull': { const v = evalExpr(e.a, env); return (v === null || v === undefined) !== e.not ? 1 : 0; } case 'between': { const v = evalExpr(e.a, env); const lo = evalExpr(e.lo, env); const hi = evalExpr(e.hi, env); if (v === null || lo === null || hi === null) return null; const r = compareValues(v, lo) >= 0 && compareValues(v, hi) <= 0; return r !== e.not ? 1 : 0; } case 'case': { if (e.operand) { const v = evalExpr(e.operand, env); for (const [w, t] of e.whens) { const c = evalExpr(w, env); if (v !== null && c !== null && valuesEqual(v, c)) return evalExpr(t, env); } } else { for (const [w, t] of e.whens) if (truth(evalExpr(w, env)) === true) return evalExpr(t, env); } return e.else ? evalExpr(e.else, env) : null; } case 'subquery': { if (env.scope.subCache.has(e)) return env.scope.subCache.get(e); const rel = env.scope.exec.run(e.q, env.scope); const v = rel.rows.length === 0 ? defaultOf(rel.columns[0]?.type ?? 'Nullable(String)') : rel.rows[0]!.length === 1 ? rel.rows[0]![0] : rel.rows[0]; env.scope.subCache.set(e, v); return v; } case 'array': return e.items.map((x) => evalExpr(x, env)); case 'tuple': return e.items.map((x) => evalExpr(x, env)); case 'index': { const arr = evalExpr(e.a, env); const idx = asNumber(evalExpr(e.i, env)); if (arr === null || idx === null) return null; if (!Array.isArray(arr)) return fail(`arrayElement: first argument must be an array, got ${valueToText(arr)}`); return arrayAt(arr, idx); } case 'interval': { const n = asNumber(evalExpr(e.n, env)); return n === null ? null : new Interval(e.unit, n); } case 'cast': return castTo(evalExpr(e.e, env), e.type); // No request supplies ClickHouse query parameters (this twin stores no Workspace secrets); // publish-time analysis types the parameter without a value, as the vendor's check does. case 'param': if (env.scope.exec.validating) return defaultOf(e.type); return fail(`Substitution \`${e.name}\` is not set`); case 'lambda': return fail('a lambda is only allowed as a higher-order function argument'); case 'bin': { if (e.op === 'and') { const a = truth(evalExpr(e.a, env)); if (a === false) return 0; const b = truth(evalExpr(e.b, env)); if (b === false) return 0; return a === null || b === null ? null : 1; } if (e.op === 'or') { const a = truth(evalExpr(e.a, env)); if (a === true) return 1; const b = truth(evalExpr(e.b, env)); if (b === true) return 1; return a === null || b === null ? null : 0; } if (e.op === 'in' || e.op === 'notin') return evalIn(e, env); const a = evalExpr(e.a, env); const b = evalExpr(e.b, env); if (['+', '-', '*', '/', '%'].includes(e.op)) return arithmetic(e.op, a, b); if (e.op === '<=>') return (a === null && b === null) || (a !== null && b !== null && valuesEqual(a, b)) ? 1 : 0; if (a === null || b === null || a === undefined || b === undefined) return null; if (e.op === 'like' || e.op === 'notlike' || e.op === 'ilike' || e.op === 'notilike') { const r = likeMatch(valueToText(a), valueToText(b), e.op.includes('ilike')); return (e.op.startsWith('not') ? !r : r) ? 1 : 0; } const c = compareValues(a, b); switch (e.op) { case '=': return c === 0 ? 1 : 0; case '!=': return c !== 0 ? 1 : 0; case '<': return c < 0 ? 1 : 0; case '<=': return c <= 0 ? 1 : 0; case '>': return c > 0 ? 1 : 0; case '>=': return c >= 0 ? 1 : 0; } return fail(`Unknown operator ${e.op}`); } case 'fn': return evalFunction(e, env); } } function arrayAt(arr: unknown[], idx: number): unknown { const i = idx > 0 ? idx - 1 : arr.length + idx; if (idx === 0 || i < 0 || i >= arr.length) { const sample = arr.find((x) => x !== null && x !== undefined); if (typeof sample === 'number') return 0; if (sample instanceof DT) return new DT(0, sample.scale, sample.tz); if (Array.isArray(sample)) return []; return ''; } return arr[i]; } function castTo(v: unknown, type: string): unknown { if (v === null || v === undefined) return isNullableType(type) ? null : fail(`Cannot convert NULL value to non-Nullable type ${type}`); const h = typeHead(type); if (h === 'String' || h === 'FixedString') return valueToText(v); if (h === 'DateTime' || h === 'DateTime64') return castDateTime(v, typeScale(type), typeZone(type)); if (h === 'Date' || h === 'Date32') return toDateValue(v); if (h === 'Bool' || h === 'Boolean') return truth(v) === true; if (isIntegerType(type)) return toIntegerOf(v, h); if (isFloatType(type)) return asNumber(v); if (h === 'Array') { if (!Array.isArray(v)) return fail(`CAST: cannot convert ${valueToText(v)} to ${type}`); const inner = typeArgs(type)[0] ?? 'String'; return v.map((x) => castTo(x, inner)); } return v; } /** * `toIntN(x)` / `CAST(x AS IntN)`: an integer wrapped to N bits. A string must be integer text * (ClickHouse: "Cannot parse string '5.5' as Int32"); a float truncates toward zero. */ function toIntegerOf(v: unknown, type: string): number | bigint { if (typeof v === 'string' && !/^[+-]?\d+$/.test(v)) { fail(`Cannot parse string '${v}' as ${type}: syntax error at begin of string. Note: there are to${type}OrZero and to${type}OrNull functions, which returns zero/NULL instead of throwing exception`); } return wrapInt(toBigInt(v, type), type); } /** `toIntNOrZero` / `toIntNOrNull` / `toFloatNOrZero|OrNull`: the parse, or 0 / NULL when it fails. */ function toNumberOrElse(v: unknown, type: string, orNull: boolean): unknown { const miss = orNull ? null : 0; if (v === null) return null; const text = typeof v === 'string' ? v : valueToText(v); if (/^Float/.test(type)) { if (!/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$|^[+-]?(inf|nan)$/i.test(text)) return miss; return Number(text.replace(/inf/i, 'Infinity')); } if (!/^[+-]?\d+$/.test(text)) return miss; const n = BigInt(text); if (type.startsWith('U') && n < 0n) return miss; const w = wrapInt(n, type); return BigInt(w) === n ? w : miss; } function toDateValue(v: unknown, tz?: string): DDate { if (v instanceof DDate) return v; if (v instanceof DT) { const w = wallOf(v.ms, tz ?? v.tz); return new DDate(daysFromCivil(w.y, w.mo, w.d)); } if (typeof v === 'number') return v > 65535 ? toDateValue(new DT(v * 1000, 0), tz) : new DDate(v); if (typeof v === 'string') { const d = parseDateText(v); if (d === undefined) return fail(`Cannot parse Date from String '${v}'`); return new DDate(d); } return fail(`Cannot convert ${valueToText(v)} to Date`); } function tzArg(e: Extract, i: number, env: Env): string | undefined { const a = e.args[i]; if (!a) return undefined; const v = evalExpr(a, env); if (v === null) return undefined; const s = valueToText(v); wallOf(0, s); // validates the zone return s; } function toDateTimeArg(v: unknown): DT { if (v instanceof DT) return v; return castDateTime(v, 0); } function startOf(v: unknown, unit: 'second' | 'minute' | 'fiveMinutes' | 'fifteenMinutes' | 'hour' | 'day', tz: string | undefined): DT | null { if (v === null) return null; const dt = v instanceof DDate ? castDateTime(v, 0, tz) : toDateTimeArg(v); const zone = tz ?? dt.tz ?? SERVER_TZ; const w = wallOf(dt.ms, zone); let wall = { ...w, ms: 0 }; if (unit === 'minute') wall = { ...wall, s: 0 }; if (unit === 'fiveMinutes') wall = { ...wall, s: 0, mi: w.mi - (w.mi % 5) }; if (unit === 'fifteenMinutes') wall = { ...wall, s: 0, mi: w.mi - (w.mi % 15) }; if (unit === 'hour') wall = { ...wall, s: 0, mi: 0 }; if (unit === 'day') wall = { ...wall, s: 0, mi: 0, h: 0 }; return new DT(instantOf(wall, zone), 0, tz ?? dt.tz); } /** * `toStartOfInterval(t, INTERVAL n unit[, tz])`, per ClickHouse's DateLUT (checked against * clickhouse-local 26.10): sub-second and second/minute buckets count from the epoch in UTC ticks; * hour buckets floor the wall-clock hour of the local day; day buckets count local days from the * epoch and return a DateTime; weeks (Monday-aligned from 1970-01-05), months (from 1970-01), * quarters and years (from year 0) return a Date. A Date argument accepts day units and above. */ function startOfInterval(v: unknown, iv: Interval, tz: string | undefined): DT | DDate { const n = Math.trunc(iv.n); if (n <= 0) return fail('Value for second argument of function toStartOfInterval must be positive'); const isDate = v instanceof DDate; if (isDate && ['millisecond', 'second', 'minute', 'hour'].includes(iv.unit)) { return fail('Illegal interval kind for argument data type Date'); } const dt = v instanceof DDate ? castDateTime(v, 0, tz) : v instanceof DT ? v : castDateTime(v, 0, tz); const zone = tz ?? dt.tz ?? SERVER_TZ; const outTz = tz ?? dt.tz; switch (iv.unit) { case 'millisecond': { const step = BigInt(n); const ms = BigInt(dt.ms); const floored = (ms >= 0n ? ms / step : -((-ms + step - 1n) / step)) * step; return new DT(Number(floored), 3, outTz); } case 'second': case 'minute': { const step = (iv.unit === 'second' ? 1000 : 60_000) * n; return new DT(Math.floor(dt.ms / step) * step, 0, outTz); } case 'hour': { const w = wallOf(dt.ms, zone); return new DT(instantOf({ ...w, h: w.h - (w.h % n), mi: 0, s: 0, ms: 0 }, zone), 0, outTz); } case 'day': { const w = wallOf(dt.ms, zone); const days = daysFromCivil(w.y, w.mo, w.d); const c = civilFromDays(Math.floor(days / n) * n); return new DT(instantOf({ ...c, h: 0, mi: 0, s: 0, ms: 0 }, zone), 0, isDate ? undefined : outTz); } case 'week': { const days = toDateValue(dt, zone).days; const week = Math.floor((days - 4) / 7); return new DDate(4 + Math.floor(week / n) * n * 7); } default: { const c = civilFromDays(toDateValue(dt, zone).days); if (iv.unit === 'year') return new DDate(daysFromCivil(Math.floor(c.y / n) * n, 1, 1)); const months = iv.unit === 'quarter' ? 3 * n : n; const idx = (c.y - 1970) * 12 + (c.mo - 1); const start = Math.floor(idx / months) * months; return new DDate(daysFromCivil(1970 + Math.floor(start / 12), (start % 12 + 12) % 12 + 1, 1)); } } } function relativeNumber(v: DT | DDate, unit: string, tz: string | undefined): number { const dt = v instanceof DDate ? castDateTime(v, 0, tz) : v; const zone = tz ?? dt.tz ?? SERVER_TZ; const w = wallOf(dt.ms, zone); const days = daysFromCivil(w.y, w.mo, w.d); switch (unit) { case 'year': case 'yy': case 'yyyy': return w.y; case 'quarter': case 'qq': case 'q': return w.y * 4 + Math.floor((w.mo - 1) / 3); case 'month': case 'mm': case 'm': return w.y * 12 + w.mo - 1; case 'week': case 'wk': case 'ww': return Math.floor((days + 3) / 7); // weeks start Monday case 'day': case 'dd': case 'd': return days; case 'hour': case 'hh': case 'h': return days * 24 + w.h; case 'minute': case 'mi': case 'n': return (days * 24 + w.h) * 60 + w.mi; case 'second': case 'ss': case 's': return Math.floor(dt.ms / 1000); case 'millisecond': return dt.ms; default: return fail(`dateDiff: unknown unit '${unit}'`); } } function jsonPathValue(json: unknown, keys: unknown[]): unknown { let cur: unknown; if (typeof json === 'string') { try { cur = parseExactJson(json, (digits) => BigInt(digits)); } catch { return undefined; } } else cur = json; for (const k of keys) { if (cur === null || typeof cur !== 'object') return undefined; if (Array.isArray(cur)) { const i = typeof k === 'number' ? (k > 0 ? k - 1 : cur.length + k) : Number.NaN; cur = cur[i]; } else { cur = (cur as Record)[valueToText(k)]; } if (cur === undefined) return undefined; } return cur; } function encodeFormComponent(s: string): string { return encodeURIComponent(s).replace(/%20/g, '+').replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); } function decodeComponent(s: string, plusIsSpace: boolean): string { const src = plusIsSpace ? s.replace(/\+/g, ' ') : s; // ClickHouse decodes byte-wise and leaves malformed escapes as-is. const bytes: number[] = []; for (let i = 0; i < src.length; i++) { const c = src[i]!; if (c === '%' && /^[0-9a-fA-F]{2}$/.test(src.slice(i + 1, i + 3))) { bytes.push(Number.parseInt(src.slice(i + 1, i + 3), 16)); i += 2; continue; } for (const b of Buffer.from(c, 'utf8')) bytes.push(b); } return Buffer.from(bytes).toString('utf8'); } function extractUrlParameter(url: string, name: string): string { const q = url.indexOf('?'); if (q < 0) return ''; let query = url.slice(q + 1); const hash = query.indexOf('#'); if (hash >= 0) query = query.slice(0, hash); for (const pair of query.split('&')) { const eq = pair.indexOf('='); const k = eq < 0 ? pair : pair.slice(0, eq); if (k === name) return eq < 0 ? '' : pair.slice(eq + 1); } return ''; } function extractUrlParameterNames(url: string): string[] { const q = url.indexOf('?'); if (q < 0) return []; let query = url.slice(q + 1); const hash = query.indexOf('#'); if (hash >= 0) query = query.slice(0, hash); return query.split('&').filter((pair) => pair !== '').map((pair) => { const eq = pair.indexOf('='); return eq < 0 ? pair : pair.slice(0, eq); }); } function callLambda(fnArg: Expr | undefined, env: Env, values: unknown[]): unknown { if (!fnArg || fnArg.k !== 'lambda') return fail('higher-order functions need a lambda as their first argument'); const lambda = new Map(env.lambda ?? []); fnArg.params.forEach((p, i) => lambda.set(p, values[i])); return evalExpr(fnArg.body, { ...env, lambda }); } function argArrays(e: Extract, env: Env, from: number): unknown[][] | null { const arrays: unknown[][] = []; for (let i = from; i < e.args.length; i++) { const v = evalExpr(e.args[i]!, env); if (v === null) return null; if (!Array.isArray(v)) return fail(`${e.name}: argument ${i + 1} must be an array`); arrays.push(v); } return arrays; } function evalFunction(e: Extract, env: Env): unknown { const name = e.name.toLowerCase(); if (isAggregateName(name)) return evalAggregate(e, env); const A = (i: number) => evalExpr(e.args[i] ?? fail(`${e.name}: missing argument ${i + 1}`), env); const argc = (n: number, m = n) => { if (e.args.length < n || e.args.length > m) fail(`Number of arguments for function ${e.name} doesn't match: passed ${e.args.length}`); }; switch (name) { // conditionals case 'if': { argc(3); const c = truth(A(0)); return c === true ? A(1) : A(2); } case 'multiif': { if (e.args.length < 3 || e.args.length % 2 === 0) fail(`Invalid number of arguments for function multiIf`); for (let i = 0; i + 1 < e.args.length; i += 2) if (truth(A(i)) === true) return A(i + 1); return A(e.args.length - 1); } case 'coalesce': { for (let i = 0; i < e.args.length; i++) { const v = A(i); if (v !== null && v !== undefined) return v; } return null; } case 'ifnull': { argc(2); const v = A(0); return v === null ? A(1) : v; } case 'nullif': { argc(2); const a = A(0); const b = A(1); return a !== null && b !== null && valuesEqual(a, b) ? null : a; } case 'isnull': { argc(1); return A(0) === null ? 1 : 0; } case 'isnotnull': { argc(1); return A(0) === null ? 0 : 1; } case 'assumenotnull': { argc(1); const v = A(0); return v === null ? defaultOf(typeOf(e.args[0]!, env.scope).replace(/^Nullable\((.*)\)$/, '$1')) : v; } case 'tolowcardinality': case 'identity': case 'materialize': { argc(1); return A(0); } case 'equals': { argc(2); const a = A(0); const b = A(1); return a === null || b === null ? null : valuesEqual(a, b) ? 1 : 0; } case 'notequals': { argc(2); const a = A(0); const b = A(1); return a === null || b === null ? null : valuesEqual(a, b) ? 0 : 1; } case 'greatest': case 'least': { let best: unknown = null; for (let i = 0; i < e.args.length; i++) { const v = A(i); if (v === null) return null; if (best === null || (name === 'greatest' ? compareValues(v, best) > 0 : compareValues(v, best) < 0)) best = v; } return best; } // strings case 'concat': { const parts = e.args.map((_, i) => A(i)); if (parts.some((p) => p === null)) return null; return parts.map(valueToText).join(''); } case 'tostring': { argc(1, 2); const v = A(0); if (v === null) return null; if (v instanceof DT && e.args[1]) return valueToText(v.withTz(tzArg(e, 1, env))); return valueToText(v); } // a UUID is its canonical text (8-4-4-4-12 hexadecimal digits, lowercased); text that is not one fails, or is NULL for // the OrNull form (https://clickhouse.com/docs/sql-reference/functions/type-conversion-functions#touuid) case 'touuid': case 'touuidornull': { argc(1); const v = A(0); if (v === null) return null; const t = valueToText(v).trim(); if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)) return t.toLowerCase(); return e.name.toLowerCase() === 'touuidornull' ? null : fail(`Cannot parse uuid ${t}: Cannot parse UUID from String`); } case 'length': case 'char_length': case 'lengthutf8': { argc(1); const v = A(0); if (v === null) return null; if (Array.isArray(v)) return v.length; const s = valueToText(v); return name === 'length' ? Buffer.byteLength(s, 'utf8') : [...s].length; } case 'empty': case 'notempty': { argc(1); const v = A(0); if (v === null) return null; const isEmpty = Array.isArray(v) ? v.length === 0 : valueToText(v) === ''; return (name === 'empty' ? isEmpty : !isEmpty) ? 1 : 0; } // lower/upper change ASCII letters only (ClickHouse works on bytes); the UTF8 variants are Unicode. case 'lower': case 'lcase': { argc(1); const v = A(0); return v === null ? null : valueToText(v).replace(/[A-Z]/g, (c) => c.toLowerCase()); } case 'upper': case 'ucase': { argc(1); const v = A(0); return v === null ? null : valueToText(v).replace(/[a-z]/g, (c) => c.toUpperCase()); } case 'lowerutf8': { argc(1); const v = A(0); return v === null ? null : valueToText(v).toLowerCase(); } case 'upperutf8': { argc(1); const v = A(0); return v === null ? null : valueToText(v).toUpperCase(); } case 'trim': case 'trimboth': { argc(1); const v = A(0); return v === null ? null : valueToText(v).replace(/^ +| +$/g, ''); } case 'trimleft': case 'ltrim': { argc(1); const v = A(0); return v === null ? null : valueToText(v).replace(/^ +/, ''); } case 'trimright': case 'rtrim': { argc(1); const v = A(0); return v === null ? null : valueToText(v).replace(/ +$/, ''); } case 'reverse': { argc(1); const v = A(0); if (v === null) return null; return Array.isArray(v) ? [...v].reverse() : [...valueToText(v)].reverse().join(''); } case 'startswith': case 'endswith': { argc(2); const s = A(0); const p = A(1); if (s === null || p === null) return null; return (name === 'startswith' ? valueToText(s).startsWith(valueToText(p)) : valueToText(s).endsWith(valueToText(p))) ? 1 : 0; } case 'position': case 'locate': { argc(2); const s = A(0); const p = A(1); if (s === null || p === null) return null; const i = Buffer.from(valueToText(s)).indexOf(Buffer.from(valueToText(p))); return i + 1; } case 'replace': case 'replaceall': { argc(3); const s = A(0); const a = A(1); const b = A(2); if (s === null || a === null || b === null) return null; const from = valueToText(a); return from === '' ? valueToText(s) : valueToText(s).split(from).join(valueToText(b)); } case 'replaceone': { argc(3); const s = A(0); const a = A(1); const b = A(2); if (s === null || a === null || b === null) return null; return valueToText(s).replace(valueToText(a), () => valueToText(b)); } case 'substring': case 'substr': case 'mid': { argc(2, 3); const s = A(0); const off = asNumber(A(1)); if (s === null || off === null) return null; const buf = Buffer.from(valueToText(s), 'utf8'); const start = off > 0 ? off - 1 : Math.max(0, buf.length + off); const len = e.args.length === 3 ? asNumber(A(2))! : buf.length - start; return buf.subarray(start, Math.max(start, start + len)).toString('utf8'); } case 'splitbystring': case 'splitbychar': { argc(2, 3); const sep = A(0); const s = A(1); if (sep === null || s === null) return null; const sepText = valueToText(sep); const text = valueToText(s); if (sepText === '') return [...text]; return text.split(sepText); } case 'arraystringconcat': { argc(1, 2); const arr = A(0); const sep = e.args.length > 1 ? valueToText(A(1)) : ''; return Array.isArray(arr) ? arr.map(valueToText).join(sep) : null; } case 'leftpad': case 'rightpad': { argc(2, 3); const s = valueToText(A(0)); const n = asNumber(A(1))!; const fill = e.args.length > 2 ? valueToText(A(2)) : ' '; if (s.length >= n) return s.slice(0, n); const pad = fill.repeat(Math.ceil((n - s.length) / Math.max(1, fill.length))).slice(0, n - s.length); return name === 'leftpad' ? pad + s : s + pad; } // ClickHouse string-search-functions#extract: first capturing group, otherwise the whole first match. case 'extract': { argc(2); const haystack = A(0), pattern = A(1); if (haystack === null || pattern === null) return null; if (typeof haystack !== 'string' || typeof pattern !== 'string') return fail('Illegal type of argument of function extract: expected String'); let match: RegExpExecArray | null; try { match = new RegExp(valueToText(pattern)).exec(valueToText(haystack)); } catch { return fail('Cannot compile re2: ' + valueToText(pattern)); } return match ? (match.length > 1 ? match[1] ?? '' : match[0]) : ''; } case 'match': { argc(2); const s = A(0); const p = A(1); if (s === null || p === null) return null; return new RegExp(valueToText(p)).test(valueToText(s)) ? 1 : 0; } case 'replaceregexpall': case 'replaceregexpone': { argc(3); const s = A(0); const p = A(1); const r = A(2); if (s === null || p === null || r === null) return null; const re = new RegExp(valueToText(p), name === 'replaceregexpall' ? 'g' : ''); return valueToText(s).replace(re, valueToText(r).replace(/\\(\d)/g, '$$$1')); } case 'base64encode': { argc(1); const v = A(0); return v === null ? null : Buffer.from(valueToText(v), 'utf8').toString('base64'); } case 'base64decode': { argc(1); const v = A(0); return v === null ? null : Buffer.from(valueToText(v), 'base64').toString('utf8'); } case 'hex': { argc(1); const v = A(0); if (v === null) return null; return typeof v === 'number' ? v.toString(16).toUpperCase() : Buffer.from(valueToText(v), 'utf8').toString('hex').toUpperCase(); } // URLs case 'encodeurlformcomponent': { argc(1); const v = A(0); return v === null ? null : encodeFormComponent(valueToText(v)); } case 'encodeurlcomponent': { argc(1); const v = A(0); return v === null ? null : encodeURIComponent(valueToText(v)); } case 'decodeurlformcomponent': { argc(1); const v = A(0); return v === null ? null : decodeComponent(valueToText(v), true); } case 'decodeurlcomponent': { argc(1); const v = A(0); return v === null ? null : decodeComponent(valueToText(v), false); } case 'extracturlparameter': { argc(2); const u = A(0); const p = A(1); if (u === null || p === null) return null; return extractUrlParameter(valueToText(u), valueToText(p)); } // "Returns an array of name strings corresponding to the names of URL parameters. The values are not decoded." // (https://clickhouse.com/docs/sql-reference/functions/url-functions#extractURLParameterNames) case 'extracturlparameternames': { argc(1); const u = A(0); if (u === null) return null; return extractUrlParameterNames(valueToText(u)); } // Maps (https://clickhouse.com/docs/sql-reference/functions/tuple-map-functions): mapFilter "Returns a map containing // only the elements in the map for which func returns something other than 0"; mapKeys "Returns array containing // all keys from the map"; mapContainsKey, alias mapContains, "Returns 1 if map contains key, 0 if not". case 'mapfilter': { argc(2); const m = A(1); if (m === null) return null; if (!(m instanceof ChMap)) return fail(`Illegal type of argument #2 of function ${e.name}, expected Map`); return new ChMap(m.entries.filter(([k, v]) => { const r = callLambda(e.args[0], env, [k, v]); return r !== null && r !== 0 && r !== false; })); } case 'mapkeys': case 'mapvalues': { argc(1); const m = A(0); if (m === null) return null; if (!(m instanceof ChMap)) return fail(`Illegal type of argument #1 of function ${e.name}, expected Map`); return m.entries.map(([k, v]) => (name === 'mapkeys' ? k : v)); } case 'mapcontains': case 'mapcontainskey': { argc(2); const m = A(0); const key = A(1); if (m === null) return null; if (!(m instanceof ChMap)) return fail(`Illegal type of argument #1 of function ${e.name}, expected Map`); return m.entries.some(([k]) => (k === null ? key === null : key !== null && valuesEqual(k, key))) ? 1 : 0; } case 'cutquerystring': { argc(1); const u = A(0); if (u === null) return null; const s = valueToText(u); const i = s.search(/[?#]/); return i < 0 ? s : s.slice(0, i); } case 'domain': case 'domainwithoutwww': { argc(1); const u = A(0); if (u === null) return null; const m = /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?\/\/([^/?#:@]+(?:@[^/?#:]+)?)/.exec(valueToText(u)); let host = m ? m[1]!.replace(/^.*@/, '') : ''; if (name === 'domainwithoutwww') host = host.replace(/^www\./, ''); return host; } case 'path': { argc(1); const u = A(0); if (u === null) return null; const m = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/?#]*([^?#]*)/.exec(valueToText(u)); return m ? m[1]! : ''; } // JSON case 'jsonextractstring': case 'jsonextractraw': case 'jsonextractint': case 'jsonextractfloat': case 'jsonextractbool': case 'jsonhas': { if (e.args.length < 1) fail(`Number of arguments for function ${e.name} doesn't match`); const j = A(0); if (j === null) return null; const keys = e.args.slice(1).map((_, i) => A(i + 1)); const v = jsonPathValue(typeof j === 'string' ? j : stringifyJson(j), keys); if (name === 'jsonhas') return v === undefined ? 0 : 1; if (name === 'jsonextractstring') return typeof v === 'string' ? v : ''; if (name === 'jsonextractraw') return v === undefined ? '' : stringifyJson(v); if (name === 'jsonextractbool') return v === true ? 1 : 0; if (typeof v === 'bigint') return name === 'jsonextractint' ? normInt(v) : Number(v); if (typeof v === 'number') return name === 'jsonextractint' ? Math.trunc(v) : v; if (typeof v === 'boolean') return v ? 1 : 0; return 0; } // numeric conversions case 'tofloat64': case 'tofloat32': { argc(1); const v = A(0); return v === null ? null : asNumber(typeof v === 'string' ? v.trim() : v); } case 'totypename': { argc(1); return typeOf(e.args[0]!, env.scope); } default: break; } // toIntN / toUIntN (8…256 bits) and their OrZero / OrNull forms, toFloatN OrZero / OrNull. const conv = /^to(u?int(?:8|16|32|64|128|256)|float(?:32|64))(orzero|ornull)?$/.exec(name); if (conv) { argc(1); const t = conv[1]!.replace(/^u?int|^float/, (m) => (m === 'uint' ? 'UInt' : m === 'int' ? 'Int' : 'Float')); const v = A(0); if (conv[2]) return toNumberOrElse(v, t, conv[2] === 'ornull'); if (v === null) return null; return toIntegerOf(typeof v === 'string' ? v : v, t); } switch (name) { case 'round': { argc(1, 2); const v = A(0); if (v === null) return null; const d = e.args.length > 1 ? asNumber(A(1))! : 0; const f = 10 ** d; return roundHalfEven(asNumber(v)! * f) / f; } case 'floor': { argc(1, 2); const v = A(0); if (v === null) return null; const d = e.args.length > 1 ? asNumber(A(1))! : 0; const f = 10 ** d; return Math.floor(asNumber(v)! * f) / f; } case 'ceil': case 'ceiling': { argc(1, 2); const v = A(0); if (v === null) return null; const d = e.args.length > 1 ? asNumber(A(1))! : 0; const f = 10 ** d; return Math.ceil(asNumber(v)! * f) / f; } case 'abs': { argc(1); const v = A(0); return v === null ? null : typeof v === 'bigint' ? normInt(v < 0n ? -v : v) : Math.abs(asNumber(v)!); } case 'intdiv': { argc(2); const a = A(0); const b = A(1); if (a === null || b === null) return null; if (isExactInt(a) && isExactInt(b)) { const divisor = toBigInt(b); if (divisor === 0n) fail('Division by zero'); return normInt(toBigInt(a) / divisor); } if (asNumber(b) === 0) fail('Division by zero'); return Math.trunc(asNumber(a)! / asNumber(b)!); } case 'divide': case 'plus': case 'minus': case 'multiply': case 'modulo': { argc(2); const ops: Record = { divide: '/', plus: '+', minus: '-', multiply: '*', modulo: '%' }; return arithmetic(ops[name]!, A(0), A(1)); } case 'sqrt': { argc(1); const v = A(0); return v === null ? null : Math.sqrt(asNumber(v)!); } case 'pow': case 'power': { argc(2); const a = A(0); const b = A(1); return a === null || b === null ? null : asNumber(a)! ** asNumber(b)!; } // dates and times case 'now': { argc(0, 1); return new DT(env.scope.exec.nowMs, 0, e.args.length ? tzArg(e, 0, env) : undefined); } case 'now64': { argc(0, 2); return new DT(env.scope.exec.nowMs, e.args.length ? asNumber(A(0))! : 3, e.args.length > 1 ? tzArg(e, 1, env) : undefined); } case 'today': { argc(0); return toDateValue(new DT(env.scope.exec.nowMs, 0)); } case 'yesterday': { argc(0); return new DDate(toDateValue(new DT(env.scope.exec.nowMs, 0)).days - 1); } case 'todatetime': case 'parsedatetimebesteffort': case 'parsedatetimebesteffortornull': { argc(1, 2); const v = A(0); if (v === null) return null; const tz = e.args.length > 1 ? tzArg(e, 1, env) : undefined; if (name === 'parsedatetimebesteffortornull') { try { return castDateTime(v, 0, tz); } catch { return null; } } return castDateTime(v, 0, tz); } // https://clickhouse.com/docs/en/sql-reference/functions/type-conversion-functions#parseDateTime64BestEffort case 'parsedatetime64besteffort': case 'parsedatetime64besteffortornull': case 'parsedatetime64besteffortorzero': { argc(1, 3); const v = A(0); if (v === null) return null; if (typeof v !== 'string') fail('Illegal type of argument of function ' + e.name + ': expected String'); const scale = e.args.length > 1 ? asNumber(A(1))! : 3; const tz = e.args.length > 2 ? tzArg(e, 2, env) : undefined; try { return castDateTime(v, scale, tz); } catch (error) { if (name === 'parsedatetime64besteffortornull') return null; if (name === 'parsedatetime64besteffortorzero') return new DT(0, scale, tz); throw error; } } case 'todatetime64': case 'todatetime64orzero': { argc(2, 3); const v = A(0); if (v === null) return null; const scale = asNumber(A(1))!; const tz = e.args.length > 2 ? tzArg(e, 2, env) : undefined; try { return castDateTime(v, scale, tz); } catch (err) { if (name === 'todatetime64orzero') return new DT(0, scale, tz); throw err; } } case 'todate': { argc(1, 2); const v = A(0); if (v === null) return null; return toDateValue(v, e.args.length > 1 ? tzArg(e, 1, env) : undefined); } case 'tostartofsecond': { argc(1, 2); return startOf(A(0), 'second', tzArg(e, 1, env)); } case 'tostartofminute': { argc(1, 2); return startOf(A(0), 'minute', tzArg(e, 1, env)); } case 'tostartoffiveminutes': case 'tostartoffiveminute': { argc(1, 2); return startOf(A(0), 'fiveMinutes', tzArg(e, 1, env)); } case 'tostartoffifteenminutes': { argc(1, 2); return startOf(A(0), 'fifteenMinutes', tzArg(e, 1, env)); } case 'tostartofhour': { argc(1, 2); return startOf(A(0), 'hour', tzArg(e, 1, env)); } case 'tostartofday': { argc(1, 2); return startOf(A(0), 'day', tzArg(e, 1, env)); } case 'tostartofweek': case 'tomonday': case 'tostartofmonth': case 'tostartofquarter': case 'tostartofyear': { argc(1, name === 'tostartofweek' ? 3 : 2); const v = A(0); if (v === null) return null; const tz = tzArg(e, name === 'tostartofweek' ? 2 : 1, env); const d = toDateValue(v, tz); const c = civilFromDays(d.days); if (name === 'tostartofmonth') return new DDate(daysFromCivil(c.y, c.mo, 1)); if (name === 'tostartofquarter') return new DDate(daysFromCivil(c.y, c.mo - ((c.mo - 1) % 3), 1)); if (name === 'tostartofyear') return new DDate(daysFromCivil(c.y, 1, 1)); const mode = name === 'tostartofweek' && e.args.length > 1 ? asNumber(A(1))! : name === 'tomonday' ? 1 : 0; const dow = ((d.days % 7) + 7 + 4) % 7; // 0 = Sunday const back = mode % 2 === 1 ? (dow + 6) % 7 : dow; return new DDate(d.days - back); } case 'tostartofinterval': case 'time_bucket': case 'date_bin': { argc(2, 3); const v = A(0); const iv = A(1); if (v === null || iv === null) return null; if (!(iv instanceof Interval)) return fail(`Illegal type of argument #2 of function ${e.name}: expected an INTERVAL`); return startOfInterval(v, iv, e.args.length > 2 ? tzArg(e, 2, env) : undefined); } case 'toyyyymmdd': case 'toyyyymmddhhmmss': case 'toquarter': case 'todayofyear': { argc(1, 2); const v = A(0); if (v === null) return null; const tz = tzArg(e, 1, env); const dt = v instanceof DDate ? castDateTime(v, 0, tz) : toDateTimeArg(v); const w = wallOf(dt.ms, tz ?? dt.tz); if (name === 'toyyyymmdd') return w.y * 10000 + w.mo * 100 + w.d; if (name === 'toquarter') return Math.floor((w.mo - 1) / 3) + 1; if (name === 'todayofyear') return daysFromCivil(w.y, w.mo, w.d) - daysFromCivil(w.y, 1, 1) + 1; return normInt(BigInt(w.y * 10000 + w.mo * 100 + w.d) * 1000000n + BigInt(w.h * 10000 + w.mi * 100 + w.s)); } case 'toyyyymm': case 'toyear': case 'tomonth': case 'todayofmonth': case 'tohour': case 'tominute': case 'tosecond': case 'todayofweek': { argc(1, 2); const v = A(0); if (v === null) return null; const tz = tzArg(e, 1, env); const dt = v instanceof DDate ? castDateTime(v, 0, tz) : toDateTimeArg(v); const w = wallOf(dt.ms, tz ?? dt.tz); switch (name) { case 'toyyyymm': return w.y * 100 + w.mo; case 'toyear': return w.y; case 'tomonth': return w.mo; case 'todayofmonth': return w.d; case 'tohour': return w.h; case 'tominute': return w.mi; case 'tosecond': return w.s; default: { const dow = ((daysFromCivil(w.y, w.mo, w.d) % 7) + 7 + 4) % 7; return dow === 0 ? 7 : dow; } } } case 'tounixtimestamp': { argc(1, 2); const v = A(0); if (v === null) return null; if (typeof v === 'string') return Math.floor(castDateTime(v, 0, tzArg(e, 1, env)).ms / 1000); return Math.floor(toDateTimeArg(v).ms / 1000); } case 'tounixtimestamp64milli': { argc(1); const v = A(0); if (v === null) return null; return toDateTimeArg(v).ms; } case 'tounixtimestamp64micro': { argc(1); const v = A(0); if (v === null) return null; const d = toDateTimeArg(v); return normInt(BigInt(d.ms) * 1000n + BigInt(Math.floor(d.ns / 1000))); } case 'tounixtimestamp64nano': { argc(1); const v = A(0); if (v === null) return null; const d = toDateTimeArg(v); return normInt(BigInt(d.ms) * 1000000n + BigInt(d.ns)); } case 'fromunixtimestamp64micro': case 'fromunixtimestamp64nano': { argc(1, 2); const v = A(0); if (v === null) return null; const n = toBigInt(v); const per = name.endsWith('micro') ? 1000n : 1000000n; const msPart = n >= 0n ? n / per : -((-n + per - 1n) / per); return makeDT(Number(msPart), Number((n - msPart * per) * (1000000n / per)), name.endsWith('micro') ? 6 : 9, tzArg(e, 1, env)); } case 'fromunixtimestamp64milli': { argc(1, 2); const v = A(0); if (v === null) return null; return new DT(asNumber(v)!, 3, tzArg(e, 1, env)); } case 'fromunixtimestamp': { argc(1, 2); const v = A(0); if (v === null) return null; return new DT(asNumber(v)! * 1000, 0, tzArg(e, 1, env)); } case 'datediff': case 'date_diff': case 'timestampdiff': { argc(3, 4); const u = A(0); const a = A(1); const b = A(2); if (u === null || a === null || b === null) return null; const tz = e.args.length > 3 ? tzArg(e, 3, env) : undefined; const unit = valueToText(u).toLowerCase(); const da = a instanceof DDate || a instanceof DT ? a : castDateTime(a, 0, tz); const db = b instanceof DDate || b instanceof DT ? b : castDateTime(b, 0, tz); const zone = tz ?? (da instanceof DT ? da.tz : undefined) ?? (db instanceof DT ? db.tz : undefined); return relativeNumber(db, unit, zone) - relativeNumber(da, unit, zone); } case 'formatdatetime': { argc(2, 3); const v = A(0); const f = A(1); if (v === null || f === null) return null; const dt = v instanceof DDate || v instanceof DT ? v : castDateTime(v, 0); return formatDateTimePattern(dt, valueToText(f), e.args.length > 2 ? tzArg(e, 2, env) : undefined); } case 'totimezone': { argc(2); const v = A(0); if (v === null) return null; return toDateTimeArg(v).withTz(tzArg(e, 1, env)); } case 'addseconds': case 'addminutes': case 'addhours': case 'adddays': case 'addweeks': case 'addmonths': case 'addyears': case 'subtractseconds': case 'subtractminutes': case 'subtracthours': case 'subtractdays': case 'subtractweeks': case 'subtractmonths': case 'subtractyears': { argc(2); const v = A(0); const n = asNumber(A(1)); if (v === null || n === null) return null; const unit = name.replace(/^(add|subtract)/, '').replace(/s$/, '') as IntervalUnit; return addInterval(v, new Interval(unit, n), name.startsWith('add') ? 1 : -1); } // arrays case 'array': return e.args.map((_, i) => A(i)); case 'arrayjoin': { const bound = env.aj?.get(e); if (bound !== undefined || env.aj?.has(e)) return bound; return fail('arrayJoin is only supported in the SELECT list of this twin'); } case 'range': { argc(1, 3); const args = e.args.map((_, i) => asNumber(A(i))); if (args.some((x) => x === null)) return null; const [start, end, step] = args.length === 1 ? [0, args[0]!, 1] : [args[0]!, args[1]!, args[2] ?? 1]; if (step <= 0) fail('range: step must be positive'); const out: number[] = []; for (let x = start; x < end; x += step) { out.push(x); if (out.length > 1_000_000) fail('range: too many elements'); } return out; } case 'arrayelement': { argc(2); const arr = A(0); const i = asNumber(A(1)); if (arr === null || i === null) return null; if (!Array.isArray(arr)) fail('arrayElement: first argument must be an array'); return arrayAt(arr as unknown[], i); } case 'has': { argc(2); const arr = A(0); const x = A(1); if (arr === null) return null; if (!Array.isArray(arr)) fail('has: first argument must be an array'); return (arr as unknown[]).some((y) => (y === null ? x === null : x !== null && valuesEqual(y, x))) ? 1 : 0; } case 'hasany': case 'hasall': { argc(2); const a = A(0); const b = A(1); if (a === null || b === null) return null; if (!Array.isArray(a) || !Array.isArray(b)) fail(`${e.name}: arguments must be arrays`); const keys = new Set((a as unknown[]).map(valueKey)); return (name === 'hasany' ? (b as unknown[]).some((x) => keys.has(valueKey(x))) : (b as unknown[]).every((x) => keys.has(valueKey(x)))) ? 1 : 0; } case 'indexof': { argc(2); const arr = A(0); const x = A(1); if (arr === null) return null; const i = (arr as unknown[]).findIndex((y) => x !== null && y !== null && valuesEqual(y, x)); return i + 1; } case 'arrayintersect': { const arrays = argArrays(e, env, 0); if (!arrays) return null; if (arrays.length === 0) return []; const rest = arrays.slice(1).map((a) => new Set(a.map(valueKey))); const seen = new Set(); const out: unknown[] = []; for (const x of arrays[0]!) { const k = valueKey(x); if (seen.has(k)) continue; if (rest.every((s) => s.has(k))) { seen.add(k); out.push(x); } } return out; } case 'arraydistinct': { argc(1); const arr = A(0); if (arr === null) return null; const seen = new Set(); return (arr as unknown[]).filter((x) => { const k = valueKey(x); if (seen.has(k) || x === null) return false; seen.add(k); return true; }); } case 'arrayconcat': { const arrays = argArrays(e, env, 0); return arrays ? arrays.flat() : null; } case 'arraysort': case 'arrayreversesort': { if (e.args[0]?.k === 'lambda') { const arrays = argArrays(e, env, 1); if (!arrays) return null; const keyed = arrays[0]!.map((x, i) => ({ x, k: callLambda(e.args[0], env, arrays.map((a) => a[i])) })); keyed.sort((p, q) => compareValues(p.k, q.k) * (name === 'arrayreversesort' ? -1 : 1)); return keyed.map((p) => p.x); } argc(1); const arr = A(0); if (arr === null) return null; return [...(arr as unknown[])].sort((p, q) => compareValues(p, q) * (name === 'arrayreversesort' ? -1 : 1)); } case 'arrayreverse': { argc(1); const arr = A(0); return arr === null ? null : [...(arr as unknown[])].reverse(); } case 'arrayslice': { argc(2, 3); const arr = A(0) as unknown[] | null; const off = asNumber(A(1)); if (arr === null || off === null) return null; const start = off > 0 ? off - 1 : arr.length + off; const len = e.args.length > 2 ? asNumber(A(2)) : null; return arr.slice(start, len === null ? undefined : start + len); } case 'arraypushback': { argc(2); const arr = A(0) as unknown[] | null; return arr === null ? null : [...arr, A(1)]; } case 'arraypushfront': { argc(2); const arr = A(0) as unknown[] | null; return arr === null ? null : [A(1), ...arr]; } case 'arraymap': { const arrays = argArrays(e, env, 1); if (!arrays) return null; const n = arrays[0]?.length ?? 0; if (arrays.some((a) => a.length !== n)) fail('arrayMap: arrays passed to the function must have equal size'); const out: unknown[] = []; for (let i = 0; i < n; i++) out.push(callLambda(e.args[0], env, arrays.map((a) => a[i]))); return out; } case 'arrayfilter': case 'arraycount': case 'arrayexists': case 'arrayall': case 'arrayfirst': case 'arraysum': { if (e.args[0]?.k !== 'lambda') { if (name === 'arraysum' || name === 'arraycount') { argc(1); const arr = A(0) as unknown[] | null; if (arr === null) return null; return name === 'arraysum' ? sumArray(arr) : arr.filter((x) => truth(x) === true).length; } return fail(`${e.name}: first argument must be a lambda`); } const arrays = argArrays(e, env, 1); if (!arrays) return null; const n = arrays[0]?.length ?? 0; const results = Array.from({ length: n }, (_, i) => callLambda(e.args[0], env, arrays.map((a) => a[i]))); if (name === 'arrayfilter') return arrays[0]!.filter((_, i) => truth(results[i]) === true); if (name === 'arraycount') return results.filter((r) => truth(r) === true).length; if (name === 'arrayexists') return results.some((r) => truth(r) === true) ? 1 : 0; if (name === 'arrayall') return results.every((r) => truth(r) === true) ? 1 : 0; if (name === 'arraysum') return sumArray(results); const i = results.findIndex((r) => truth(r) === true); return i < 0 ? arrayAt(arrays[0]!, 0) : arrays[0]![i]; } case 'tuple': return e.args.map((_, i) => A(i)); default: if (name.startsWith('tointerval')) { argc(1); const unit = name.slice('tointerval'.length) as IntervalUnit; if (!['millisecond', 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'].includes(unit)) fail(`Unknown function ${e.name}`); const n = asNumber(A(0)); return n === null ? null : new Interval(unit, n); } return fail(`Unknown function ${e.name}`); } } function sumArray(values: unknown[]): number | bigint { const held = values.filter((value) => value !== null && value !== undefined); return held.every(isExactInt) ? normInt(held.reduce((sum, value) => sum + toBigInt(value), 0n)) : held.reduce((sum, value) => sum + (asNumber(value) ?? 0), 0); } function roundHalfEven(x: number): number { const r = Math.round(x); return Math.abs(x % 1) === 0.5 && r % 2 !== 0 ? r - 1 : r; } // ── aggregates ────────────────────────────────────────────────────────────────────────────── /** sum()/avg() of a String is ClickHouse's ILLEGAL_TYPE_OF_ARGUMENT, never a coerced number. */ function rejectStringArgument(e: Extract, env: Env): void { const arg = e.args[0]; if (!arg || arg.k === 'star') return; const t = typeOf(arg, env.scope); const h = typeHead(t); if (h === 'String' || h === 'FixedString' || h === 'UUID') { fail(`Illegal type ${baseType(t).base} of argument for aggregate function ${e.name}`); } } /** * An aggregate's state: what finishing it (plain call or `-Merge`) needs. Its shape per kind is * documented beside `aggKind` in ./values.ts (scalar, sum, avg, set, list, arg). */ function buildState(base: string, values: unknown[], keys: unknown[] | undefined): unknown { const kind = aggKind(base)!; switch (kind) { case 'sum': { if (base === 'count') return values.length; if (values.length === 0) return null; let exact = true; for (const v of values) if (!isExactInt(v)) { exact = false; break; } if (exact) return normInt(values.reduce((s, v) => s + toBigInt(v), 0n)); return values.reduce((s, v) => s + asNumber(v)!, 0); } case 'avg': return values.length === 0 ? null : [values.reduce((s, v) => s + asNumber(v)!, 0), values.length]; case 'scalar': { if (values.length === 0) return null; if (base === 'any') return values[0]; if (base === 'anylast') return values[values.length - 1]; return values.reduce((a, b) => ((base === 'min' ? compareValues(b, a) < 0 : compareValues(b, a) > 0) ? b : a)); } case 'set': { const seen = new Set(); return values.filter((v) => { const k = valueKey(v); if (seen.has(k)) return false; seen.add(k); return true; }); } case 'list': return values; case 'arg': { let best = -1; for (let i = 0; i < values.length; i++) { if (keys![i] === null || keys![i] === undefined) continue; if (best < 0 || (base === 'argmin' ? compareValues(keys![i], keys![best]) < 0 : compareValues(keys![i], keys![best]) > 0)) best = i; } return best < 0 ? null : [values[best], keys![best]]; } } } /** Union two states of the same aggregate (what `-Merge` does across parts). */ function mergeStates(base: string, a: unknown, b: unknown): unknown { if (a === null || a === undefined) return b; if (b === null || b === undefined) return a; switch (aggKind(base)!) { case 'sum': return arithmetic('+', a, b); case 'avg': { const [s1, c1] = a as number[]; const [s2, c2] = b as number[]; return [s1! + s2!, c1! + c2!]; } case 'scalar': if (base === 'any') return a; if (base === 'anylast') return b; return (base === 'min' ? compareValues(b, a) < 0 : compareValues(b, a) > 0) ? b : a; case 'set': return buildState(base, [...(a as unknown[]), ...(b as unknown[])], undefined); case 'list': return [...(a as unknown[]), ...(b as unknown[])]; case 'arg': { const [, ka] = a as unknown[]; const [, kb] = b as unknown[]; return (base === 'argmin' ? compareValues(kb, ka) < 0 : compareValues(kb, ka) > 0) ? b : a; } } } /** ClickHouse's `quantile` family: linear interpolation (exact at this twin's sizes), or the * `quantileExact` element at ⌊n·p⌋ of the sorted values. */ function quantileOf(values: unknown[], p: number, exact: boolean): unknown { if (values.length === 0) return exact ? null : Number.NaN; const sorted = [...values].sort(compareValues); if (exact) return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * p))]; const pos = (sorted.length - 1) * p; const lo = Math.floor(pos); const hi = Math.min(sorted.length - 1, lo + 1); const a = asNumber(sorted[lo])!; const b = asNumber(sorted[hi])!; return a + (b - a) * (pos - lo); } /** Finish an aggregate from its state; `argType` is the argument's type (defaults for no rows). */ function finishState(base: string, params: unknown[], state: unknown, argType: string): unknown { const nullable = isNullableType(argType) && !RETURNS_DEFAULT_ON_NULL.has(base); switch (aggKind(base)!) { case 'sum': return state ?? (nullable ? null : 0); case 'avg': { if (state === null || state === undefined) return nullable ? null : Number.NaN; const [s, c] = state as number[]; return s! / c!; } case 'scalar': return state === null || state === undefined ? (nullable ? null : defaultOf(argType)) : state; case 'set': return base === 'groupuniqarray' ? (state ?? []) : ((state as unknown[] | null) ?? []).length; case 'arg': return state === null || state === undefined ? (nullable ? null : defaultOf(argType)) : (state as unknown[])[0]; case 'list': { const vs = (state as unknown[] | null) ?? []; if (base === 'grouparray') return vs; if (base === 'grouparraysample') return sampleOf(vs, params); const exact = base.includes('exact'); const many = base.startsWith('quantiles'); const ps = (params.length ? params : [0.5]).map((p) => asNumber(p)!); if (base.startsWith('median')) ps.splice(0, ps.length, 0.5); if (vs.length === 0 && nullable && !many) return null; const out = ps.map((p) => quantileOf(vs, p, exact)); if (exact) for (let i = 0; i < out.length; i++) if (out[i] === null) out[i] = defaultOf(argType); return many ? out : out[0]; } } } /** Aggregates that answer a default (not NULL) when every input is NULL (ClickHouse's -Null rules). */ const RETURNS_DEFAULT_ON_NULL = new Set(['count', 'countdistinct', 'uniq', 'uniqexact', 'uniqcombined', 'uniqcombined64', 'uniqhll12', 'grouparray', 'grouparraysample', 'groupuniqarray']); /** * `groupArraySample(max_size[, seed])(x)`: "Creates an array of sample argument values. The size of the resulting array * is limited to max_size elements. Argument values are selected and added to the array randomly" * (https://clickhouse.com/docs/sql-reference/aggregate-functions/reference/grouparraysample): a reservoir sample. With * no seed, ClickHouse seeds from a thread-local generator; a World must replay byte for byte, so the twin seeds from what * the World holds (R9: a stable hash of the values sampled and the size asked), and a given `seed` seeds it instead. */ /** mulberry32: a small seeded generator of uniform numbers in [0, 1), the same numbers for the same seed on every * machine. */ export function mulberry32(seed: number): () => number { let state = seed >>> 0; return () => { state = (state + 0x6d2b79f5) >>> 0; let t = state; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } function sampleOf(values: unknown[], params: unknown[]): unknown[] { const max = Math.max(0, Number(asNumber(params[0]) ?? 0)); if (values.length <= max) return [...values]; const seedText = params[1] !== undefined ? `seed:${valueToText(params[1])}` : `values:${max}:${values.map(valueKey).join('\u0001')}`; const nextUniform = mulberry32(parseInt(digest('sha256', seedText).slice(0, 8), 16)); const reservoir = values.slice(0, max); for (let i = max; i < values.length; i++) { const j = Math.floor(nextUniform() * (i + 1)); if (j < max) reservoir[j] = values[i]; } return reservoir; } function evalAggregate(e: Extract, env: Env): unknown { if (!env.group) return fail(`Aggregate function ${e.name}() is found in a clause where it is not allowed (WHERE, PREWHERE, ON or an array function)`); const agg = parseAggregate(e.name)!; const rows = env.group; const rowEnv = (row: JRow): Env => ({ scope: env.scope, row, aliasCache: new Map(), evaluating: new Set(env.evaluating), ...(env.lambda ? { lambda: env.lambda } : {}), ...(env.aj ? { aj: env.aj } : {}) }); const star = e.args.length === 1 && e.args[0]!.k === 'star'; const nArgs = agg.cond ? e.args.length - 1 : e.args.length; const mask = agg.cond ? rows.map((r) => truth(evalExpr(e.args[e.args.length - 1]!, rowEnv(r))) === true) : rows.map(() => true); const live = rows.filter((_, i) => mask[i]); const params = (e.params ?? []).map((p) => evalExpr(p, { ...env, group: undefined as unknown as JRow[] })); const { base } = agg; if ((base === 'sum' || base === 'avg') && agg.mode !== 'merge') rejectStringArgument(e, env); if (agg.mode === 'merge') { const states = live.map((r) => evalExpr(e.args[0]!, rowEnv(r))).filter((s): s is AggState => s instanceof AggState); const want = stateName(base, params); if (states.some((s) => s.fn.toLowerCase().replace(/\s+/g, '') !== want)) fail(`${e.name}: the argument holds a state of a different aggregate function`); let st: unknown = null; for (const s of states) st = mergeStates(base, st, s.value); const colType = e.args[0] ? typeOf(e.args[0], env.scope) : ''; const inner = typeArgs(colType)[1] ?? 'String'; return finishState(base, params, st, inner.replace(/^Nullable\((.*)\)$/s, '$1')); } // count(), count(*) and count(DISTINCT …). if (base === 'count' && (nArgs === 0 || star)) { const n = live.length; return agg.mode === 'state' ? new AggState('count', n) : n; } // uniq(a, b, …) hashes the tuple. const tupleArgs = (base.startsWith('uniq') || base === 'countdistinct') && nArgs > 1; let values: unknown[]; let keys: unknown[] | undefined; if (star) { // `uniq(*)` hashes the whole row (every column of every joined source). values = live.map((r) => r.map((s) => s.map(valueKey).join('|')).join('||')); } else if (tupleArgs) { values = live.map((r) => e.args.slice(0, nArgs).map((a) => evalExpr(a, rowEnv(r)))); } else if (base === 'argmin' || base === 'argmax') { const pairs = live.map((r) => [evalExpr(e.args[0]!, rowEnv(r)), evalExpr(e.args[1]!, rowEnv(r))] as const); values = pairs.map((p) => p[0]); keys = pairs.map((p) => p[1]); } else { values = live.map((r) => evalExpr(e.args[0]!, rowEnv(r))).filter((v) => v !== null && v !== undefined); } if (e.distinct) values = buildState('uniq', values, undefined) as unknown[]; const state = buildState(base, values, keys); if (agg.mode === 'state') return new AggState(stateName(base, params), state); const argType = e.args[0] && !star ? typeOf(e.args[0], env.scope) : 'UInt64'; return finishState(base, params, state, argType); } // ── static checking (what ClickHouse's analyzer refuses before reading a row) ───────────── // // ClickHouse resolves every identifier, function and argument type when it ANALYZES a query, so an // unknown column, an unknown function or `'a' + 1` is its 400 whether or not the table holds rows // (and so at `tb push`, which runs each node through the analyzer). The executor runs this pass on // every SELECT once its FROM is bound: names resolve by exactly the rules `resolveId` applies, a // function must be one this engine implements (anything else is the honest `Unknown function`), // and the type rules below fire only when a String operand is CERTAIN (a literal, a declared // Data Source column, a CAST or a function whose result is String) — never on an inferred guess. /** Every scalar function `evalFunction` implements (lower-case), besides the conversion family. */ const SCALAR_FUNCTIONS = new Set([ 'abs', 'adddays', 'addhours', 'addminutes', 'addmonths', 'addseconds', 'addweeks', 'addyears', 'array', 'arrayall', 'arrayconcat', 'arraycount', 'arraydistinct', 'arrayelement', 'arrayexists', 'arrayfilter', 'arrayfirst', 'arrayintersect', 'arrayjoin', 'arraymap', 'arraypushback', 'arraypushfront', 'arrayreverse', 'arrayreversesort', 'arrayslice', 'arraysort', 'arraystringconcat', 'arraysum', 'assumenotnull', 'base64decode', 'base64encode', 'ceil', 'ceiling', 'char_length', 'coalesce', 'concat', 'cutquerystring', 'date_bin', 'date_diff', 'datediff', 'decodeurlcomponent', 'decodeurlformcomponent', 'divide', 'domain', 'domainwithoutwww', 'empty', 'encodeurlcomponent', 'encodeurlformcomponent', 'endswith', 'equals', 'extract', 'extracturlparameter', 'extracturlparameternames', 'floor', 'formatdatetime', 'mapcontains', 'mapcontainskey', 'mapfilter', 'mapkeys', 'mapvalues', 'fromunixtimestamp', 'fromunixtimestamp64micro', 'fromunixtimestamp64milli', 'fromunixtimestamp64nano', 'greatest', 'has', 'hasall', 'hasany', 'hex', 'identity', 'if', 'ifnull', 'indexof', 'intdiv', 'isnotnull', 'isnull', 'jsonextractbool', 'jsonextractfloat', 'jsonextractint', 'jsonextractraw', 'jsonextractstring', 'jsonhas', 'lcase', 'least', 'leftpad', 'length', 'lengthutf8', 'locate', 'lower', 'lowerutf8', 'ltrim', 'match', 'materialize', 'mid', 'minus', 'modulo', 'multiif', 'multiply', 'notempty', 'notequals', 'now', 'now64', 'nullif', 'parsedatetime64besteffort', 'parsedatetime64besteffortornull', 'parsedatetime64besteffortorzero', 'parsedatetimebesteffort', 'parsedatetimebesteffortornull', 'path', 'plus', 'position', 'pow', 'power', 'range', 'replace', 'replaceall', 'replaceone', 'replaceregexpall', 'replaceregexpone', 'reverse', 'rightpad', 'round', 'rtrim', 'splitbychar', 'splitbystring', 'sqrt', 'startswith', 'substr', 'substring', 'subtractdays', 'subtracthours', 'subtractminutes', 'subtractmonths', 'subtractseconds', 'subtractweeks', 'subtractyears', 'time_bucket', 'timestampdiff', 'todate', 'todatetime', 'todatetime64', 'todatetime64orzero', 'today', 'todayofmonth', 'todayofweek', 'todayofyear', 'tofloat32', 'tofloat64', 'tohour', 'tolowcardinality', 'tominute', 'tomonday', 'tomonth', 'toquarter', 'tosecond', 'tostartofday', 'tostartoffifteenminutes', 'tostartoffiveminute', 'tostartoffiveminutes', 'tostartofhour', 'tostartofinterval', 'tostartofminute', 'tostartofmonth', 'tostartofquarter', 'tostartofsecond', 'tostartofweek', 'tostartofyear', 'tostring', 'totimezone', 'totypename', 'tounixtimestamp', 'tounixtimestamp64micro', 'tounixtimestamp64milli', 'tounixtimestamp64nano', 'toyear', 'toyyyymm', 'toyyyymmdd', 'toyyyymmddhhmmss', 'trim', 'trimboth', 'trimleft', 'trimright', 'tuple', 'ucase', 'upper', 'upperutf8', 'yesterday', 'touuid', 'touuidornull', ]); const INTERVAL_FUNCTIONS = new Set(['millisecond', 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year']); /** Functions whose result is always a String. */ const STRING_FUNCTIONS = new Set([ 'tostring', 'concat', 'replace', 'replaceall', 'replaceone', 'replaceregexpall', 'replaceregexpone', 'lower', 'upper', 'lowerutf8', 'upperutf8', 'substring', 'substr', 'trim', 'trimboth', 'trimleft', 'trimright', 'encodeurlformcomponent', 'decodeurlformcomponent', 'encodeurlcomponent', 'decodeurlcomponent', 'extract', 'extracturlparameter', 'jsonextractstring', 'jsonextractraw', 'formatdatetime', 'domain', 'domainwithoutwww', 'path', 'cutquerystring', 'leftpad', 'rightpad', 'base64encode', 'base64decode', 'hex', 'totypename', ]); export function isKnownFunction(name: string): boolean { const n = name.toLowerCase(); if (SCALAR_FUNCTIONS.has(n) || isAggregateName(n)) return true; if (n.startsWith('tointerval')) return INTERVAL_FUNCTIONS.has(n.slice(10)); return /^to(u?int(?:8|16|32|64|128|256)|float(?:32|64))(orzero|ornull)?$/.test(n); } /** Resolve an identifier the way `resolveId` does, without a row; an unresolvable name is the 400. */ function checkId(parts: string[], scope: Scope): void { if (parts.length === 1) { const name = parts[0]!; if (scope.aliases.has(name) || findColumn(scope, name) || scope.withExprs.has(name)) return; if (scope.outer) return checkId(parts, scope.outer); fail(`Missing columns: '${name}' while processing query`); } const qualifier = parts.slice(0, -1).join('.'); const column = parts[parts.length - 1]!; const s = findSource(scope, qualifier); if (s !== undefined) { const src = scope.sources[s]!; if (src.index.has(column) || src.index.has(parts.join('.'))) return; fail(`Missing columns: '${parts.join('.')}' while processing query`); } if (findColumn(scope, parts.join('.'))) return; checkId([column], scope); } /** A qualified column reference (`t.col`): its source and column, or undefined. */ function qualifiedColumn(scope: Scope, parts: string[]): { s: number; c: number } | undefined { const q = findSource(scope, parts.slice(0, -1).join('.')); const c = q === undefined ? undefined : scope.sources[q]!.index.get(parts[parts.length - 1]!); return q === undefined || c === undefined ? undefined : { s: q, c }; } /** Is this expression's type CERTAINLY a String (never a guess)? */ function certainlyString(e: Expr, scope: Scope, lambdas: Set, seen = new Set()): boolean { switch (e.k) { case 'lit': return e.type === 'String'; case 'alias': return certainlyString(e.e, scope, lambdas, seen); case 'cast': return /^(String|FixedString)$/.test(typeHead(e.type)); case 'fn': return STRING_FUNCTIONS.has(e.name.toLowerCase()); case 'id': { if (e.parts.length === 1) { const name = e.parts[0]!; if (lambdas.has(name)) return false; const alias = scope.aliases.get(name); if (alias && !seen.has(name)) { seen.add(name); return certainlyString(alias, scope, lambdas, seen); } } const s = e.parts.length === 1 ? findColumn(scope, e.parts[0]!) : qualifiedColumn(scope, e.parts); if (!s) return false; const src = scope.sources[s.s]!; return src.declared === true && /^(String|FixedString|UUID)$/.test(typeHead(src.columns[s.c]!.type)); } default: return false; } } const ARITHMETIC_NAMES: Record = { '+': 'plus', '-': 'minus', '*': 'multiply', '/': 'divide', '%': 'modulo' }; /** * The output name of a joined column. ClickHouse names a column of a joined (non-first) table * `.` when an earlier table of the join has a column of the same name, and the bare * column otherwise — `SELECT e.id, d.id FROM ev e JOIN dim d …` answers `id` and `d.id`, and * `SELECT *` over the same join answers `id, …, d.id, …` (clickhouse-local 26.10). */ function joinedColumnName(scope: Scope, s: number, column: string): string { const src = scope.sources[s]!; const q = src.alias ?? src.name; if (s === 0 || !q) return column; return scope.sources.slice(0, s).some((o) => o.index.has(column)) ? `${q}.${column}` : column; } /** A projected identifier's output name (see `joinedColumnName`). */ function idOutputName(scope: Scope, parts: string[]): string { const column = parts[parts.length - 1]!; if (parts.length > 1) { const s = findSource(scope, parts.slice(0, -1).join('.')); if (s !== undefined && scope.sources[s]!.index.has(column)) return joinedColumnName(scope, s, column); return column; } if (scope.aliases.has(column)) return column; const at = findColumn(scope, column); return at ? joinedColumnName(scope, at.s, column) : column; } // ── the executor ──────────────────────────────────────────────────────────────────────────── export class Executor { rowsRead = 0; bytesRead = 0; /** `validating`: publish-time analysis — subqueries in expressions are analyzed even when no row reaches them. */ constructor(readonly catalog: Catalog, readonly nowMs: number, readonly validating = false) {} /** Resolve a FROM name: CTEs in scope first, then the catalog. */ table(name: string, final: boolean, scope?: Scope): Relation { for (let s: Scope | undefined = scope; s; s = s.outer) { const cte = (s as Scope & { ctes?: Map }).ctes?.get(name); if (cte) return this.run(cte, s); } const rel = this.catalog.table(name, final); if (!rel) throw new ClickHouseError(`Resource '${name}' not found`, 404); this.rowsRead += rel.rows.length; this.bytesRead += rel.rows.reduce((n, r) => n + stringifyJson(r.map(toOutput)).length, 0); return rel; } run(q: Query, outer?: Scope): Relation { const parts = q.selects.map((s) => this.select(s, outer)); if (parts.length === 1) return parts[0]!.rel; const first = parts[0]!.rel; for (const p of parts.slice(1)) { if (p.rel.columns.length !== first.columns.length) fail('UNION ALL: different number of columns in the queries'); } return { columns: first.columns, rows: parts.flatMap((p) => p.rel.rows) }; } /** Run and also report rows_before_limit (for the response envelope). */ runTop(q: Query): { rel: Relation; rowsBeforeLimit?: number } { if (q.selects.length === 1) return this.select(q.selects[0]!, undefined); return { rel: this.run(q) }; } private select(sel: Select, outer?: Scope): { rel: Relation; rowsBeforeLimit?: number } { const scope: Scope & { ctes?: Map } = { sources: [], usingKeys: new Set(), aliases: new Map(), withExprs: new Map(), withCache: new Map(), exec: this, subCache: new Map(), ...(outer ? { outer } : {}), }; for (const w of sel.with) { if (w.query) { scope.ctes ??= new Map(); scope.ctes.set(w.name, w.query); } else if (w.expr) scope.withExprs.set(w.name, w.expr); } // Aliases are query-wide (ClickHouse's analyzer), including ones nested in expressions. for (const item of sel.items) collectAliases(item, scope.aliases); for (const w of sel.with) if (w.expr) collectAliases(w.expr, scope.withExprs); for (const x of [sel.prewhere, sel.where, sel.having, ...sel.groupBy, ...sel.orderBy.map((o) => o.e)]) if (x) collectAliases(x, scope.aliases); // FROM const rows: JRow[] = this.from(sel.from, scope); this.check(sel, scope); // arrayJoin in the SELECT list multiplies rows before filtering. const ajNodes: Array> = []; const findAj = (e: Expr): void => { if (e.k === 'fn' && e.name.toLowerCase() === 'arrayjoin') { ajNodes.push(e); return; } forEachChild(e, findAj); }; sel.items.forEach(findAj); let ajRows: Array<{ row: JRow; aj?: Map }> = rows.map((row) => ({ row })); if (ajNodes.length > 0) { const expanded: Array<{ row: JRow; aj: Map }> = []; for (const { row } of ajRows) { let combos: Array> = [new Map()]; for (const node of ajNodes) { const next: Array> = []; for (const combo of combos) { const env: Env = { scope, row, aliasCache: new Map(), evaluating: new Set(), aj: combo }; if (node.args.length !== 1) fail('arrayJoin requires exactly one argument'); const arr = evalExpr(node.args[0]!, env); if (!Array.isArray(arr)) fail(`arrayJoin: argument must be an array, got ${valueToText(arr)}`); for (const v of arr as unknown[]) { const m = new Map(combo); m.set(node, v); next.push(m); } } combos = next; } for (const aj of combos) expanded.push({ row, aj }); } ajRows = expanded; } const envOf = (r: { row: JRow; aj?: Map }): Env => ({ scope, row: r.row, aliasCache: new Map(), evaluating: new Set(), ...(r.aj ? { aj: r.aj } : {}) }); for (const cond of [sel.prewhere, sel.where]) { if (!cond) continue; if (containsAggregate(cond, scope.aliases)) fail('Aggregate function is found in WHERE or PREWHERE in query'); ajRows = ajRows.filter((r) => truth(evalExpr(cond, envOf(r))) === true); } const aggregate = sel.groupBy.length > 0 || sel.items.some((i) => containsAggregate(i, scope.aliases)) || (sel.having !== undefined); // Expand * and t.* in place. const finalItems: Array<{ name: string; e: Expr }> = []; for (const item of sel.items) { if (item.k === 'star') { const srcs = item.qualifier === undefined ? scope.sources.map((_, i) => i) : [findSource(scope, item.qualifier) ?? fail(`Unknown table expression identifier '${item.qualifier}'`)]; for (const s of srcs) { const src = scope.sources[s]!; for (const c of src.columns) { if (item.qualifier === undefined && s > 0 && scope.usingKeys.has(c.name)) continue; const q = src.alias ?? src.name; finalItems.push({ name: joinedColumnName(scope, s, c.name), e: { k: 'id', parts: q ? [q, c.name] : [c.name] } }); } } continue; } finalItems.push({ name: item.k === 'id' ? idOutputName(scope, item.parts) : exprName(item), e: item }); } if (finalItems.length === 0) fail('Empty list of columns in SELECT query'); // an item's own alias does not name the item inside it (`groupArraySample(1)(p) AS p` reads the column p) const columns: ClickHouseColumn[] = finalItems.map((it) => ({ name: it.name, type: typeOf(it.e, scope, new Set([it.name])) })); type Out = { values: unknown[]; keys: unknown[] }; let out: Out[] = []; if (aggregate) { // Validate that every plain column in the output is grouped (ClickHouse's NOT_AN_AGGREGATE). // Positional GROUP BY is off by default in ClickHouse: a constant key groups everything. const groupKeys = sel.groupBy; checkGroupKeys(sel, scope.aliases); for (const it of finalItems) checkAggregateProjection(it.e, groupKeys, scope); checkAggregateOrder(sel, scope, finalItems.map((it) => it.name)); const groups = new Map }>>(); const order: string[] = []; for (const r of ajRows) { const env = envOf(r); const key = groupKeys.map((g) => valueKey(evalExpr(g, env))).join('\u0001'); let g = groups.get(key); if (!g) { g = []; groups.set(key, g); order.push(key); } g.push(r); } if (sel.groupBy.length === 0 && order.length === 0) { groups.set('', []); order.push(''); } for (const key of order) { const members = groups.get(key)!; const first = members[0] ?? { row: this.defaultRow(scope) }; const env: Env = { scope, row: first.row, group: members.map((m) => m.row), aliasCache: new Map(), evaluating: new Set(), ...(first.aj ? { aj: first.aj } : {}) }; if (sel.having && truth(evalExpr(sel.having, env)) !== true) continue; const values = finalItems.map((it) => evalExpr(it.e, env)); const keys = sel.orderBy.map((o) => this.orderValue(o.e, env, finalItems, values)); out.push({ values, keys }); } } else { for (const r of ajRows) { const env = envOf(r); const values = finalItems.map((it) => evalExpr(it.e, env)); const keys = sel.orderBy.map((o) => this.orderValue(o.e, env, finalItems, values)); out.push({ values, keys }); } } if (sel.distinct) { const seen = new Set(); out = out.filter((o) => { const k = o.values.map(valueKey).join('\u0001'); if (seen.has(k)) return false; seen.add(k); return true; }); } if (sel.orderBy.length > 0) { const decorated = out.map((o, i) => ({ o, i })); decorated.sort((x, y) => { for (let k = 0; k < sel.orderBy.length; k++) { const spec = sel.orderBy[k]!; const a = x.o.keys[k]; const b = y.o.keys[k]; const an = a === null || a === undefined || (typeof a === 'number' && Number.isNaN(a)); const bn = b === null || b === undefined || (typeof b === 'number' && Number.isNaN(b)); if (an || bn) { if (an && bn) continue; return (an ? 1 : -1) * (spec.nullsFirst ? -1 : 1); } const c = compareValues(a, b); if (c !== 0) return spec.desc ? -c : c; } return x.i - y.i; }); out = decorated.map((d) => d.o); } const before = out.length; const constEnv: Env = { scope: { ...scope, sources: [] }, row: [], aliasCache: new Map(), evaluating: new Set() }; const offset = sel.offset ? Math.max(0, Math.trunc(asNumber(evalExpr(sel.offset, constEnv)) ?? 0)) : 0; const limit = sel.limit ? Math.max(0, Math.trunc(asNumber(evalExpr(sel.limit, constEnv)) ?? 0)) : undefined; if (offset > 0 || limit !== undefined) out = out.slice(offset, limit === undefined ? undefined : offset + limit); return { rel: { columns, rows: out.map((o) => o.values) }, ...(sel.limit || sel.offset ? { rowsBeforeLimit: before } : {}), }; } /** The analyzer pass: every expression of the SELECT resolves (see "static checking"). */ private check(sel: Select, scope: Scope): void { const exprs: Expr[] = [...sel.items]; for (const w of sel.with) if (w.expr) exprs.push(w.expr); for (const f of sel.from) if (f.join?.on) exprs.push(f.join.on); for (const x of [sel.prewhere, sel.where, sel.having, sel.limit, sel.offset, ...sel.groupBy, ...sel.orderBy.map((o) => o.e)]) if (x) exprs.push(x); for (const e of exprs) this.checkExpr(e, scope, new Set()); } private checkExpr(e: Expr, scope: Scope, lambdas: Set): void { const sub = (x: Expr) => this.checkExpr(x, scope, lambdas); switch (e.k) { case 'id': if (e.parts.length === 1 && lambdas.has(e.parts[0]!)) return; checkId(e.parts, scope); return; case 'lambda': this.checkExpr(e.body, scope, new Set([...lambdas, ...e.params])); return; case 'subquery': if (this.validating) this.run(e.q, scope); return; case 'cast': if (!isModeledSchemaType(e.type)) fail(`Unknown data type family: ${typeHead(e.type)}`); sub(e.e); return; case 'fn': { if (!isKnownFunction(e.name)) fail(`Unknown function ${e.name}`); const lname = e.name.toLowerCase(); const agg = parseAggregate(lname); if (agg && (agg.base === 'sum' || agg.base === 'avg') && agg.mode !== 'merge' && e.args[0] && certainlyString(e.args[0], scope, lambdas)) { fail(`Illegal type String of argument for aggregate function ${e.name}`); } e.params?.forEach(sub); for (const a of e.args) if (a.k !== 'star') sub(a); return; } case 'bin': { if (e.op === 'in' || e.op === 'notin') { sub(e.a); const rhs = e.b; if (rhs.k === 'id' && rhs.parts.length === 1 && !lambdas.has(rhs.parts[0]!) && !findColumn(scope, rhs.parts[0]!) && !scope.aliases.has(rhs.parts[0]!) && !scope.withExprs.has(rhs.parts[0]!)) { if (this.validating) this.table(rhs.parts[0]!, false, scope); return; } sub(rhs); return; } const op = ARITHMETIC_NAMES[e.op]; if (op) { const isInterval = (x: Expr) => x.k === 'interval' || (x.k === 'fn' && /^tointerval/i.test(x.name)); if (!isInterval(e.a) && !isInterval(e.b) && (certainlyString(e.a, scope, lambdas) || certainlyString(e.b, scope, lambdas))) { fail(`Illegal types ${typeOf(e.a, scope)} and ${typeOf(e.b, scope)} of arguments of function ${op}`); } } sub(e.a); sub(e.b); return; } default: forEachChild(e, sub); } } private orderValue(e: Expr, env: Env, items: Array<{ name: string; e: Expr }>, values: unknown[]): unknown { // `ORDER BY ` reads the computed output column. if (e.k === 'id' && e.parts.length === 1) { const i = items.findIndex((it) => it.name === e.parts[0]); if (i >= 0) return values[i]; } const same = items.findIndex((it) => sameExpr(it.e, e)); if (same >= 0) return values[same]; return evalExpr(e, env); } private defaultRow(scope: Scope): JRow { return scope.sources.map((s) => s.columns.map((c) => defaultOf(c.type))); } private relationOf(item: FromItem, scope: Scope): Relation { if (item.source.kind === 'sub') return this.run(item.source.query, scope); return this.table(item.source.name, item.final, scope); } private from(items: FromItem[], scope: Scope): JRow[] { if (items.length === 0) return [[]]; const first = items[0]!; const firstRel = this.relationOf(first, scope); scope.sources.push(makeSource(firstRel, first.alias, first.source.kind === 'table' ? first.source.name : undefined)); let rows: JRow[] = firstRel.rows.map((r) => [r]); for (const item of items.slice(1)) { const rel = this.relationOf(item, scope); const src = makeSource(rel, item.alias, item.source.kind === 'table' ? item.source.name : undefined); const leftSources = scope.sources.slice(); scope.sources.push(src); const join = item.join!; const rightDefault = rel.columns.map((c) => defaultOf(c.type)); const leftDefault = leftSources.map((s) => s.columns.map((c) => defaultOf(c.type))); if (join.kind === 'cross') { const next: JRow[] = []; for (const l of rows) for (const r of rel.rows) next.push([...l, r]); rows = next; continue; } if (join.using) { const using = join.using; for (const k of using) scope.usingKeys.add(k); const leftScope: Scope = { ...scope, sources: leftSources, aliases: new Map() }; const leftKey = (l: JRow) => using.map((k) => { const col = findColumn(leftScope, k); if (!col) return fail(`USING column '${k}' is not found in the left table`); return l[col.s]![col.c]; }); const rightIdx = using.map((k) => src.index.get(k) ?? fail(`USING column '${k}' is not found in the right table`)); // Hash the right side on the USING key. const buckets = new Map(); for (const r of rel.rows) { const key = rightIdx.map((i) => valueKey(r[i])).join('\u0001'); let b = buckets.get(key); if (!b) { b = []; buckets.set(key, b); } b.push(r); } const probe = (l: JRow): unknown[][] => { const lk = leftKey(l); if (lk.some((v) => v === null)) return []; const key = lk.map((v, i) => { const sample = rel.rows.find((r) => r[rightIdx[i]!] !== null)?.[rightIdx[i]!]; return valueKeyAs(v, sample); }).join('\u0001'); return buckets.get(key) ?? []; }; rows = this.combine(rows, rel.rows, join, probe, rightDefault, leftDefault); continue; } const on = join.on!; const env0: Env = { scope, row: [], aliasCache: new Map(), evaluating: new Set() }; const matches = (l: JRow, r: unknown[]): boolean => truth(evalExpr(on, { ...env0, row: [...l, r], aliasCache: new Map() })) === true; const probe = (l: JRow): unknown[][] => rel.rows.filter((r) => matches(l, r)); rows = this.combine(rows, rel.rows, join, probe, rightDefault, leftDefault); } return rows; } private combine(left: JRow[], right: unknown[][], join: NonNullable, probe: (l: JRow) => unknown[][], rightDefault: unknown[], leftDefault: unknown[][]): JRow[] { const out: JRow[] = []; const matchedRight = new Set(); for (const l of left) { let hits = probe(l); if (join.strictness === 'any' && hits.length > 1) hits = [hits[0]!]; if (join.strictness === 'semi') { if (hits.length) out.push([...l, hits[0]!]); continue; } if (join.strictness === 'anti') { if (!hits.length) out.push([...l, rightDefault]); continue; } if (hits.length === 0) { if (join.kind === 'left' || join.kind === 'full') out.push([...l, rightDefault]); continue; } for (const r of hits) { matchedRight.add(r); out.push([...l, r]); } } if (join.kind === 'right' || join.kind === 'full') { for (const r of right) if (!matchedRight.has(r)) out.push([...leftDefault, r]); } return out; } } function forEachChild(e: Expr, fn: (c: Expr) => void): void { switch (e.k) { case 'alias': fn(e.e); return; case 'fn': e.args.forEach(fn); return; case 'bin': fn(e.a); fn(e.b); return; case 'not': case 'neg': case 'isnull': fn(e.a); return; case 'between': fn(e.a); fn(e.lo); fn(e.hi); return; case 'case': if (e.operand) fn(e.operand); e.whens.forEach(([a, b]) => { fn(a); fn(b); }); if (e.else) fn(e.else); return; case 'array': case 'tuple': e.items.forEach(fn); return; case 'index': fn(e.a); fn(e.i); return; case 'interval': fn(e.n); return; case 'cast': fn(e.e); return; case 'lambda': fn(e.body); return; default: return; } } /** GROUP BY keys are row expressions: an aggregate there (directly or through an alias) is refused. */ function checkGroupKeys(sel: Select, aliases: Map): void { for (const g of sel.groupBy) { if (containsAggregate(g, aliases)) fail(`Aggregate function found in GROUP BY: ${exprText(g)}`); } } /** In an aggregate query ORDER BY and HAVING may only use what the grouping produces. */ function checkAggregateOrder(sel: Select, scope: Scope, outputNames: string[] = []): void { const names = new Set([...outputNames, ...sel.items.filter((i) => i.k === 'alias').map((i) => (i as { name: string }).name)]); for (const o of sel.orderBy) { if (o.e.k === 'id' && o.e.parts.length === 1 && names.has(o.e.parts[0]!)) continue; try { checkAggregateProjection(o.e, sel.groupBy, scope); } catch (e) { if (e instanceof ClickHouseError) throw new ClickHouseError(`${e.message} (in ORDER BY)`, e.status); throw e; } } } /** ClickHouse's NOT_AN_AGGREGATE: a plain column in an aggregate query must be a grouping key. */ function checkAggregateProjection(e: Expr, keys: Expr[], scope: Scope, seen = new Set()): void { if (keys.some((k) => sameExpr(k, e))) return; // `expr AS name … GROUP BY name`: the aliased expression is itself the key. if (e.k === 'alias' && keys.some((k) => k.k === 'id' && k.parts.length === 1 && k.parts[0] === e.name)) return; switch (e.k) { case 'fn': if (isAggregateName(e.name)) return; e.args.forEach((a) => checkAggregateProjection(a, keys, scope, seen)); return; case 'id': { if (e.parts.length === 1) { const name = e.parts[0]!; if (keys.some((k) => k.k === 'id' && k.parts.length === 1 && k.parts[0] === name)) return; const alias = scope.aliases.get(name); if (alias && !seen.has(name)) { // An alias that IS a group key (by name or by expression) is fine. if (keys.some((k) => sameExpr(k, alias))) return; seen.add(name); checkAggregateProjection(alias, keys, scope, seen); seen.delete(name); return; } if (scope.withExprs.has(name)) return; } const col = e.parts[e.parts.length - 1]!; if (keys.some((k) => k.k === 'id' && k.parts[k.parts.length - 1] === col)) return; // Group keys that are aliases whose expression is this column. if (keys.some((k) => k.k === 'id' && k.parts.length === 1 && scope.aliases.get(k.parts[0]!) && sameExpr(scope.aliases.get(k.parts[0]!)!, e))) return; fail(`Column '${e.parts.join('.')}' is not under an aggregate function and not in GROUP BY keys`); return; } case 'lambda': return; case 'subquery': return; default: forEachChild(e, (c) => checkAggregateProjection(c, keys, scope, seen)); } } // ── the public result API ─────────────────────────────────────────────────────────────────── export type QueryResult = { meta: ClickHouseColumn[]; data: Array>; rows: number; rowsBeforeLimitAtLeast?: number; rowsRead: number; bytesRead: number; }; /** Execute a parsed query against a catalog and shape Tinybird's result envelope. */ export function executeSql(q: Query, catalog: Catalog, nowMs: number, opts: { validate?: boolean } = {}): QueryResult { const exec = new Executor(catalog, nowMs, opts.validate === true); const { rel, rowsBeforeLimit } = exec.runTop(q); return relationResult(rel, exec, rowsBeforeLimit); } /** Run a query to a Relation (for materialized views and node chaining). */ export function runSql(q: Query, catalog: Catalog, nowMs: number, opts: { validate?: boolean } = {}): Relation { const exec = new Executor(catalog, nowMs, opts.validate === true); return exec.run(q); } function relationResult(rel: Relation, exec: Executor, rowsBeforeLimit?: number): QueryResult { const data = rel.rows.map((r) => { const o: Record = {}; rel.columns.forEach((c, i) => { o[c.name] = toOutput(r[i]); }); return o; }); return { meta: rel.columns.map((c) => ({ name: c.name, type: c.type })), data, rows: data.length, ...(rowsBeforeLimit !== undefined ? { rowsBeforeLimitAtLeast: rowsBeforeLimit } : {}), rowsRead: exec.rowsRead, bytesRead: exec.bytesRead, }; } /** Every table name a query reads (FROM / JOIN / IN-subqueries), excluding its own CTEs. */ export function usedTables(q: Query): string[] { const out = new Set(); const ctes = new Set(); const visitQuery = (query: Query): void => query.selects.forEach(visitSelect); const visitExpr = (e: Expr): void => { if (e.k === 'subquery') { visitQuery(e.q); return; } if ((e.k === 'bin') && (e.op === 'in' || e.op === 'notin') && e.b.k === 'id' && e.b.parts.length === 1) { visitExpr(e.a); return; } forEachChild(e, visitExpr); }; const visitSelect = (s: Select): void => { for (const w of s.with) { if (w.query) { ctes.add(w.name); visitQuery(w.query); } else if (w.expr) visitExpr(w.expr); } for (const f of s.from) { if (f.source.kind === 'table') { if (!ctes.has(f.source.name)) out.add(f.source.name); } else visitQuery(f.source.query); if (f.join?.on) visitExpr(f.join.on); } s.items.forEach(visitExpr); [s.prewhere, s.where, s.having, s.limit, s.offset].forEach((x) => { if (x) visitExpr(x); }); s.groupBy.forEach(visitExpr); s.orderBy.forEach((o) => visitExpr(o.e)); }; visitQuery(q); return [...out]; } /** The left-most table of the first SELECT — a materialized view's trigger table. */ export function primaryTable(q: Query): string | undefined { const first = q.selects[0]?.from[0]; if (!first) return undefined; if (first.source.kind === 'table') return first.source.name; return primaryTable(first.source.query); } export function queryStatistics(result: QueryResult): { elapsed: number; rows_read: number; bytes_read: number } { return { elapsed: Number((result.rowsRead * 0.000001 + 0.000123).toFixed(9)), rows_read: result.rowsRead, bytes_read: result.bytesRead, }; } // ── response formats ──────────────────────────────────────────────────────────────────────── /** * One CSV field as ClickHouse writes it: strings, dates, times, arrays and other compound values * double-quoted (`"` doubled inside), numbers and booleans bare, NULL as `\N` * (`format_csv_null_representation`), an array in its text form (`"['a','b']"`). */ function csvCell(v: unknown, type: string): string { if (v === null || v === undefined) return '\\N'; const h = typeHead(type); const bare = isNumberType(type) || h === 'Bool' || h === 'Boolean' || h === 'Nothing'; const text = Array.isArray(v) ? outputArrayText(v, arrayElementType(type)) : typeof v === 'object' ? JSON.stringify(v) : String(v); if (bare && !Array.isArray(v)) return text; return `"${text.replace(/"/g, '""')}"`; } /** An output array's ClickHouse text form: `[1,2]`, `['a','b']`. */ function outputArrayText(arr: unknown[], elementType: string): string { const quote = !(isNumberType(elementType) || /^(Bool|Boolean)$/.test(typeHead(elementType))); return `[${arr.map((x) => (x === null || x === undefined ? 'NULL' : Array.isArray(x) ? outputArrayText(x, arrayElementType(elementType)) : quote ? `'${String(x).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'` : String(x))).join(',')}]`; } /** * Render a result in one of the modeled text formats (`.json` is handled by the caller): * ClickHouse's JSONEachRow and CSV / CSVWithNames, every row (and the header) ending in `\n`. */ export function renderFormat(format: 'ndjson' | 'csv' | 'csvwithnames', result: QueryResult): string { if (format === 'ndjson') return result.data.map((r) => `${stringifyJson(r)}\n`).join(''); const lines = result.data.map((r) => result.meta.map((m) => csvCell(r[m.name], m.type)).join(',')); if (format === 'csvwithnames') lines.unshift(result.meta.map((m) => `"${m.name.replace(/"/g, '""')}"`).join(',')); return lines.map((l) => `${l}\n`).join(''); } // ── single-table conveniences (the Query API and delete conditions) ───────────────────────── export type QueryPlan = Query; /** Parse a SELECT and apply the checks ClickHouse makes before reading any data. */ export function parseQuery(sql: string): Query { const q = parseSql(sql); // A function this engine does not implement is refused by name before any other check. const visitExpr = (e: Expr): void => { if (e.k === 'fn' && !isKnownFunction(e.name)) fail(`Unknown function ${e.name}`); if (e.k === 'subquery') { e.q.selects.forEach(visitSelect); return; } if (e.k === 'fn') e.params?.forEach(visitExpr); forEachChild(e, visitExpr); }; const visitSelect = (sel: Select): void => { for (const w of sel.with) { if (w.expr) visitExpr(w.expr); if (w.query) w.query.selects.forEach(visitSelect); } for (const f of sel.from) { if (f.source.kind === 'sub') f.source.query.selects.forEach(visitSelect); if (f.join?.on) visitExpr(f.join.on); } [...sel.items, ...sel.groupBy, ...sel.orderBy.map((o) => o.e)].forEach(visitExpr); [sel.prewhere, sel.where, sel.having, sel.limit, sel.offset].forEach((x) => { if (x) visitExpr(x); }); }; q.selects.forEach(visitSelect); for (const sel of q.selects) { const aliases = new Map(); sel.items.forEach((i) => collectAliases(i, aliases)); const aggregate = sel.groupBy.length > 0 || sel.items.some((i) => containsAggregate(i, aliases)); if (!aggregate) continue; const scope: Scope = { sources: [], usingKeys: new Set(), aliases, withExprs: new Map(), withCache: new Map(), exec: undefined as unknown as Executor, subCache: new Map() }; for (const w of sel.with) if (w.expr) scope.withExprs.set(w.name, w.expr); checkGroupKeys(sel, aliases); for (const it of sel.items) if (it.k !== 'star') checkAggregateProjection(it, sel.groupBy, scope); checkAggregateOrder(sel, scope); } return q; } /** Run a query over ONE table's stored rows (any FROM name resolves to it). */ export function executeQuery(q: Query, columns: readonly ClickHouseColumn[], rows: ReadonlyArray>, nowMs = 0): QueryResult { const rel: Relation = { columns: [...columns], rows: rows.map((r) => columns.map((c) => fromStored(r[c.name], c.type))) }; return executeSql(q, { table: () => rel }, nowMs); }