import { ConnectionId } from './connection_id.ts'; import { Identity } from './identity.ts'; import type { ColumnIndex, IndexColumns, IndexOpts, UnbrandedIdentity, } from './indexes.ts'; import type { UntypedSchemaDef } from './schema.ts'; import type { UntypedTableDef } from './table.ts'; import type { UntypedTableSchema } from './table_schema.ts'; import { Timestamp } from './timestamp.ts'; import type { ColumnBuilder, ColumnMetadata, RowBuilder, TypeBuilder, } from './type_builders.ts'; import type { Values } from './type_util.ts'; import type { Bool as SatsBool } from './algebraic_type_variants.ts'; import { Uuid } from './uuid.ts'; /** * Helper to get the set of table names. */ export type TableNames = Values< SchemaDef['tables'] >['accessorName'] & string; /** helper: pick the table def object from the schema by its name */ export type TableDefByName< SchemaDef extends UntypedSchemaDef, Name extends TableNames, > = Extract, { accessorName: Name }>; // internal only — NOT exported. // This is how we make sure queries are only created with our helpers. const QueryBrand = Symbol('QueryBrand'); export interface TableTypedQuery { readonly [QueryBrand]: true; readonly __table?: TableDef; } export interface RowTypedQuery { readonly [QueryBrand]: true; // Phantom type to track the row type. readonly __row?: Row; readonly __algebraicType?: ST; } export type Query = RowTypedQuery< RowType, TableDef['rowType'] >; export const isRowTypedQuery = (val: unknown): val is RowTypedQuery => !!val && typeof val === 'object' && QueryBrand in (val as object); export const isTypedQuery = (val: unknown): val is TableTypedQuery => !!val && typeof val === 'object' && QueryBrand in (val as object); export function toSql(q: Query): string { return (q as unknown as { toSql(): string }).toSql(); } // A query builder with a single table. type From = RowTypedQuery< RowType, TableDef['rowType'] > & Readonly<{ toSql(): string; where( predicate: (row: RowExpr) => PredicateExpr ): From; rightSemijoin( other: TableRef, on: ( left: IndexedRowExpr, right: IndexedRowExpr ) => BooleanExpr ): SemijoinBuilder; leftSemijoin( other: TableRef, on: ( left: IndexedRowExpr, right: IndexedRowExpr ) => BooleanExpr ): SemijoinBuilder; /** @deprecated No longer needed — builder is already a valid query. */ build(): Query; }>; // A query builder with a semijoin. type SemijoinBuilder = RowTypedQuery< RowType, TableDef['rowType'] > & Readonly<{ toSql(): string; where( predicate: (row: RowExpr) => PredicateExpr ): SemijoinBuilder; /** @deprecated No longer needed — builder is already a valid query. */ build(): Query; }>; class SemijoinImpl implements SemijoinBuilder, TableTypedQuery { readonly [QueryBrand] = true; readonly type = 'semijoin' as const; constructor( readonly sourceQuery: FromBuilder, readonly filterQuery: FromBuilder, readonly joinCondition: BooleanExpr ) { if (sourceQuery.table.sourceName === filterQuery.table.sourceName) { // TODO: Handle aliasing properly instead of just forbidding it. throw new Error('Cannot semijoin a table to itself'); } } build(): Query { return this as Query; } where( predicate: (row: RowExpr) => PredicateExpr ): SemijoinImpl { const nextSourceQuery = this.sourceQuery.where(predicate); return new SemijoinImpl( nextSourceQuery, this.filterQuery, this.joinCondition ); } toSql(): string { const left = this.filterQuery; const right = this.sourceQuery; const leftTable = quoteIdentifier(left.table.sourceName); const rightTable = quoteIdentifier(right.table.sourceName); let sql = `SELECT ${rightTable}.* FROM ${leftTable} JOIN ${rightTable} ON ${booleanExprToSql(this.joinCondition)}`; const clauses: string[] = []; if (left.whereClause) { clauses.push(booleanExprToSql(left.whereClause)); } if (right.whereClause) { clauses.push(booleanExprToSql(right.whereClause)); } if (clauses.length > 0) { const whereSql = clauses.length === 1 ? clauses[0] : clauses.map(wrapInParens).join(' AND '); sql += ` WHERE ${whereSql}`; } return sql; } } class FromBuilder implements From, TableTypedQuery { readonly [QueryBrand] = true; constructor( readonly table: TableRef, readonly whereClause?: BooleanExpr ) {} where( predicate: (row: RowExpr) => PredicateExpr ): FromBuilder { const newCondition = normalizePredicateExpr(predicate(this.table.cols)); const nextWhere = this.whereClause ? this.whereClause.and(newCondition) : newCondition; return new FromBuilder(this.table, nextWhere); } rightSemijoin( right: TableRef, on: ( left: IndexedRowExpr, right: IndexedRowExpr ) => BooleanExpr ): SemijoinBuilder { const sourceQuery = new FromBuilder(right); const joinCondition = on( this.table.indexedCols, right.indexedCols ) as BooleanExpr; return new SemijoinImpl(sourceQuery, this, joinCondition); } leftSemijoin( right: TableRef, on: ( left: IndexedRowExpr, right: IndexedRowExpr ) => BooleanExpr ): SemijoinBuilder { const filterQuery = new FromBuilder(right); const joinCondition = on( this.table.indexedCols, right.indexedCols ) as BooleanExpr; return new SemijoinImpl(this, filterQuery, joinCondition); } toSql(): string { return renderSelectSqlWithJoins(this.table, this.whereClause); } build(): Query { return this as Query; } } export type QueryBuilder = { readonly [Tbl in Values< SchemaDef['tables'] > as Tbl['accessorName']]: TableRef & From; } & {}; /** * Like `QueryBuilder`, but with declared namespaces also exposed as sub-objects. * This is the type of the `tables` argument in a `subscribe` query-builder callback. * * Root-level tables appear as direct properties (same as `QueryBuilder`). * Declared namespaces appear as sub-objects — each is itself a `QueryBuilder` for that * namespace's schema, so `tables..` is fully typed. * * When `SchemaDef['namespaces']` is absent or `{}`, no namespace properties appear — * accessing an undeclared namespace is a compile error. */ export type NamespacedQueryBuilder = QueryBuilder & { readonly [NS in keyof NonNullable]: NonNullable< SchemaDef['namespaces'] >[NS] extends UntypedSchemaDef ? QueryBuilder[NS]> : never; }; /** * A runtime reference to a table. This materializes the RowExpr for us. * TODO: Maybe add the full SchemaDef to the type signature depending on how joins will work. */ export type TableRef = Readonly<{ type: 'table'; sourceName: TableDef['sourceName']; accessorName: string; cols: RowExpr; indexedCols: IndexedRowExpr; tableDef: TableDef; // Delegated UntypedTableDef properties for compatibility. columns: TableDef['columns']; indexes: TableDef['indexes']; rowType: TableDef['rowType']; constraints: any; }>; class TableRefImpl implements TableRef, From { readonly [QueryBrand] = true; readonly type = 'table' as const; sourceName: string; accessorName: string; cols: RowExpr; indexedCols: IndexedRowExpr; tableDef: TableDef; // Delegate UntypedTableDef properties from tableDef so this can be used as a table def. get columns() { return this.tableDef.columns; } get indexes() { return this.tableDef.indexes; } get rowType() { return this.tableDef.rowType; } get constraints() { return (this.tableDef as any).constraints; } constructor(tableDef: TableDef) { this.sourceName = tableDef.sourceName; this.accessorName = tableDef.accessorName; this.cols = createRowExpr(tableDef); // this.indexedCols = createIndexedRowExpr(tableDef, this.cols); // TODO: we could create an indexedRowExpr to avoid having the extra columns. // Right now, the objects we pass will actually have all the columns, but the // type system will consider it an error. this.indexedCols = this.cols; this.tableDef = tableDef; Object.freeze(this); } asFrom(): FromBuilder { return new FromBuilder(this); } rightSemijoin( other: TableRef, on: ( left: IndexedRowExpr, right: IndexedRowExpr ) => EqExpr ): SemijoinBuilder { return this.asFrom().rightSemijoin(other, on); } leftSemijoin( other: TableRef, on: ( left: IndexedRowExpr, right: IndexedRowExpr ) => EqExpr ): SemijoinBuilder { return this.asFrom().leftSemijoin(other, on); } build(): Query { return this.asFrom().build(); } toSql(): string { return this.asFrom().toSql(); } where( predicate: (row: RowExpr) => PredicateExpr ): FromBuilder { return this.asFrom().where(predicate); } } export function createTableRefFromDef( tableDef: TableDef ): TableRef { return new TableRefImpl(tableDef); } export function makeQueryBuilder( schema: SchemaDef ): QueryBuilder { const qb = Object.create(null) as QueryBuilder; for (const table of Object.values(schema.tables)) { const ref = createTableRefFromDef( table as TableDefByName> ); (qb as Record>)[table.accessorName] = ref; } return Object.freeze(qb) as QueryBuilder; } /** * Builds the namespace-aware `tables` object passed to `subscribe`'s query-builder callback. * * Tables whose `sourceName` contains no `.` are placed at the root. * Tables with a dotted `sourceName` (e.g. `"namespace.table"`) are grouped under a * sub-object keyed by the namespace alias, with the part after the dot as the * property key within that namespace. */ export function makeFromBuilder( tables: SchemaDef['tables'] ): NamespacedQueryBuilder { const result: Record = Object.create(null); const namespaces: Record> = Object.create( null ); for (const table of Object.values(tables) as UntypedTableDef[]) { const dotIdx = table.sourceName.indexOf('.'); if (dotIdx === -1) { result[table.accessorName] = createTableRefFromDef(table as any); } else { const ns = table.sourceName.slice(0, dotIdx); const key = table.sourceName.slice(dotIdx + 1); (namespaces[ns] ??= Object.create(null))[key] = createTableRefFromDef( table as any ); } } for (const [ns, nsTables] of Object.entries(namespaces)) { result[ns] = Object.freeze(nsTables); } return Object.freeze(result) as unknown as NamespacedQueryBuilder; } function createRowExpr( tableDef: TableDef ): RowExpr { const row: Record> = {}; for (const columnName of Object.keys(tableDef.columns) as Array< keyof TableDef['columns'] & string >) { const columnBuilder = tableDef.columns[columnName]; const column = new ColumnExpression( tableDef.sourceName, columnName, columnBuilder.typeBuilder.algebraicType as InferSpacetimeTypeOfColumn< TableDef, typeof columnName >, columnBuilder.columnMetadata.name ); row[columnName] = Object.freeze(column); } return Object.freeze(row) as RowExpr; } function renderSelectSqlWithJoins
( table: TableRef
, where?: BooleanExpr
, extraClauses: readonly string[] = [] ): string { const quotedTable = quoteIdentifier(table.sourceName); const sql = `SELECT * FROM ${quotedTable}`; const clauses: string[] = []; if (where) clauses.push(booleanExprToSql(where)); clauses.push(...extraClauses); if (clauses.length === 0) return sql; const whereSql = clauses.length === 1 ? clauses[0] : clauses.map(wrapInParens).join(' AND '); return `${sql} WHERE ${whereSql}`; } // TODO: Just use UntypedTableDef if they end up being the same. export type TypedTableDef< Columns extends Record< string, ColumnBuilder> > = Record>>, > = { sourceName: string; accessorName: string; columns: Columns; indexes: readonly IndexOpts[]; rowType: RowBuilder['algebraicType']['value']; }; export type TableSchemaAsTableDef = { name: TSchema['tableName']; columns: TSchema['rowType']['row']; indexes: TSchema['idxs']; }; type RowType = { [K in keyof TableDef['columns']]: TableDef['columns'][K] extends ColumnBuilder< infer T, any, any > ? T : never; }; // TODO: Consider making a smaller version of these types that doesn't expose the internals. // Restricting it later should not break anyone in practice. export type ColumnExpr< TableDef extends TypedTableDef, ColumnName extends ColumnNames, > = ColumnExpression; type ColumnSpacetimeType> = Col extends ColumnExpr ? InferSpacetimeTypeOfColumn : never; // TODO: This checks that they match, but we also need to make sure that they are comparable types, // since you can use product types at all. type ColumnSameSpacetime< ThisTable extends TypedTableDef, ThisCol extends ColumnNames, OtherCol extends ColumnExpr, > = [InferSpacetimeTypeOfColumn] extends [ ColumnSpacetimeType, ] ? [ColumnSpacetimeType] extends [ InferSpacetimeTypeOfColumn, ] ? OtherCol : never : never; // Helper to get the table back from a column. type ExtractTable> = Col extends ColumnExpr ? T : never; export class ColumnExpression< TableDef extends TypedTableDef, ColumnName extends ColumnNames, > { readonly type = 'column' as const; // This is the column accessor readonly column: ColumnName; // The name of the column in the database. readonly columnName: string; readonly table: TableDef['sourceName']; // phantom: actual runtime value is undefined readonly tsValueType?: RowType[ColumnName]; readonly spacetimeType: InferSpacetimeTypeOfColumn; constructor( table: TableDef['sourceName'], column: ColumnName, spacetimeType: InferSpacetimeTypeOfColumn, columnName?: string ) { this.table = table; this.column = column; this.columnName = columnName || column; this.spacetimeType = spacetimeType; } eq( literal: LiteralValue & UnbrandedIdentity[ColumnName]> ): BooleanExpr; eq>( value: ColumnSameSpacetime ): BooleanExpr>; eq(x: any): any { return new BooleanExpr({ type: 'eq', left: this as unknown as ValueExpr, right: normalizeValue(x) as ValueExpr, }); } ne( literal: LiteralValue & UnbrandedIdentity[ColumnName]> ): BooleanExpr; ne>( value: ColumnSameSpacetime ): BooleanExpr>; ne(x: any): any { return new BooleanExpr({ type: 'ne', left: this as unknown as ValueExpr, right: normalizeValue(x) as ValueExpr, }); } lt( literal: LiteralValue & UnbrandedIdentity[ColumnName]> ): BooleanExpr; lt>( value: ColumnSameSpacetime ): BooleanExpr>; lt(x: any): any { return new BooleanExpr({ type: 'lt', left: this as unknown as ValueExpr, right: normalizeValue(x) as ValueExpr, }); } lte( literal: LiteralValue & UnbrandedIdentity[ColumnName]> ): BooleanExpr; lte>( value: ColumnSameSpacetime ): BooleanExpr>; lte(x: any): any { return new BooleanExpr({ type: 'lte', left: this as unknown as ValueExpr, right: normalizeValue(x) as ValueExpr, }); } gt( literal: LiteralValue & UnbrandedIdentity[ColumnName]> ): BooleanExpr; gt>( value: ColumnSameSpacetime ): BooleanExpr>; gt(x: any): any { return new BooleanExpr({ type: 'gt', left: this as unknown as ValueExpr, right: normalizeValue(x) as ValueExpr, }); } gte( literal: LiteralValue & UnbrandedIdentity[ColumnName]> ): BooleanExpr; gte>( value: ColumnSameSpacetime ): BooleanExpr>; gte(x: any): any { return new BooleanExpr({ type: 'gte', left: this as unknown as ValueExpr, right: normalizeValue(x) as ValueExpr, }); } } /** * Helper to get the spacetime type of a column. */ type InferSpacetimeTypeOfColumn< TableDef extends TypedTableDef, ColumnName extends ColumnNames, > = TableDef['columns'][ColumnName]['typeBuilder'] extends TypeBuilder< any, infer U > ? U : never; type ColumnNames = keyof RowType & string; // For composite indexes, we only consider it as an index over the first column in the index. type FirstIndexColumn> = IndexColumns extends readonly [infer Head extends string, ...infer _Rest] ? Head : never; // Columns that are indexed by something in the indexes: [...] part. type ExplicitIndexedColumns = TableDef['indexes'][number] extends infer I ? I extends IndexOpts> ? FirstIndexColumn & ColumnNames : never : never; // Columns with an index defined on the column definition. type MetadataIndexedColumns = { [K in ColumnNames]: ColumnIndex< K, TableDef['columns'][K]['columnMetadata'] > extends never ? never : K; }[ColumnNames]; export type IndexedColumnNames = | ExplicitIndexedColumns | MetadataIndexedColumns; export type IndexedRowExpr = Readonly<{ readonly [C in IndexedColumnNames]: ColumnExpr; }>; /** * Acts as a row when writing filters for queries. It is a way to get column references. */ export type RowExpr = Readonly<{ readonly [C in ColumnNames]: ColumnExpr; }>; /** * Union of ColumnExprs from Table whose spacetimeType is compatible with Value * (produces a union of ColumnExpr for matching columns). */ export type ColumnExprForValue
= { [C in ColumnNames
]: InferSpacetimeTypeOfColumn extends Value ? ColumnExpr : never; }[ColumnNames
]; type LiteralValue = | string | number | bigint | boolean | Identity | Uuid | Timestamp | ConnectionId; type ValueLike = LiteralValue | ColumnExpr | LiteralExpr; type ValueInput = | ValueLike | ValueExpr; export type ValueExpr = | LiteralExpr | ColumnExprForValue; type PredicateExpr = | BooleanExpr | ColumnExprForValue | boolean; type LiteralExpr = { type: 'literal'; value: Value; }; export function literal( value: Value ): ValueExpr { return { type: 'literal', value }; } // This is here to take literal values and wrap them in an AST node. function normalizeValue(val: ValueInput): ValueExpr { if ((val as LiteralExpr).type === 'literal') return val as LiteralExpr; if ( typeof val === 'object' && val != null && 'type' in (val as any) && (val as any).type === 'column' ) { return val as ColumnExpr; } return literal(val as LiteralValue); } function normalizePredicateExpr( value: PredicateExpr ): BooleanExpr { if (value instanceof BooleanExpr) return value; if (typeof value === 'boolean') { return new BooleanExpr({ type: 'eq', left: literal(value), right: literal(true), }); } return new BooleanExpr({ type: 'eq', left: value as ValueExpr, right: literal(true), }); } type EqExpr
= BooleanExpr
; type BooleanExprData
= ( | { type: 'eq' | 'ne' | 'gt' | 'lt' | 'gte' | 'lte'; left: ValueExpr; right: ValueExpr; } | { type: 'and'; clauses: readonly [ BooleanExprData
, BooleanExprData
, ...BooleanExprData
[], ]; } | { type: 'or'; clauses: readonly [ BooleanExprData
, BooleanExprData
, ...BooleanExprData
[], ]; } | { type: 'not'; clause: BooleanExprData
; } ) & { _tableType?: Table; }; type AndOrMixedTableScopeError = { readonly 'Cannot combine predicates from different table scopes with and/or. In semijoin on(...), keep only the join equality and move extra predicates to .where(...).': never; }; type RequireSameAndOrTable< Expected extends TypedTableDef, Actual extends TypedTableDef, > = [Expected] extends [Actual] ? [Actual] extends [Expected] ? unknown : AndOrMixedTableScopeError : AndOrMixedTableScopeError; export class BooleanExpr
{ constructor(readonly data: BooleanExprData
) {} and( other: BooleanExpr & RequireSameAndOrTable ): BooleanExpr
{ return new BooleanExpr({ type: 'and', clauses: [this.data, other.data as BooleanExprData
], }); } or( other: BooleanExpr & RequireSameAndOrTable ): BooleanExpr
{ return new BooleanExpr({ type: 'or', clauses: [this.data, other.data as BooleanExprData
], }); } not(): BooleanExpr
{ return new BooleanExpr({ type: 'not', clause: this.data }); } } export function not( clause: BooleanExpr ): BooleanExpr { return new BooleanExpr({ type: 'not', clause: clause.data }); } export function and< Table extends TypedTableDef, OtherTable extends TypedTableDef, >( first: BooleanExpr
, second: BooleanExpr & RequireSameAndOrTable, ...rest: readonly BooleanExpr
[] ): BooleanExpr
{ const clauses = [first, second, ...rest]; return new BooleanExpr({ type: 'and', clauses: clauses.map(c => c.data) as [ BooleanExprData
, BooleanExprData
, ...BooleanExprData
[], ], }); } export function or< Table extends TypedTableDef, OtherTable extends TypedTableDef, >( first: BooleanExpr
, second: BooleanExpr & RequireSameAndOrTable, ...rest: readonly BooleanExpr
[] ): BooleanExpr
{ const clauses = [first, second, ...rest]; return new BooleanExpr({ type: 'or', clauses: clauses.map(c => c.data) as [ BooleanExprData
, BooleanExprData
, ...BooleanExprData
[], ], }); } function booleanExprToSql
( expr: BooleanExpr
| BooleanExprData
, tableAlias?: string ): string { const data = expr instanceof BooleanExpr ? expr.data : expr; switch (data.type) { case 'eq': return `${valueExprToSql(data.left, tableAlias)} = ${valueExprToSql(data.right, tableAlias)}`; case 'ne': return `${valueExprToSql(data.left, tableAlias)} <> ${valueExprToSql(data.right, tableAlias)}`; case 'gt': return `${valueExprToSql(data.left, tableAlias)} > ${valueExprToSql(data.right, tableAlias)}`; case 'gte': return `${valueExprToSql(data.left, tableAlias)} >= ${valueExprToSql(data.right, tableAlias)}`; case 'lt': return `${valueExprToSql(data.left, tableAlias)} < ${valueExprToSql(data.right, tableAlias)}`; case 'lte': return `${valueExprToSql(data.left, tableAlias)} <= ${valueExprToSql(data.right, tableAlias)}`; case 'and': return data.clauses .map(c => booleanExprToSql(c, tableAlias)) .map(wrapInParens) .join(' AND '); case 'or': return data.clauses .map(c => booleanExprToSql(c, tableAlias)) .map(wrapInParens) .join(' OR '); case 'not': return `NOT ${wrapInParens(booleanExprToSql(data.clause, tableAlias))}`; } } function wrapInParens(sql: string): string { return `(${sql})`; } function valueExprToSql
( expr: ValueExpr, tableAlias?: string ): string { if (isLiteralExpr(expr)) { return literalValueToSql(expr.value); } const table = tableAlias ?? expr.table; return `${quoteIdentifier(table)}.${quoteIdentifier(expr.columnName)}`; } function literalValueToSql(value: unknown): string { if (value === null || value === undefined) { return 'NULL'; } if ( value instanceof Identity || value instanceof ConnectionId || value instanceof Uuid ) { // We use this hex string syntax. return `0x${value.toHexString()}`; } if (value instanceof Timestamp) { return `'${value.toISOString()}'`; } switch (typeof value) { case 'number': case 'bigint': return String(value); case 'boolean': return value ? 'TRUE' : 'FALSE'; case 'string': return `'${value.replace(/'/g, "''")}'`; default: // It might be safer to error here? return `'${JSON.stringify(value).replace(/'/g, "''")}'`; } } function quoteIdentifier(name: string): string { return name .split('.') .map(part => `"${part.replace(/"/g, '""')}"`) .join('.'); } function isLiteralExpr( expr: ValueExpr ): expr is LiteralExpr { return (expr as LiteralExpr).type === 'literal'; } /** * Evaluate a BooleanExpr against a row at runtime for client-side filtering. */ export function evaluateBooleanExpr( expr: BooleanExpr, row: Record ): boolean { return evaluateData(expr.data, row); } function evaluateData( data: BooleanExprData, row: Record ): boolean { switch (data.type) { case 'eq': return resolveValue(data.left, row) === resolveValue(data.right, row); case 'ne': return resolveValue(data.left, row) !== resolveValue(data.right, row); case 'gt': return resolveValue(data.left, row) > resolveValue(data.right, row); case 'gte': return resolveValue(data.left, row) >= resolveValue(data.right, row); case 'lt': return resolveValue(data.left, row) < resolveValue(data.right, row); case 'lte': return resolveValue(data.left, row) <= resolveValue(data.right, row); case 'and': return data.clauses.every(c => evaluateData(c, row)); case 'or': return data.clauses.some(c => evaluateData(c, row)); case 'not': return !evaluateData(data.clause, row); } } function resolveValue( expr: ValueExpr, row: Record ): any { if (isLiteralExpr(expr)) { return toComparableValue(expr.value); } return toComparableValue(row[expr.column]); } type TimestampLike = { __timestamp_micros_since_unix_epoch__: bigint; }; type HexSerializableLike = { toHexString: () => string; }; function isHexSerializableLike(value: unknown): value is HexSerializableLike { return ( !!value && typeof value === 'object' && typeof (value as { toHexString?: unknown }).toHexString === 'function' ); } // Check if this value is a Timestamp-like object. This is here because // running locally can end up with different versions of the Timestamp class, // which breaks the simple instanceof version. function isTimestampLike(value: unknown): value is TimestampLike { if (!value || typeof value !== 'object') return false; if (value instanceof Timestamp) return true; const micros = (value as Record)[ '__timestamp_micros_since_unix_epoch__' ]; return typeof micros === 'bigint'; } // Exported for tests. export function toComparableValue(value: any): any { // Handle `ConnectionId` and `Identity`. if (isHexSerializableLike(value)) { return value.toHexString(); } if (isTimestampLike(value)) { return value.__timestamp_micros_since_unix_epoch__; } return value; } /** * Extract the table name from a query builder expression. */ export function getQueryTableName(query: any): string { if (query.table) return query.table.name; // FromBuilder if (query.name) return query.name; // TableRefImpl if (query.sourceQuery) return query.sourceQuery.table.name; // SemijoinImpl (source table) throw new Error('Cannot extract table name from query'); } /** * Extract the accessor name from a query builder expression. */ export function getQueryAccessorName(query: any): string { if (query.table) return query.table.accessorName; // FromBuilder if (query.accessorName) return query.accessorName; // TableRefImpl if (query.sourceQuery) return query.sourceQuery.table.accessorName; // SemijoinImpl throw new Error('Cannot extract accessor name from query'); } /** * Extract the BooleanExpr from a query builder, if any. */ export function getQueryWhereClause(query: any): BooleanExpr | undefined { if (query.whereClause) return query.whereClause; // FromBuilder return undefined; // TableRefImpl has no where clause } // TODO: Fix this. function _createIndexedRowExpr( tableDef: TableDef, cols: RowExpr ): IndexedRowExpr { const indexed = new Set>(); for (const idx of tableDef.indexes) { if ('columns' in idx) { const [first] = idx.columns; if (first) indexed.add(first); } else if ('column' in idx) { indexed.add(idx.column); } } const pickedEntries = [...indexed].map(name => [name, cols[name]]); return Object.freeze( Object.fromEntries(pickedEntries) ) as IndexedRowExpr; }