export declare function abs(expr: ExprInput): Expr; /** * AddPartition */ declare type AddPartition = { this: Expression; exists: boolean; location: Expression | null; }; /** * Add columns to a SELECT expression */ declare function addSelectColumns(node: Expression, ...columns: Expression[]): Expression; /** * Add a condition to the WHERE clause of a SELECT (via WASM) * * @example * ```typescript * const newAst = addWhere(selectAst, eq('deleted', false), 'and'); * ``` */ declare function addWhere(node: Expression, condition: Expression, operator?: 'and' | 'or'): Expression; /** * Generic aggregate function base type */ declare type AggFunc = { this: Expression; distinct: boolean; filter: Expression | null; order_by: Array; /** * Original function name (case-preserving) when parsed from SQL */ name?: string | null; /** * IGNORE NULLS (true) or RESPECT NULLS (false), None if not specified */ ignore_nulls?: boolean | null; /** * HAVING MAX/MIN expr inside aggregate (BigQuery syntax) * e.g., ANY_VALUE(fruit HAVING MAX sold) - (expression, is_max: true for MAX, false for MIN) */ having_max?: [Expression, boolean] | null; /** * LIMIT inside aggregate (e.g., ARRAY_AGG(x ORDER BY y LIMIT 2)) */ limit?: Expression | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Union of all aggregate function expression types */ declare type AggregateExpression = ExpressionByType<'count'> | ExpressionByType<'sum'> | ExpressionByType<'avg'> | ExpressionByType<'min'> | ExpressionByType<'max'> | ExpressionByType<'group_concat'> | ExpressionByType<'string_agg'> | ExpressionByType<'list_agg'> | ExpressionByType<'array_agg'> | ExpressionByType<'count_if'> | ExpressionByType<'sum_if'> | ExpressionByType<'stddev'> | ExpressionByType<'variance'> | ExpressionByType<'median'> | ExpressionByType<'mode'> | ExpressionByType<'first'> | ExpressionByType<'last'> | ExpressionByType<'any_value'> | ExpressionByType<'approx_distinct'> | ExpressionByType<'approx_count_distinct'>; /** * Represent a named aggregate function call with optional FILTER, ORDER BY, and LIMIT. * * This struct is used for aggregate function calls that are not covered by * one of the dedicated typed variants (e.g. `Count`, `Sum`). It supports * SQL:2003 FILTER (WHERE ...) clauses, ordered-set aggregates, and * IGNORE NULLS / RESPECT NULLS modifiers. */ declare type AggregateFunction = { /** * The aggregate function name (e.g. "JSON_AGG", "XMLAGG"). */ name: string; /** * Positional arguments. */ args: Array; /** * Whether DISTINCT was specified. */ distinct: boolean; /** * Optional FILTER (WHERE ...) clause applied to the aggregate. */ filter: Expression | null; /** * ORDER BY inside aggregate (e.g., JSON_AGG(x ORDER BY y)) */ order_by?: Array; /** * LIMIT inside aggregate (e.g., ARRAY_CONCAT_AGG(x LIMIT 2)) */ limit?: Expression | null; /** * IGNORE NULLS / RESPECT NULLS */ ignore_nulls?: boolean | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * AIAgg */ declare type AIAgg = { this: Expression; expression: Expression; }; /** * AIClassify */ declare type AIClassify = { this: Expression; categories: Expression | null; config: Expression | null; }; /** * AlgorithmProperty */ declare type AlgorithmProperty = { this: Expression; }; /** * Represent an aliased expression (`expr AS name`). * * Used for column aliases in select-lists, table aliases on subqueries, * and column alias lists on table-valued expressions (e.g. `AS t(c1, c2)`). */ declare type Alias = { /** * The expression being aliased. */ this: Expression; /** * The alias name (required for simple aliases, optional when only column aliases provided) */ alias: Identifier; /** * Optional column aliases for table-valued functions: AS t(col1, col2) or AS (col1, col2) */ column_aliases: Array; /** * Whether AS keyword was explicitly used for the alias. */ alias_explicit_as: boolean; /** * Original alias keyword spelling, e.g. `AS` vs `as`. */ alias_keyword?: string | null; /** * Comments that appeared between the expression and AS keyword */ pre_alias_comments: Array; /** * Trailing comments that appeared after the alias */ trailing_comments: Array; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** Create an expr AS name alias expression. */ export declare function alias(expr: ExprInput, name: string): Expr; /** * Aliases */ declare type Aliases = { this: Expression; expressions: Array; }; /** * AllowedValuesProperty */ declare type AllowedValuesProperty = { expressions: Array; }; /** * AlterColumn */ declare type AlterColumn = { this: Expression; dtype: Expression | null; collate: Expression | null; using: Expression | null; default: Expression | null; drop: Expression | null; comment: Expression | null; allow_null: Expression | null; visible: Expression | null; rename_to: Expression | null; }; /** * Actions for ALTER COLUMN */ declare type AlterColumnAction = { "SetDataType": { data_type: DataType; /** * USING expression for type conversion (PostgreSQL) */ using: Expression | null; /** * COLLATE clause (TSQL: ALTER COLUMN col TYPE COLLATE collation_name) */ collate?: string | null; }; } | { "SetDefault": Expression; } | "DropDefault" | "SetNotNull" | "DropNotNull" | { "Comment": string; } | "SetVisible" | "SetInvisible"; /** * ALTER INDEX statement */ declare type AlterIndex = { name: Identifier; table: TableRef | null; actions: Array; }; /** * Actions for ALTER INDEX */ declare type AlterIndexAction = { "Rename": Identifier; } | { "SetTablespace": Identifier; } | { "Visible": boolean; }; /** * ALTER SEQUENCE statement */ declare type AlterSequence = { name: TableRef; if_exists: boolean; increment: bigint | null; minvalue: SequenceBound | null; maxvalue: SequenceBound | null; start: bigint | null; restart: bigint | null | null; cache: bigint | null; cycle: boolean | null; owned_by: TableRef | null | null; }; /** * AlterSession */ declare type AlterSession = { expressions: Array; unset: Expression | null; }; /** * AlterSet */ declare type AlterSet = { expressions: Array; option: Expression | null; tablespace: Expression | null; access_method: Expression | null; file_format: Expression | null; copy_options: Expression | null; tag: Expression | null; location: Expression | null; serde: Expression | null; }; /** * AlterSortKey */ declare type AlterSortKey = { this: Expression | null; expressions: Array; compound: Expression | null; }; /** * ALTER TABLE statement */ declare type AlterTable = { name: TableRef; actions: Array; /** * IF EXISTS clause */ if_exists: boolean; /** * MySQL: ALGORITHM=INPLACE|COPY|DEFAULT|INSTANT */ algorithm?: string | null; /** * MySQL: LOCK=NONE|SHARED|DEFAULT|EXCLUSIVE */ lock?: string | null; /** * TSQL: WITH CHECK / WITH NOCHECK modifier before ADD CONSTRAINT */ with_check?: string | null; /** * Hive: PARTITION clause before actions (e.g., ALTER TABLE x PARTITION(y=z) ADD COLUMN ...) */ partition?: Array<[Identifier, Expression]> | null; /** * ClickHouse: ON CLUSTER clause for distributed DDL */ on_cluster?: OnCluster | null; /** * Snowflake: ALTER ICEBERG TABLE */ table_modifier?: string | null; }; /** * Actions for ALTER TABLE */ declare type AlterTableAction = { "AddColumn": { column: ColumnDef; if_not_exists: boolean; position: ColumnPosition | null; }; } | { "DropColumn": { name: Identifier; if_exists: boolean; cascade: boolean; }; } | { "RenameColumn": { old_name: Identifier; new_name: Identifier; if_exists: boolean; }; } | { "AlterColumn": { name: Identifier; action: AlterColumnAction; /** * Whether this was parsed from MODIFY COLUMN syntax (MySQL) */ use_modify_keyword: boolean; }; } | { "RenameTable": TableRef; } | { "AddConstraint": TableConstraint; } | { "DropConstraint": { name: Identifier; if_exists: boolean; }; } | { "DropForeignKey": { name: Identifier; }; } | { "DropPartition": { /** * List of partitions to drop (each partition is a list of key=value pairs) */ partitions: Array>; if_exists: boolean; }; } | { "AddPartition": { /** * The partition expression */ partition: Expression; if_not_exists: boolean; location: Expression | null; }; } | { "Delete": { where_clause: Expression; }; } | { "SwapWith": TableRef; } | { "SetProperty": { properties: Array<[string, Expression]>; }; } | { "UnsetProperty": { properties: Array; }; } | { "ClusterBy": { expressions: Array; }; } | { "SetTag": { expressions: Array<[string, Expression]>; }; } | { "UnsetTag": { names: Array; }; } | { "SetOptions": { expressions: Array; }; } | { "AlterIndex": { name: Identifier; visible: boolean; }; } | { "SetAttribute": { attribute: string; }; } | { "SetStageFileFormat": { options: Expression | null; }; } | { "SetStageCopyOptions": { options: Expression | null; }; } | { "AddColumns": { columns: Array; cascade: boolean; }; } | { "DropColumns": { names: Array; }; } | { "ChangeColumn": { old_name: Identifier; new_name: Identifier; data_type?: DataType | null; comment: string | null; cascade: boolean; }; } | { "AlterSortKey": { /** * AUTO or NONE keyword */ this: string | null; /** * Column list for (col1, col2) syntax */ expressions: Array; /** * Whether COMPOUND keyword was present */ compound: boolean; }; } | { "AlterDistStyle": { /** * Distribution style: ALL, EVEN, AUTO, or KEY */ style: string; /** * DISTKEY column (only when style is KEY) */ distkey: Identifier | null; }; } | { "SetTableProperties": { properties: Array<[Expression, Expression]>; }; } | { "SetLocation": { location: string; }; } | { "SetFileFormat": { format: string; }; } | { "ReplacePartition": { partition: Expression; source: Expression | null; }; } | { "Raw": { sql: string; }; }; /** * ALTER VIEW statement */ declare type AlterView = { name: TableRef; actions: Array; /** * MySQL: ALGORITHM = MERGE|TEMPTABLE|UNDEFINED */ algorithm?: string | null; /** * MySQL: DEFINER = 'user'@'host' */ definer?: string | null; /** * MySQL: SQL SECURITY = DEFINER|INVOKER */ sql_security?: string | null; /** * TSQL: WITH option (SCHEMABINDING, ENCRYPTION, VIEW_METADATA) */ with_option?: string | null; /** * Hive: Column aliases with optional comments: (c1 COMMENT 'text', c2) */ columns?: Array; }; /** * Actions for ALTER VIEW */ declare type AlterViewAction = { "Rename": TableRef; } | { "OwnerTo": Identifier; } | { "SetSchema": Identifier; } | { "SetAuthorization": string; } | { "AlterColumn": { name: Identifier; action: AlterColumnAction; }; } | { "AsSelect": Expression; } | { "SetTblproperties": Array<[string, string]>; } | { "UnsetTblproperties": Array; }; /** * Analyze */ declare type Analyze = { kind: string | null; this: Expression | null; options: Array; mode: Expression | null; partition: Expression | null; expression: Expression | null; properties: Array; /** * Column list for ANALYZE tbl(col1, col2) syntax (PostgreSQL) */ columns?: Array; }; /** * AnalyzeDelete */ declare type AnalyzeDelete = { kind: string | null; }; /** * AnalyzeHistogram */ declare type AnalyzeHistogram = { this: Expression; expressions: Array; expression: Expression | null; update_options: Expression | null; }; /** * AnalyzeListChainedRows */ declare type AnalyzeListChainedRows = { expression: Expression | null; }; /** * Return compact query analysis facts for a SELECT or set operation. */ export declare function analyzeQuery(sql: string, dialect: Dialect | string): QueryAnalysisResult; export declare function analyzeQuery(sql: string, options?: AnalyzeQueryOptions): QueryAnalysisResult; export declare interface AnalyzeQueryOptions { /** Dialect used for parsing and dialect-aware rendering */ dialect?: Dialect | string; /** Optional schema used for qualification and type annotation */ schema?: Schema; } /** * AnalyzeSample */ declare type AnalyzeSample = { kind: string; sample: Expression | null; }; /** * AnalyzeStatistics */ declare type AnalyzeStatistics = { kind: string; option: Expression | null; this: Expression | null; expressions: Array; }; /** * AnalyzeValidate */ declare type AnalyzeValidate = { kind: string; this: Expression | null; expression: Expression | null; }; /** * AnalyzeWith */ declare type AnalyzeWith = { expressions: Array; }; /** Chain multiple conditions with AND. */ export declare function and(...conditions: ExprInput[]): Expr; /** * Expression annotated with trailing comments (for round-trip preservation) */ declare type Annotated = { this: Expression; trailing_comments: Array; }; /** * Parse SQL and annotate the AST with inferred type information. * * Parses the given SQL and runs bottom-up type inference, populating the * `inferred_type` field on value-producing AST nodes (columns, operators, * functions, casts, etc.). Use `ast.getInferredType(expr)` to read the * inferred type from any expression node. * * @param sql - The SQL string to parse and annotate * @param dialect - The dialect to use for parsing (default: Generic) * @param schema - Optional schema for column type resolution * * @example * ```typescript * import { annotateTypes, ast, Dialect } from '@polyglot-sql/sdk'; * * const result = annotateTypes( * "SELECT a + b FROM t", * Dialect.PostgreSQL, * { tables: { t: { a: "INT", b: "DOUBLE" } } } * ); * * if (result.success) { * // Walk the AST and inspect inferred types * ast.walk(result.ast![0], (node) => { * const dt = ast.getInferredType(node); * if (dt) { * console.log(ast.getExprType(node), "=>", dt); * } * }); * } * ``` */ export declare function annotateTypes(sql: string, dialect?: Dialect, schema?: Schema): AnnotateTypesResult; /** * Result of an annotateTypes operation */ export declare interface AnnotateTypesResult { success: boolean; /** The AST with `inferred_type` fields populated on value-producing nodes */ ast?: Expression[]; error?: string; } /** * Anonymous */ declare type Anonymous = { this: Expression; expressions: Array; }; /** * AnonymousAggFunc */ declare type AnonymousAggFunc = { this: Expression; expressions: Array; }; /** * Apply */ declare type Apply = { this: Expression; expression: Expression; }; /** * ApproxPercentileEstimate */ declare type ApproxPercentileEstimate = { this: Expression; percentile: Expression | null; }; /** * APPROX_PERCENTILE function */ declare type ApproxPercentileFunc = { this: Expression; percentile: Expression; accuracy: Expression | null; filter: Expression | null; }; /** * ApproxQuantile */ declare type ApproxQuantile = { this: Expression; quantile: Expression | null; accuracy: Expression | null; weight: Expression | null; error_tolerance: Expression | null; }; /** * ApproxQuantiles */ declare type ApproxQuantiles = { this: Expression; expression: Expression | null; }; /** * ApproxTopK */ declare type ApproxTopK = { this: Expression; expression: Expression | null; counters: Expression | null; }; /** * ApproxTopKAccumulate */ declare type ApproxTopKAccumulate = { this: Expression; expression: Expression | null; }; /** * ApproxTopKCombine */ declare type ApproxTopKCombine = { this: Expression; expression: Expression | null; }; /** * ApproxTopKEstimate */ declare type ApproxTopKEstimate = { this: Expression; expression: Expression | null; }; /** * ApproxTopSum */ declare type ApproxTopSum = { this: Expression; expression: Expression; count: Expression | null; }; /** * ArgMax */ declare type ArgMax = { this: Expression; expression: Expression; count: Expression | null; }; /** * ArgMin */ declare type ArgMin = { this: Expression; expression: Expression; count: Expression | null; }; /** * Union of all arithmetic operator types */ declare type ArithmeticExpression = ExpressionByType<'add'> | ExpressionByType<'sub'> | ExpressionByType<'mul'> | ExpressionByType<'div'> | ExpressionByType<'mod'>; /** * ArrayAll */ declare type ArrayAll = { this: Expression; expression: Expression; }; /** * ArrayAny */ declare type ArrayAny = { this: Expression; expression: Expression; }; /** * ArrayConstructCompact */ declare type ArrayConstructCompact = { expressions: Array; }; /** * ARRAY constructor */ declare type ArrayConstructor_2 = { expressions: Array; bracket_notation: boolean; /** * True if LIST keyword was used instead of ARRAY (DuckDB) */ use_list_keyword: boolean; }; /** * ARRAY_FILTER function (with lambda) */ declare type ArrayFilterFunc = { this: Expression; filter: Expression; }; /** * ARRAY_JOIN / ARRAY_TO_STRING function */ declare type ArrayJoinFunc = { this: Expression; separator: Expression; null_replacement: Expression | null; }; /** * Array slice (array[start:end]) */ declare type ArraySlice = { this: Expression; start: Expression | null; end: Expression | null; }; /** * ARRAY_SORT function */ declare type ArraySortFunc = { this: Expression; comparator: Expression | null; desc: boolean; nulls_first: boolean | null; }; /** * ArraySum */ declare type ArraySum = { this: Expression; expression: Expression | null; }; /** * ARRAY_TRANSFORM / TRANSFORM function (with lambda) */ declare type ArrayTransformFunc = { this: Expression; transform: Expression; }; /** * AssumeColumnConstraint (ClickHouse ASSUME constraint) */ declare type AssumeColumnConstraint = { this: Expression; }; export declare namespace ast { export { ExpressionByKey, ExpressionInner, ExpressionType, getExprData, getExprType, getInferredType, isExpressionValue, makeExpr, Alias, BinaryOp, Case, Cast, Column, DataType, Delete, Expression, From, GroupBy, Having, Identifier, Index, Insert, Join, JoinKind, Limit, Literal, Offset, OrderBy, Ordered, Select, TableRef, UnaryOp, Update, Where, isQuery, isSetOperation, isComparison, isArithmetic, isLogical, isDDL, isSelect, isInsert, isUpdate, isDelete, isUnion, isIntersect, isExcept, isSubquery, isIdentifier, isColumn, isTable, isStar, isLiteral, isBoolean, isNullLiteral, isAnd, isOr, isNot, isEq, isNeq, isLt, isLte, isGt, isGte, isLike, isILike, isAdd, isSub, isMul, isDiv, isMod, isConcat, isIn, isBetween, isIsNull, isExists, isFunction, isAggregateFunction, isWindowFunction, isCount, isSum, isAvg, isMin, isMax, isCoalesce, isNullIf, isCast, isTryCast, isSafeCast, isCase, isFrom, isJoin, isWhere, isGroupBy, isHaving, isOrderBy, isLimit, isOffset, isWith, isCte, isAlias, isParen, isOrdered, isCreateTable, isDropTable, isAlterTable, isCreateIndex, isDropIndex, isCreateView, isDropView, ExpressionByType, QueryExpression, SetOperationExpression, DDLExpression, BinaryOperatorExpression, UnaryOperatorExpression, ComparisonExpression, ArithmeticExpression, LogicalExpression, LiteralExpression, ReferenceExpression, FunctionExpression, AggregateExpression, WindowExpression, ClauseExpression, PredicateExpression, ExpressionInput, ColumnInput, TableInput, OrderInput, addSelectColumns, addWhere, clone, qualifyColumns, qualifyTables, remove, removeLimitOffset, removeSelectColumns, removeWhere, renameColumns, renameTables, replaceByType, replaceNodes, setDistinct, setLimit, setOffset, setOrderBy, transform, NodePath, NodePredicate, TransformCallback, TransformConfig, VisitorCallback, VisitorConfig, VisitorContext, QualifyTablesOptions, RenameTablesOptions, countNodes, every, findAll, findAncestor, findByType, findFirst, getAggregateFunctions, getChildren, getColumnNames, getColumns, getDepth, getFunctions, getIdentifiers, getLiterals, getNodeDepth, getParent, getSubqueries, getTableNames, getTables, getWindowFunctions, hasAggregates, hasSubqueries, hasWindowFunctions, nodeCount, some, walk } } /** * AtIndex */ declare type AtIndex = { this: Expression; expression: Expression; }; /** * Attach */ declare type Attach = { this: Expression; exists: boolean; expressions: Array; }; /** * AttachOption */ declare type AttachOption = { this: Expression; expression: Expression | null; }; /** * AT TIME ZONE expression for timezone conversion */ declare type AtTimeZone = { /** * The expression to convert */ this: Expression; /** * The target timezone */ zone: Expression; }; /** * AutoIncrementColumnConstraint - MySQL/TSQL auto-increment marker * TSQL: outputs "IDENTITY" */ declare type AutoIncrementColumnConstraint = null; /** * AutoIncrementProperty */ declare type AutoIncrementProperty = { this: Expression; }; /** * AutoRefreshProperty */ declare type AutoRefreshProperty = { this: Expression; }; export declare function avg(expr: ExprInput): Expr; /** * BackupProperty */ declare type BackupProperty = { this: Expression; }; /** * Base64DecodeBinary */ declare type Base64DecodeBinary = { this: Expression; alphabet: Expression | null; }; /** * Base64DecodeString */ declare type Base64DecodeString = { this: Expression; alphabet: Expression | null; }; /** * Base64Encode */ declare type Base64Encode = { this: Expression; max_line_length: Expression | null; alphabet: Expression | null; }; /** * Represent a BETWEEN predicate (`x BETWEEN low AND high`). */ declare type Between = { /** * The expression being tested. */ this: Expression; /** * The lower bound. */ low: Expression; /** * The upper bound. */ high: Expression; /** * Whether this is NOT BETWEEN. */ not: boolean; /** * SYMMETRIC/ASYMMETRIC qualifier: None = regular, Some(true) = SYMMETRIC, Some(false) = ASYMMETRIC */ symmetric: boolean | null; }; /** * Generic binary function (takes two arguments) */ declare type BinaryFunc = { this: Expression; expression: Expression; /** * Original function name for round-trip preservation (e.g., NVL vs IFNULL) */ original_name?: string | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Represent a binary operation (two operands separated by an operator). * * This is the shared payload struct for all binary operator variants in the * [`Expression`] enum: arithmetic (`Add`, `Sub`, `Mul`, `Div`, `Mod`), * comparison (`Eq`, `Neq`, `Lt`, `Gt`, etc.), logical (`And`, `Or`), * bitwise, and dialect-specific operators. Comment fields enable round-trip * preservation of inline comments around operators. */ declare type BinaryOp = { left: Expression; right: Expression; /** * Comments after the left operand (before the operator) */ left_comments: Array; /** * Comments after the operator (before the right operand) */ operator_comments: Array; /** * Comments after the right operand */ trailing_comments: Array; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Union of all binary operator expression types */ declare type BinaryOperatorExpression = ExpressionByType<'and'> | ExpressionByType<'or'> | ExpressionByType<'add'> | ExpressionByType<'sub'> | ExpressionByType<'mul'> | ExpressionByType<'div'> | ExpressionByType<'mod'> | ExpressionByType<'eq'> | ExpressionByType<'neq'> | ExpressionByType<'lt'> | ExpressionByType<'lte'> | ExpressionByType<'gt'> | ExpressionByType<'gte'> | ExpressionByType<'like'> | ExpressionByType<'i_like'> | ExpressionByType<'concat'> | ExpressionByType<'bitwise_and'> | ExpressionByType<'bitwise_or'> | ExpressionByType<'bitwise_xor'> | ExpressionByType<'bitwise_left_shift'> | ExpressionByType<'bitwise_right_shift'>; /** * BlockCompressionProperty */ declare type BlockCompressionProperty = { autotemp: Expression | null; always: Expression | null; default: Expression | null; manual: Expression | null; never: Expression | null; }; /** * Booland */ declare type Booland = { this: Expression; expression: Expression; }; /** Create a SQL boolean literal. */ export declare function boolean(value: boolean): Expr; /** * Boolean literal */ declare type BooleanLiteral = { value: boolean; }; /** * Boolor */ declare type Boolor = { this: Expression; expression: Expression; }; /** * BuildProperty */ declare type BuildProperty = { this: Expression; }; /** * ByteString */ declare type ByteString = { this: Expression; is_bytes: Expression | null; }; /** * CACHE TABLE statement (Spark) */ declare type Cache_2 = { /** * The table to cache */ table: Identifier; /** * LAZY keyword - defer caching until first use */ lazy: boolean; /** * Optional OPTIONS clause (key-value pairs) */ options: Array<[Expression, Expression]>; /** * Optional AS clause with query */ query: Expression | null; }; /** * Represent a CASE expression (both simple and searched forms). * * When `operand` is `Some`, this is a simple CASE (`CASE x WHEN 1 THEN ...`). * When `operand` is `None`, this is a searched CASE (`CASE WHEN x > 0 THEN ...`). * Each entry in `whens` is a `(condition, result)` pair. */ declare type Case = { /** * The operand for simple CASE, or `None` for searched CASE. */ operand: Expression | null; /** * Pairs of (WHEN condition, THEN result). */ whens: Array<[Expression, Expression]>; /** * Optional ELSE result. */ else_: Expression | null; /** * Comments from the CASE keyword (emitted after END) */ comments?: Array; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Fluent builder for CASE expressions. * * @example * ```typescript * const expr = caseWhen() * .when(col('x').gt(lit(0)), lit('positive')) * .else_(lit('negative')) * .build(); * ``` */ export declare class CaseBuilder { /* Excluded from this release type: _w */ /* Excluded from this release type: __constructor */ /** Add a WHEN condition THEN result branch. */ when(condition: ExprInput, result: ExprInput): this; /** Set the ELSE result. */ else_(result: ExprInput): this; /** Build the CASE expression as an Expr. */ build(): Expr; /** Generate SQL string. Defaults to generic dialect. */ toSql(dialect?: string): string; } /** Create a simple CASE builder (CASE operand WHEN value THEN ...). */ export declare function caseOf(operand: ExprInput): CaseBuilder; /** * CaseSpecificColumnConstraint */ declare type CaseSpecificColumnConstraint = { not_: Expression | null; }; /** Create a searched CASE builder (CASE WHEN ... THEN ...). */ export declare function caseWhen(): CaseBuilder; /** * Represent a type cast expression. * * Covers both the standard `CAST(expr AS type)` syntax and the PostgreSQL * shorthand `expr::type`. Also used as the payload for `TryCast` and * `SafeCast` variants. Supports optional FORMAT (BigQuery) and DEFAULT ON * CONVERSION ERROR (Oracle) clauses. */ declare type Cast = { /** * The expression being cast. */ this: Expression; /** * The target data type. */ to: DataType; trailing_comments: Array; /** * Whether PostgreSQL `::` syntax was used (true) vs CAST() function (false) */ double_colon_syntax: boolean; /** * FORMAT clause for BigQuery: CAST(x AS STRING FORMAT 'format_string') */ format?: Expression | null; /** * DEFAULT value ON CONVERSION ERROR (Oracle): CAST(x AS type DEFAULT val ON CONVERSION ERROR) */ default?: Expression | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** Create a CAST(expr AS type) expression. */ export declare function cast(expr: ExprInput, to: string): Expr; /** * CastToStrType */ declare type CastToStrType = { this: Expression; to: Expression | null; }; export declare function ceil(expr: ExprInput): Expr; /** * CEIL function with optional decimals and time unit (Druid: CEIL(time TO unit)) */ declare type CeilFunc = { this: Expression; decimals?: Expression | null; /** * Time unit for Druid-style CEIL(time TO unit) syntax */ to?: Expression | null; }; /** * Changes */ declare type Changes = { information: Expression | null; at_before: Expression | null; end: Expression | null; }; /** Filter to only change edits (exclude keeps) */ export declare function changesOnly(edits: DiffEdit[]): DiffEdit[]; /** * CharacterSetColumnConstraint */ declare type CharacterSetColumnConstraint = { this: Expression; }; /** * CharacterSetProperty */ declare type CharacterSetProperty = { this: Expression; default: Expression | null; }; /** * CHAR/CHR function with multiple args and optional USING charset * e.g., CHAR(77, 77.3, '77.3' USING utf8mb4) * e.g., CHR(187 USING NCHAR_CS) -- Oracle */ declare type CharFunc = { args: Array; charset?: string | null; /** * Original function name (CHAR or CHR), defaults to CHAR */ name?: string | null; }; /** * CheckColumnConstraint */ declare type CheckColumnConstraint = { this: Expression; enforced: Expression | null; }; /** * CheckJson */ declare type CheckJson = { this: Expression; }; /** * ChecksumProperty */ declare type ChecksumProperty = { on: Expression | null; default: Expression | null; }; /** * CheckXml */ declare type CheckXml = { this: Expression; disable_auto_convert: Expression | null; }; /** * Union of all clause expression types */ declare type ClauseExpression = ExpressionByType<'from'> | ExpressionByType<'join'> | ExpressionByType<'where'> | ExpressionByType<'group_by'> | ExpressionByType<'having'> | ExpressionByType<'order_by'> | ExpressionByType<'limit'> | ExpressionByType<'offset'> | ExpressionByType<'with'> | ExpressionByType<'cte'>; /** * Clone */ declare type Clone = { this: Expression; shallow: Expression | null; copy: Expression | null; }; /** * Create a deep clone of an AST node */ declare function clone(node: Expression): Expression; /** * CLUSTER BY clause (Hive/Spark) * Combines DISTRIBUTE BY and SORT BY on the same columns */ declare type ClusterBy = { expressions: Array; }; /** * BigQuery CLUSTER BY property in CREATE TABLE statements. */ declare type ClusterByColumnsProperty = { columns: Array; }; /** * ClusteredByProperty */ declare type ClusteredByProperty = { expressions: Array; sorted_by: Expression | null; buckets: Expression | null; }; export declare function coalesce(...exprs: ExprInput[]): Expr; /** Create a column reference. Supports dotted names like `'users.id'`. */ export declare function col(name: string): Expr; /** * CollateProperty */ declare type CollateProperty = { this: Expression; default: Expression | null; }; declare type CollationExpr = { this: Expression; collation: string; /** * True if the collation was single-quoted in the original SQL (string literal) */ quoted: boolean; /** * True if the collation was double-quoted in the original SQL (identifier) */ double_quoted: boolean; }; /** * Represent a column reference, optionally qualified by a table name. * * Renders as `name` when unqualified, or `table.name` when qualified. * Use [`Expression::column()`] or [`Expression::qualified_column()`] for * convenient construction. */ declare type Column = { /** * The column name. */ name: Identifier; /** * Optional table qualifier (e.g. `t` in `t.col`). */ table: Identifier | null; /** * Oracle-style join marker (+) for outer joins */ join_mark: boolean; /** * Trailing comments that appeared after this column reference */ trailing_comments: Array; /** * Source position span */ span?: Span | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Column-level constraint */ declare type ColumnConstraint = "NotNull" | "Null" | "Unique" | "PrimaryKey" | { "Default": Expression; } | { "Check": Expression; } | { "References": ForeignKeyRef; } | { "GeneratedAsIdentity": GeneratedAsIdentity; } | { "Collate": Identifier; } | { "Comment": string; } | { "Tags": Tags; } | { "ComputedColumn": ComputedColumn; } | { "GeneratedAsRow": GeneratedAsRow; } | { "Path": Expression; }; /** * Column definition in CREATE TABLE */ declare type ColumnDef = { name: Identifier; data_type: DataType; nullable: boolean | null; default: Expression | null; primary_key: boolean; /** * Sort order for PRIMARY KEY (ASC/DESC) */ primary_key_order: SortOrder | null; unique: boolean; /** * PostgreSQL 15+: UNIQUE NULLS NOT DISTINCT */ unique_nulls_not_distinct: boolean; auto_increment: boolean; comment: string | null; constraints: Array; /** * Track original order of constraints for accurate regeneration */ constraint_order: Array; /** * Teradata: FORMAT 'pattern' */ format: string | null; /** * Teradata: TITLE 'title' */ title: string | null; /** * Teradata: INLINE LENGTH n */ inline_length: bigint | null; /** * Teradata: COMPRESS or COMPRESS (values) or COMPRESS 'value' */ compress: Array | null; /** * Teradata: CHARACTER SET name */ character_set: string | null; /** * Teradata: UPPERCASE */ uppercase: boolean; /** * Teradata: CASESPECIFIC / NOT CASESPECIFIC (None = not specified, Some(true) = CASESPECIFIC, Some(false) = NOT CASESPECIFIC) */ casespecific: boolean | null; /** * Snowflake: AUTOINCREMENT START value */ auto_increment_start: Expression | null; /** * Snowflake: AUTOINCREMENT INCREMENT value */ auto_increment_increment: Expression | null; /** * Snowflake: AUTOINCREMENT ORDER/NOORDER (true = ORDER, false = NOORDER, None = not specified) */ auto_increment_order: boolean | null; /** * MySQL: UNSIGNED modifier */ unsigned: boolean; /** * MySQL: ZEROFILL modifier */ zerofill: boolean; /** * MySQL: ON UPDATE expression (e.g., ON UPDATE CURRENT_TIMESTAMP) */ on_update?: Expression | null; /** * MySQL: column VISIBLE/INVISIBLE modifier. */ visible?: boolean | null; /** * Named constraint for UNIQUE (e.g., CONSTRAINT must_be_different UNIQUE) */ unique_constraint_name?: string | null; /** * Named constraint for NOT NULL (e.g., CONSTRAINT present NOT NULL) */ not_null_constraint_name?: string | null; /** * Named constraint for PRIMARY KEY (e.g., CONSTRAINT pk_name PRIMARY KEY) */ primary_key_constraint_name?: string | null; /** * Named constraint for CHECK (e.g., CONSTRAINT chk_name CHECK(...)) */ check_constraint_name?: string | null; /** * BigQuery: OPTIONS (key=value, ...) on column */ options?: Array; /** * SQLite: Column definition without explicit type */ no_type: boolean; /** * Redshift: ENCODE encoding_type (e.g., ZSTD, DELTA, LZO, etc.) */ encoding?: string | null; /** * ClickHouse: CODEC(LZ4HC(9), ZSTD, DELTA) */ codec?: string | null; /** * ClickHouse: EPHEMERAL [expr] modifier */ ephemeral?: Expression | null | null; /** * ClickHouse: MATERIALIZED expr modifier */ materialized_expr?: Expression | null; /** * ClickHouse: ALIAS expr modifier */ alias_expr?: Expression | null; /** * ClickHouse: TTL expr modifier on columns */ ttl_expr?: Expression | null; /** * TSQL: NOT FOR REPLICATION */ not_for_replication: boolean; }; /** * Input type for column references */ declare type ColumnInput = string | ExpressionByType<'column'>; /** * Column position for ADD COLUMN (MySQL/MariaDB) */ declare type ColumnPosition = "First" | { "After": Identifier; }; /** * ColumnPrefix */ declare type ColumnPrefix = { this: Expression; expression: Expression; }; export declare interface ColumnReferenceFact { sourceName?: string; sourceAlias?: string; sourceKind: QueryAnalysisSourceKind; table?: string; column: string; unqualified: boolean; confidence: ReferenceConfidence; } /** * Columns */ declare type Columns = { this: Expression; unpack: Expression | null; }; /** * Schema Types for Schema-Aware Validation * * These types define the structure for database schema definitions * used in schema-aware SQL validation. */ /** * Column definition in a table schema. */ export declare interface ColumnSchema { /** Column name */ name: string; /** * Column data type (e.g., "integer", "varchar", "timestamp"). * Type names are case-insensitive. */ type: string; /** Whether the column allows NULL values */ nullable?: boolean; /** Whether this column is a primary key */ primaryKey?: boolean; /** Whether this column has a uniqueness constraint */ unique?: boolean; /** * Foreign key reference to another table. * Used for validating join conditions. */ references?: { table: string; column: string; schema?: string; }; } /** * CombinedAggFunc */ declare type CombinedAggFunc = { this: Expression; expressions: Array; }; /** * CombinedParameterizedAgg */ declare type CombinedParameterizedAgg = { this: Expression; expressions: Array; params: Array; }; /** * SQL Command (COMMIT, ROLLBACK, BEGIN, etc.) */ declare type Command = { /** * The command text (e.g., "ROLLBACK", "COMMIT", "BEGIN") */ this: string; }; /** * COMMENT ON statement */ declare type Comment_2 = { /** * The object being commented on */ this: Expression; /** * The object kind (COLUMN, TABLE, DATABASE, etc.) */ kind: string; /** * The comment text expression */ expression: Expression; /** * IF EXISTS clause */ exists: boolean; /** * MATERIALIZED keyword */ materialized: boolean; }; /** * CommentColumnConstraint - Column comment marker */ declare type CommentColumnConstraint = null; /** * Commit */ declare type Commit = { chain: Expression | null; this: Expression | null; durability: Expression | null; }; /** * Union of all comparison operator types */ declare type ComparisonExpression = ExpressionByType<'eq'> | ExpressionByType<'neq'> | ExpressionByType<'lt'> | ExpressionByType<'lte'> | ExpressionByType<'gt'> | ExpressionByType<'gte'> | ExpressionByType<'like'> | ExpressionByType<'i_like'>; /** * Comprehension */ declare type Comprehension = { this: Expression; expression: Expression; position: Expression | null; iterator: Expression | null; condition: Expression | null; }; /** * Compress */ declare type Compress = { this: Expression; method: string | null; }; /** * CompressColumnConstraint */ declare type CompressColumnConstraint = { this: Expression | null; }; /** * Computed/generated column constraint */ declare type ComputedColumn = { /** * The expression that computes the column value */ expression: Expression; /** * PERSISTED (TSQL) or STORED (MySQL/PostgreSQL) = true; VIRTUAL = false; None = not specified */ persisted: boolean; /** * NOT NULL (TSQL computed columns) */ not_null: boolean; /** * The persistence keyword used: "STORED", "VIRTUAL", or "PERSISTED" * When None, defaults to dialect-appropriate output */ persistence_kind: string | null; /** * Optional data type for SingleStore: AS (expr) PERSISTED TYPE NOT NULL */ data_type?: DataType | null; }; /** * ComputedColumnConstraint */ declare type ComputedColumnConstraint = { this: Expression; persisted: Expression | null; not_null: Expression | null; data_type: Expression | null; }; /** * CONCAT_WS function */ declare type ConcatWs = { separator: Expression; expressions: Array; }; export declare function concatWs(separator: ExprInput, ...exprs: ExprInput[]): Expr; /** Alias for `sqlExpr()` — parse a SQL condition string. */ export declare function condition(sql: string): Expr; /** * ConditionalInsert */ declare type ConditionalInsert = { this: Expression; expression: Expression | null; else_: Expression | null; }; /** * Oracle CONNECT BY clause for hierarchical queries */ declare type Connect = { /** * START WITH condition (optional, can come before or after CONNECT BY) */ start: Expression | null; /** * CONNECT BY condition (required, contains PRIOR references) */ connect: Expression; /** * NOCYCLE keyword to prevent infinite loops */ nocycle: boolean; }; /** * Oracle CONNECT_BY_ROOT function - returns root row's column value */ declare type ConnectByRoot = { this: Expression; }; /** * Constraint */ declare type Constraint = { this: Expression; expressions: Array; }; /** * Constraint modifiers (shared between table-level constraints) */ declare type ConstraintModifiers = { /** * ENFORCED / NOT ENFORCED */ enforced: boolean | null; /** * DEFERRABLE / NOT DEFERRABLE */ deferrable: boolean | null; /** * INITIALLY DEFERRED / INITIALLY IMMEDIATE */ initially_deferred: boolean | null; /** * NORELY (Oracle) */ norely: boolean; /** * RELY (Oracle) */ rely: boolean; /** * USING index type (MySQL): BTREE or HASH */ using: string | null; /** * True if USING appeared before columns (MySQL: INDEX USING BTREE (col) vs INDEX (col) USING BTREE) */ using_before_columns: boolean; /** * MySQL index COMMENT 'text' */ comment?: string | null; /** * MySQL index VISIBLE/INVISIBLE */ visible?: boolean | null; /** * MySQL ENGINE_ATTRIBUTE = 'value' */ engine_attribute?: string | null; /** * MySQL WITH PARSER name */ with_parser?: string | null; /** * PostgreSQL NOT VALID (constraint is not validated against existing data) */ not_valid: boolean; /** * TSQL CLUSTERED/NONCLUSTERED modifier */ clustered?: string | null; /** * SQLite ON CONFLICT clause: ROLLBACK, ABORT, FAIL, IGNORE, or REPLACE */ on_conflict?: string | null; /** * TSQL WITH options (e.g., PAD_INDEX=ON, STATISTICS_NORECOMPUTE=OFF) */ with_options?: Array<[string, string]>; /** * TSQL ON filegroup (e.g., ON [INDEX], ON [PRIMARY]) */ on_filegroup?: Identifier | null; }; /** * Type of column constraint for tracking order */ declare type ConstraintType = "NotNull" | "Null" | "PrimaryKey" | "Unique" | "Default" | "AutoIncrement" | "Collate" | "Comment" | "References" | "Check" | "GeneratedAsIdentity" | "Tags" | "ComputedColumn" | "GeneratedAsRow" | "OnUpdate" | "Path" | "Encode"; /** * CONVERT function (SQL Server style) */ declare type ConvertFunc = { this: Expression; to: DataType; style: Expression | null; }; /** * ConvertTimezone */ declare type ConvertTimezone = { source_tz: Expression | null; target_tz: Expression | null; timestamp: Expression | null; options: Array; }; /** * ConvertToCharset */ declare type ConvertToCharset = { this: Expression; dest: Expression | null; source: Expression | null; }; /** * COPY parameter (e.g., FILE_FORMAT = CSV or FORMAT PARQUET) */ declare type CopyParameter = { name: string; value: Expression | null; values: Array; /** * Whether the parameter used = sign (TSQL: KEY = VALUE vs DuckDB: KEY VALUE) */ eq: boolean; }; /** * COPY statement (Snowflake, PostgreSQL, DuckDB, TSQL) */ declare type CopyStmt = { /** * Target table or query */ this: Expression; /** * True for FROM (loading into table), false for TO (exporting) */ kind: boolean; /** * Source/destination file(s) or stage */ files: Array; /** * Copy parameters */ params: Array; /** * Credentials for external access */ credentials: Credentials | null; /** * Whether the INTO keyword was used (COPY INTO vs COPY) */ is_into: boolean; /** * Whether parameters are wrapped in WITH (...) syntax */ with_wrapped: boolean; }; /** * Corr */ declare type Corr = { this: Expression; expression: Expression; null_on_zero_variance: Expression | null; }; /** * CosineDistance */ declare type CosineDistance = { this: Expression; expression: Expression; }; export declare function count(expr?: ExprInput): Expr; export declare function countDistinct(expr: ExprInput): Expr; /** * COUNT function with optional star */ declare type CountFunc = { this: Expression | null; star: boolean; distinct: boolean; filter: Expression | null; /** * IGNORE NULLS (true) or RESPECT NULLS (false) */ ignore_nulls?: boolean | null; /** * Original function name for case preservation (e.g., "count" or "COUNT") */ original_name?: string | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Count nodes matching a predicate * * @example * ```typescript * const columnCount = countNodes(ast, (node) => getExprType(node) === 'column'); * ``` */ declare function countNodes(node: Expression, predicate: NodePredicate): number; /** * CovarPop */ declare type CovarPop = { this: Expression; expression: Expression; }; /** * CovarSamp */ declare type CovarSamp = { this: Expression; expression: Expression; }; /** * CREATE DATABASE statement */ declare type CreateDatabase = { name: Identifier; if_not_exists: boolean; options: Array; /** * Snowflake CLONE source */ clone_from: Identifier | null; /** * AT/BEFORE clause for time travel (Snowflake) */ at_clause: Expression | null; }; /** * CREATE FUNCTION statement */ declare type CreateFunction = { name: TableRef; parameters: Array; return_type: DataType | null; body: FunctionBody | null; or_replace: boolean; /** * TSQL: CREATE OR ALTER */ or_alter?: boolean; if_not_exists: boolean; temporary: boolean; language: string | null; deterministic: boolean | null; returns_null_on_null_input: boolean | null; security: FunctionSecurity | null; /** * Whether parentheses were present in the original syntax */ has_parens: boolean; /** * SQL data access characteristic (CONTAINS SQL, READS SQL DATA, etc.) */ sql_data_access: SqlDataAccess | null; /** * TSQL: RETURNS @var TABLE (col_defs) - stores the variable name and column definitions as raw string */ returns_table_body?: string | null; /** * True if LANGUAGE clause appears before RETURNS clause */ language_first: boolean; /** * PostgreSQL SET options: SET key = value, SET key FROM CURRENT */ set_options?: Array; /** * True if STRICT was used instead of RETURNS NULL ON NULL INPUT */ strict: boolean; /** * BigQuery: OPTIONS (key=value, ...) */ options?: Array; /** * BigQuery: True if this is a TABLE FUNCTION (CREATE TABLE FUNCTION) */ is_table_function: boolean; /** * Original order of function properties (SET, AS, LANGUAGE, etc.) */ property_order?: Array; /** * Hive: USING JAR|FILE|ARCHIVE '...' */ using_resources?: Array; /** * Databricks: ENVIRONMENT (dependencies = '...', environment_version = '...') */ environment?: Array; /** * HANDLER 'handler_function' clause (Databricks) */ handler?: string | null; /** * True when the HANDLER clause used Snowflake-style `HANDLER = 'fn'` */ handler_uses_eq?: boolean; /** * Snowflake: RUNTIME_VERSION='3.11' */ runtime_version?: string | null; /** * Snowflake: PACKAGES=('pkg1', 'pkg2') */ packages?: Array | null; /** * PARAMETER STYLE clause (e.g., PANDAS for Databricks) */ parameter_style?: string | null; }; /** * CREATE INDEX statement */ declare type CreateIndex = { name: Identifier; table: TableRef; columns: Array; unique: boolean; if_not_exists: boolean; using: string | null; /** * TSQL CLUSTERED/NONCLUSTERED modifier */ clustered: string | null; /** * PostgreSQL CONCURRENTLY modifier */ concurrently: boolean; /** * PostgreSQL WHERE clause for partial indexes */ where_clause: Expression | null; /** * PostgreSQL INCLUDE columns */ include_columns?: Array; /** * TSQL WITH options (e.g., allow_page_locks=on) */ with_options?: Array<[string, string]>; /** * TSQL ON filegroup or partition scheme (e.g., ON PRIMARY, ON X([y])) */ on_filegroup: string | null; }; /** * CREATE PROCEDURE statement */ declare type CreateProcedure = { name: TableRef; parameters: Array; body: FunctionBody | null; or_replace: boolean; /** * TSQL: CREATE OR ALTER */ or_alter?: boolean; if_not_exists: boolean; language: string | null; security: FunctionSecurity | null; /** * Return type (Snowflake: RETURNS OBJECT, RETURNS VARCHAR, etc.) */ return_type: DataType | null; /** * Execution context (EXECUTE AS CALLER, EXECUTE AS OWNER) */ execute_as: string | null; /** * TSQL WITH options (ENCRYPTION, RECOMPILE, SCHEMABINDING, etc.) */ with_options?: Array; /** * Whether the parameter list had parentheses (false for TSQL procedures without parens) */ has_parens?: boolean; /** * Whether the short form PROC was used (instead of PROCEDURE) */ use_proc_keyword?: boolean; }; /** * CREATE SCHEMA statement */ declare type CreateSchema = { /** * Schema name parts, possibly dot-qualified (e.g. [mydb, hr] for "mydb.hr") */ name: Array; if_not_exists: boolean; authorization: Identifier | null; /** * CLONE source parts, possibly dot-qualified */ clone_from: Array | null; /** * AT/BEFORE clause for time travel (Snowflake) */ at_clause: Expression | null; /** * Schema properties like DEFAULT COLLATE */ properties: Array; /** * Leading comments before the statement */ leading_comments?: Array; }; /** * CREATE SEQUENCE statement */ declare type CreateSequence = { name: TableRef; if_not_exists: boolean; temporary: boolean; or_replace: boolean; /** * AS clause (e.g., AS SMALLINT, AS BIGINT) */ as_type?: DataType | null; increment: bigint | null; minvalue: SequenceBound | null; maxvalue: SequenceBound | null; start: bigint | null; cache: bigint | null; cycle: boolean; owned_by: TableRef | null; /** * Whether OWNED BY NONE was specified */ owned_by_none: boolean; /** * Snowflake: ORDER or NOORDER (true = ORDER, false = NOORDER, None = not specified) */ order: boolean | null; /** * Snowflake: COMMENT = 'value' */ comment: string | null; /** * SHARING= (Oracle) */ sharing?: string | null; /** * SCALE modifier: Some("EXTEND"), Some("NOEXTEND"), Some("") for plain SCALE */ scale_modifier?: string | null; /** * SHARD modifier: Some("EXTEND"), Some("NOEXTEND"), Some("") for plain SHARD */ shard_modifier?: string | null; /** * Tracks the order in which properties appeared in the source */ property_order: Array; }; /** * CREATE SYNONYM statement (TSQL) */ declare type CreateSynonym = { /** * The synonym name (can be qualified: schema.synonym_name) */ name: TableRef; /** * The target object the synonym refers to */ target: TableRef; }; /** * CREATE TABLE statement */ declare type CreateTable = { name: TableRef; /** * ClickHouse: ON CLUSTER clause for distributed DDL */ on_cluster?: OnCluster | null; columns: Array; constraints: Array; if_not_exists: boolean; temporary: boolean; or_replace: boolean; /** * Table modifier: DYNAMIC, ICEBERG, EXTERNAL, HYBRID (Snowflake) */ table_modifier?: string | null; as_select: Expression | null; /** * Whether the AS SELECT was wrapped in parentheses */ as_select_parenthesized: boolean; /** * ON COMMIT behavior for temporary tables */ on_commit: OnCommit | null; /** * Clone source table (e.g., CREATE TABLE t CLONE source_table) */ clone_source: TableRef | null; /** * Time travel AT/BEFORE clause for CLONE (e.g., AT(TIMESTAMP => '...')) */ clone_at_clause?: Expression | null; /** * Whether this is a COPY operation (BigQuery) vs CLONE (Snowflake/Databricks) */ is_copy: boolean; /** * Whether this is a SHALLOW CLONE (Databricks/Delta Lake) */ shallow_clone: boolean; /** * Whether this is an explicit DEEP CLONE (Databricks/Delta Lake) */ deep_clone: boolean; /** * Leading comments before the statement */ leading_comments: Array; /** * WITH properties (e.g., WITH (FORMAT='parquet')) */ with_properties: Array<[string, string]>; /** * Teradata: table options after name before columns (comma-separated) */ teradata_post_name_options: Array; /** * Teradata: WITH DATA (true) or WITH NO DATA (false) after AS SELECT */ with_data: boolean | null; /** * Teradata: AND STATISTICS (true) or AND NO STATISTICS (false) */ with_statistics: boolean | null; /** * Teradata: Index specifications (NO PRIMARY INDEX, UNIQUE PRIMARY INDEX, etc.) */ teradata_indexes: Array; /** * WITH clause (CTEs) - for CREATE TABLE ... AS WITH ... SELECT ... */ with_cte: With | null; /** * Table properties like DEFAULT COLLATE (BigQuery) */ properties: Array; /** * PostgreSQL PARTITION OF property (e.g., CREATE TABLE t PARTITION OF parent ...) */ partition_of?: Expression | null; /** * TSQL: WITH(SYSTEM_VERSIONING=ON(...)) after column definitions */ post_table_properties: Array; /** * MySQL table options after column definitions (ENGINE=val, AUTO_INCREMENT=val, etc.) */ mysql_table_options: Array<[string, string]>; /** * PostgreSQL INHERITS clause: INHERITS (parent1, parent2, ...) */ inherits?: Array; /** * TSQL ON filegroup or ON filegroup (partition_column) clause */ on_property?: OnProperty | null; /** * Snowflake: COPY GRANTS clause to copy privileges from replaced table */ copy_grants: boolean; /** * Snowflake: USING TEMPLATE expression for schema inference */ using_template?: Expression | null; /** * StarRocks: ROLLUP (r1(col1, col2), r2(col1)) */ rollup?: RollupProperty | null; /** * ClickHouse: UUID 'xxx' clause after table name */ uuid?: string | null; /** * WITH PARTITION COLUMNS (col_name col_type, ...) — currently used by BigQuery * for hive-partitioned external tables. Not dialect-prefixed since the syntax * could appear in other engines. */ with_partition_columns?: Array; /** * WITH CONNECTION `project.region.connection` — currently used by BigQuery * for external tables that reference a Cloud Resource connection. */ with_connection?: TableRef | null; }; /** * Snowflake CREATE TASK statement */ declare type CreateTask = { or_replace: boolean; if_not_exists: boolean; /** * Task name (possibly qualified: db.schema.task) */ name: string; /** * Raw text of properties between name and AS (WAREHOUSE, SCHEDULE, etc.) */ properties: string; /** * The SQL statement body after AS */ body: Expression; }; /** * CREATE TRIGGER statement */ declare type CreateTrigger = { name: Identifier; table: TableRef; timing: TriggerTiming; events: Array; for_each?: TriggerForEach | null; when: Expression | null; /** * Whether the WHEN clause was parenthesized in the original SQL */ when_paren?: boolean; body: TriggerBody; or_replace: boolean; /** * TSQL: CREATE OR ALTER */ or_alter?: boolean; constraint: boolean; deferrable: boolean | null; initially_deferred: boolean | null; referencing: TriggerReferencing | null; }; /** * CREATE TYPE statement */ declare type CreateType = { name: TableRef; definition: TypeDefinition; if_not_exists: boolean; }; /** * CREATE VIEW statement */ declare type CreateView = { name: TableRef; columns: Array; query: Expression; or_replace: boolean; /** * TSQL: CREATE OR ALTER */ or_alter?: boolean; if_not_exists: boolean; materialized: boolean; temporary: boolean; /** * Snowflake: SECURE VIEW */ secure: boolean; /** * MySQL: ALGORITHM=UNDEFINED/MERGE/TEMPTABLE */ algorithm: string | null; /** * MySQL: DEFINER=user@host */ definer: string | null; /** * MySQL: SQL SECURITY DEFINER/INVOKER; Presto: SECURITY DEFINER/INVOKER */ security: FunctionSecurity | null; /** * True for MySQL-style "SQL SECURITY", false for Presto-style "SECURITY" */ security_sql_style: boolean; /** * True when SQL SECURITY appears after the view name (not before VIEW keyword) */ security_after_name: boolean; /** * Whether the query was parenthesized: AS (SELECT ...) */ query_parenthesized: boolean; /** * Teradata: LOCKING mode (ROW, TABLE, DATABASE) */ locking_mode: string | null; /** * Teradata: LOCKING access type (ACCESS, READ, WRITE) */ locking_access: string | null; /** * Snowflake: COPY GRANTS */ copy_grants: boolean; /** * Snowflake: COMMENT = 'text' */ comment?: string | null; /** * Snowflake: WITH ROW ACCESS POLICY ... clause */ row_access_policy?: string | null; /** * Snowflake: TAG (name='value', ...) */ tags: Array<[string, string]>; /** * BigQuery: OPTIONS (key=value, ...) */ options: Array; /** * Doris: BUILD IMMEDIATE/DEFERRED for materialized views */ build?: string | null; /** * Doris: REFRESH property for materialized views */ refresh?: RefreshTriggerProperty | null; /** * Doris: Schema with typed column definitions for materialized views * This is used instead of `columns` when the view has typed column definitions */ schema?: Schema_2 | null; /** * Doris: KEY (columns) for materialized views */ unique_key?: UniqueKeyProperty | null; /** * Redshift: WITH NO SCHEMA BINDING */ no_schema_binding: boolean; /** * Redshift: AUTO REFRESH YES|NO for materialized views */ auto_refresh?: boolean | null; /** * ClickHouse: POPULATE / EMPTY before AS in materialized views */ clickhouse_population?: string | null; /** * ClickHouse: ON CLUSTER clause */ on_cluster?: OnCluster | null; /** * ClickHouse: TO destination_table */ to_table?: TableRef | null; /** * ClickHouse: Table properties (ENGINE, ORDER BY, SAMPLE, SETTINGS, TTL, etc.) for materialized views */ table_properties?: Array; }; /** * Credentials for external access (S3, Azure, etc.) */ declare type Credentials = { credentials: Array<[string, string]>; encryption: string | null; storage: string | null; }; /** * CredentialsProperty */ declare type CredentialsProperty = { expressions: Array; }; /** * Represent a single Common Table Expression definition. * * A CTE has a name (`alias`), an optional column list, and a body query. * The `materialized` field maps to PostgreSQL's `MATERIALIZED` / * `NOT MATERIALIZED` hints. ClickHouse supports an inverted syntax where * the expression comes before the alias (`alias_first`). */ declare type Cte = { /** * The CTE name. */ alias: Identifier; /** * The CTE body (typically a SELECT, UNION, etc.). */ this: Expression; /** * Optional column alias list: `cte_name(c1, c2) AS (...)`. */ columns: Array; /** * `Some(true)` = MATERIALIZED, `Some(false)` = NOT MATERIALIZED, `None` = unspecified. */ materialized: boolean | null; /** * USING KEY (columns) for DuckDB recursive CTEs */ key_expressions?: Array; /** * ClickHouse supports expression-first WITH items: WITH AS */ alias_first: boolean; /** * Comments associated with this CTE (placed after alias name, before AS) */ comments?: Array; }; export declare interface CteFact { name: string; columns: string[]; bodySql: string; outputColumns: string[]; } /** * Cube */ declare type Cube = { expressions: Array; }; /** * CUME_DIST function (DuckDB allows ORDER BY inside, Oracle allows hypothetical args with WITHIN GROUP) */ declare type CumeDist = { /** * DuckDB: CUME_DIST(ORDER BY col) - order by inside function */ order_by?: Array | null; /** * Oracle hypothetical rank: CUME_DIST(val1, val2, ...) WITHIN GROUP (ORDER BY ...) */ args?: Array; }; /** * CURRENT_DATE (no arguments) */ declare type CurrentDate = null; export declare function currentDate(): Expr; /** * CurrentDatetime */ declare type CurrentDatetime = { this: Expression | null; }; /** * CurrentSchema */ declare type CurrentSchema = { this: Expression | null; }; /** * CurrentSchemas */ declare type CurrentSchemas = { this: Expression | null; }; /** * CURRENT_TIME */ declare type CurrentTime = { precision: number | null; }; export declare function currentTime(): Expr; /** * CURRENT_TIMESTAMP */ declare type CurrentTimestamp = { precision: number | null; /** * If true, generate SYSDATE instead of CURRENT_TIMESTAMP (Oracle-specific) */ sysdate: boolean; }; export declare function currentTimestamp(): Expr; /** * CURRENT_TIMESTAMP_LTZ - Snowflake local timezone timestamp */ declare type CurrentTimestampLTZ = { precision: number | null; }; /** * CurrentUser */ declare type CurrentUser = { this: Expression | null; }; /** * Database option */ declare type DatabaseOption = { "CharacterSet": string; } | { "Collate": string; } | { "Owner": Identifier; } | { "Template": Identifier; } | { "Encoding": string; } | { "Location": string; }; /** * DataBlocksizeProperty */ declare type DataBlocksizeProperty = { size: bigint | null; units: Expression | null; minimum: Expression | null; maximum: Expression | null; default: Expression | null; }; /** * DataDeletionProperty */ declare type DataDeletionProperty = { on: Expression; filter_column: Expression | null; retention_period: Expression | null; }; /** * Enumerate all SQL data types recognized by the parser. * * Covers standard SQL types (BOOLEAN, INT, VARCHAR, TIMESTAMP, etc.) as well * as dialect-specific types (JSONB, VECTOR, OBJECT, etc.). Parametric types * like ARRAY, MAP, and STRUCT are represented with nested [`DataType`] fields. * * This enum is used in CAST expressions, column definitions, function return * types, and anywhere a data type specification appears in SQL. * * Types that do not match any known variant fall through to `Custom { name }`, * preserving the original type name for round-trip fidelity. */ export declare type DataType = { "data_type": "boolean"; } | { "data_type": "tiny_int"; length: number | null; } | { "data_type": "small_int"; length: number | null; } | { "data_type": "int"; length: number | null; integer_spelling?: boolean; } | { "data_type": "big_int"; length: number | null; } | { "data_type": "float"; precision: number | null; scale: number | null; real_spelling?: boolean; } | { "data_type": "double"; precision: number | null; scale: number | null; } | { "data_type": "decimal"; precision: number | null; scale: number | null; } | { "data_type": "char"; length: number | null; } | { "data_type": "var_char"; length: number | null; parenthesized_length?: boolean; } | { "data_type": "string"; length: number | null; } | { "data_type": "text"; } | { "data_type": "text_with_length"; length: number; } | { "data_type": "binary"; length: number | null; } | { "data_type": "var_binary"; length: number | null; } | { "data_type": "blob"; } | { "data_type": "bit"; length: number | null; } | { "data_type": "var_bit"; length: number | null; } | { "data_type": "date"; } | { "data_type": "time"; precision: number | null; timezone: boolean; } | { "data_type": "timestamp"; precision: number | null; timezone: boolean; } | { "data_type": "interval"; unit: string | null; /** * For range intervals like INTERVAL DAY TO HOUR */ to?: string | null; } | { "data_type": "json"; } | { "data_type": "json_b"; } | { "data_type": "uuid"; } | { "data_type": "array"; element_type: DataType; /** * Optional dimension size for PostgreSQL (e.g., [3] in INT[3]) */ dimension?: number | null; } | { "data_type": "list"; element_type: DataType; } | { "data_type": "struct"; fields: Array; nested: boolean; } | { "data_type": "map"; key_type: DataType; value_type: DataType; } | { "data_type": "enum"; values: Array; assignments?: Array; } | { "data_type": "set"; values: Array; } | { "data_type": "union"; fields: Array<[string, DataType]>; } | { "data_type": "vector"; element_type: DataType | null; dimension: number | null; } | { "data_type": "object"; fields: Array<[string, DataType, boolean]>; modifier: string | null; } | { "data_type": "nullable"; inner: DataType; } | { "data_type": "custom"; name: string; } | { "data_type": "geometry"; subtype: string | null; srid: number | null; } | { "data_type": "geography"; subtype: string | null; srid: number | null; } | { "data_type": "character_set"; name: string; } | { "data_type": "unknown"; }; /** * Result of a standalone data type parse operation */ export declare interface DataTypeResult { success: boolean; dataType?: DataType; error?: string; /** 1-based line number where the error occurred */ errorLine?: number; /** 1-based column number where the error occurred */ errorColumn?: number; /** Start byte offset of the error range */ errorStart?: number; /** End byte offset of the error range (exclusive) */ errorEnd?: number; } /** * DATE_ADD / DATE_SUB function */ declare type DateAddFunc = { this: Expression; interval: Expression; unit: IntervalUnit; }; /** * DateBin */ declare type DateBin = { this: Expression; expression: Expression; unit: string | null; zone: Expression | null; origin: Expression | null; }; /** * DATEDIFF function */ declare type DateDiffFunc = { this: Expression; expression: Expression; unit: IntervalUnit | null; }; /** * DateFormatColumnConstraint */ declare type DateFormatColumnConstraint = { this: Expression; }; /** * DATE_FORMAT / FORMAT_DATE function */ declare type DateFormatFunc = { this: Expression; format: Expression; }; /** * DateFromParts */ declare type DateFromParts = { year: Expression | null; month: Expression | null; day: Expression | null; allow_overflow: Expression | null; }; /** * Datetime */ declare type Datetime = { this: Expression; expression: Expression | null; }; /** * DatetimeAdd */ declare type DatetimeAdd = { this: Expression; expression: Expression; unit: string | null; }; /** * DatetimeDiff */ declare type DatetimeDiff = { this: Expression; expression: Expression; unit: string | null; }; declare type DateTimeField = "Year" | "Month" | "Day" | "Hour" | "Minute" | "Second" | "Millisecond" | "Microsecond" | "DayOfWeek" | "DayOfYear" | "Week" | { "WeekWithModifier": string; } | "Quarter" | "Epoch" | "Timezone" | "TimezoneHour" | "TimezoneMinute" | "Date" | "Time" | { "Custom": string; }; /** * DatetimeSub */ declare type DatetimeSub = { this: Expression; expression: Expression; unit: string | null; }; /** * DatetimeTrunc */ declare type DatetimeTrunc = { this: Expression; unit: string; zone: Expression | null; }; /** * DATE_TRUNC function */ declare type DateTruncFunc = { this: Expression; unit: DateTimeField; }; /** * Dayname */ declare type Dayname = { this: Expression; abbreviated: Expression | null; }; /** * Union of all DDL expression types */ declare type DDLExpression = ExpressionByType<'create_table'> | ExpressionByType<'drop_table'> | ExpressionByType<'alter_table'> | ExpressionByType<'create_index'> | ExpressionByType<'drop_index'> | ExpressionByType<'create_view'> | ExpressionByType<'drop_view'> | ExpressionByType<'alter_view'> | ExpressionByType<'alter_index'> | ExpressionByType<'truncate'> | ExpressionByType<'create_schema'> | ExpressionByType<'drop_schema'> | ExpressionByType<'create_database'> | ExpressionByType<'drop_database'> | ExpressionByType<'create_function'> | ExpressionByType<'drop_function'> | ExpressionByType<'create_procedure'> | ExpressionByType<'drop_procedure'> | ExpressionByType<'create_sequence'> | ExpressionByType<'drop_sequence'> | ExpressionByType<'alter_sequence'> | ExpressionByType<'create_trigger'> | ExpressionByType<'drop_trigger'> | ExpressionByType<'create_type'> | ExpressionByType<'drop_type'>; /** * Declare */ declare type Declare = { expressions: Array; replace: boolean; }; /** * DeclareItem */ declare type DeclareItem = { this: Expression; kind: string | null; default: Expression | null; has_as: boolean; /** * BigQuery: additional variable names in multi-variable DECLARE (DECLARE X, Y, Z INT64) */ additional_names?: Array; }; /** * DecodeCase */ declare type DecodeCase = { expressions: Array; }; /** * DECODE function (Oracle style) */ declare type DecodeFunc = { this: Expression; search_results: Array<[Expression, Expression]>; default: Expression | null; }; /** * DecompressBinary */ declare type DecompressBinary = { this: Expression; method: string; }; /** * DecompressString */ declare type DecompressString = { this: Expression; method: string; }; /** * Decrypt */ declare type Decrypt = { this: Expression; passphrase: Expression | null; aad: Expression | null; encryption_method: Expression | null; safe: Expression | null; }; /** * DecryptRaw */ declare type DecryptRaw = { this: Expression; key: Expression | null; iv: Expression | null; aad: Expression | null; encryption_method: Expression | null; aead: Expression | null; safe: Expression | null; }; declare const _default: { init: typeof init; isInitialized: typeof isInitialized; transpile: typeof transpile; parse: typeof parse; parseDataType: typeof parseDataType; tokenize: typeof tokenize; generate: typeof generate; generateDataType: typeof generateDataType; format: typeof format; annotateTypes: typeof annotateTypes; analyzeQuery: typeof analyzeQuery; getDialects: typeof getDialects; getVersion: typeof getVersion; lineage: typeof lineage; lineageWithSchema: typeof lineageWithSchema; getSourceTables: typeof getSourceTables; openLineageColumnLineage: typeof openLineageColumnLineage; openLineageJobEvent: typeof openLineageJobEvent; openLineageRunEvent: typeof openLineageRunEvent; diff: typeof diff; hasChanges: typeof hasChanges; changesOnly: typeof changesOnly; plan: typeof plan; Dialect: typeof Dialect; Polyglot: typeof Polyglot; }; export default _default; /** * DefaultColumnConstraint - DEFAULT value for a column */ declare type DefaultColumnConstraint = { this: Expression; /** * TSQL: DEFAULT value FOR column (table-level default constraint) */ for_column?: Identifier | null; }; /** * DefinerProperty */ declare type DefinerProperty = { this: Expression; }; /** Alias for deleteFrom. */ export declare function del(tableName: string): DeleteBuilder; /** * DELETE statement */ declare type Delete = { table: TableRef; hint: Hint | null; /** * ClickHouse: ON CLUSTER clause for distributed DDL */ on_cluster?: OnCluster | null; /** * Optional alias for the table */ alias: Identifier | null; /** * Whether the alias was declared with explicit AS keyword */ alias_explicit_as: boolean; /** * PostgreSQL/DuckDB USING clause - additional tables to join */ using: Array; where_clause: Where | null; /** * OUTPUT clause (TSQL) */ output: OutputClause | null; /** * Leading comments before the statement */ leading_comments: Array; /** * WITH clause (CTEs) */ with: With | null; /** * LIMIT clause (MySQL) */ limit: Expression | null; /** * ORDER BY clause (MySQL) */ order_by: OrderBy | null; /** * RETURNING clause (PostgreSQL) */ returning: Array; /** * MySQL multi-table DELETE: DELETE t1, t2 FROM ... or DELETE FROM t1, t2 USING ... * These are the target tables to delete from */ tables: Array; /** * True if tables were after FROM keyword (DELETE FROM t1, t2 USING syntax) * False if tables were before FROM keyword (DELETE t1, t2 FROM syntax) */ tables_from_using: boolean; /** * JOINs in MySQL multi-table DELETE: DELETE t1 FROM t1 LEFT JOIN t2 ... */ joins: Array; /** * FORCE INDEX hint (MySQL): DELETE FROM t FORCE INDEX (idx) */ force_index: string | null; /** * BigQuery-style DELETE without FROM keyword: DELETE table WHERE ... */ no_from: boolean; }; /** * Fluent builder for DELETE FROM statements. * * @example * ```typescript * const sql = deleteFrom('users') * .where(col('id').eq(lit(1))) * .toSql(); * ``` */ export declare class DeleteBuilder { /* Excluded from this release type: _w */ constructor(tableName: string); /** Set the WHERE clause. */ where(condition: ExprInput): this; /** Generate SQL string. Defaults to generic dialect. */ toSql(dialect?: string): string; /** Return the Expression AST as a plain JS object. */ build(): any; /** Free the underlying WASM handle. */ free(): void; } /** Create a DeleteBuilder for the given table. */ export declare function deleteFrom(tableName: string): DeleteBuilder; /** * DENSE_RANK function (Oracle allows hypothetical args with WITHIN GROUP) */ declare type DenseRank = { /** * Oracle hypothetical rank: DENSE_RANK(val1, val2, ...) WITHIN GROUP (ORDER BY ...) */ args?: Array; }; export declare function denseRank(): Expr; /** * DESCRIBE statement - shows table structure or query plan */ declare type Describe = { /** * The target to describe (table name or query) */ target: Expression; /** * EXTENDED format */ extended: boolean; /** * FORMATTED format */ formatted: boolean; /** * Object kind (e.g., "SEMANTIC VIEW", "TABLE", etc.) */ kind: string | null; /** * Properties like type=stage */ properties: Array<[string, string]>; /** * Style keyword (e.g., "ANALYZE", "HISTORY") */ style?: string | null; /** * Partition specification for DESCRIBE PARTITION */ partition: Expression | null; /** * Leading comments before the statement */ leading_comments: Array; /** * AS JSON suffix (Databricks) */ as_json: boolean; /** * Parenthesized parameter types for DESCRIBE PROCEDURE/FUNCTION (e.g., INT, VARCHAR) */ params?: Array; }; /** * Detach */ declare type Detach = { this: Expression; exists: boolean; }; /** * Supported SQL dialects */ export declare enum Dialect { Generic = "generic", PostgreSQL = "postgresql", MySQL = "mysql", BigQuery = "bigquery", Snowflake = "snowflake", DuckDB = "duckdb", SQLite = "sqlite", Hive = "hive", Spark = "spark", Trino = "trino", Presto = "presto", Redshift = "redshift", TSQL = "tsql", Oracle = "oracle", ClickHouse = "clickhouse", Databricks = "databricks", Athena = "athena", Teradata = "teradata", Doris = "doris", StarRocks = "starrocks", Materialize = "materialize", RisingWave = "risingwave", SingleStore = "singlestore", CockroachDB = "cockroachdb", TiDB = "tidb", Druid = "druid", Solr = "solr", Tableau = "tableau", Dune = "dune", Fabric = "fabric", Drill = "drill", Dremio = "dremio", Exasol = "exasol", DataFusion = "datafusion" } /** * DictProperty */ declare type DictProperty = { this: Expression; kind: string; settings: Expression | null; }; /** * DictRange */ declare type DictRange = { this: Expression; min: Expression | null; max: Expression | null; }; /** * Diff two SQL statements and return edit operations. * * @param source - Source SQL string * @param target - Target SQL string * @param dialect - Dialect for parsing (default: 'generic') * @param options - Diff configuration options * * @example * ```typescript * const result = diff( * "SELECT col_a FROM t", * "SELECT col_b FROM t", * ); * // result.edits contains update/keep edits * ``` */ export declare function diff(source: string, target: string, dialect?: string, options?: DiffOptions): DiffResult; /** A single edit in the diff result */ export declare interface DiffEdit { type: EditType; /** Present for insert/remove edits */ expression?: Expression; /** Present for move/update/keep edits */ source?: Expression; /** Present for move/update/keep edits */ target?: Expression; } /** Configuration for diff sensitivity */ export declare interface DiffOptions { /** Exclude 'keep' edits from result (default: false) */ deltaOnly?: boolean; /** Dice coefficient threshold for internal nodes (default: 0.6) */ f?: number; /** Leaf similarity threshold (default: 0.6) */ t?: number; } /** Result from diffing two SQL statements */ export declare interface DiffResult { success: boolean; edits?: DiffEdit[]; error?: string; } /** * Directory */ declare type Directory = { this: Expression; local: Expression | null; row_format: Expression | null; }; /** * Directory insert for INSERT OVERWRITE DIRECTORY (Hive/Spark) */ declare type DirectoryInsert = { local: boolean; path: string; row_format: RowFormat | null; /** * STORED AS clause (e.g., TEXTFILE, ORC, PARQUET) */ stored_as: string | null; }; /** * DistKeyProperty */ declare type DistKeyProperty = { this: Expression; }; /** * DISTRIBUTE BY clause (Hive/Spark) * Controls how rows are distributed across reducers */ declare type DistributeBy = { expressions: Array; }; /** * DistributedByProperty */ declare type DistributedByProperty = { expressions: Array; kind: string; buckets: Expression | null; order: Expression | null; }; /** * DistStyleProperty */ declare type DistStyleProperty = { this: Expression; }; /** * Domain constraint */ declare type DomainConstraint = { name: Identifier | null; check: Expression; }; /** * Dot access (struct.field) */ declare type DotAccess = { this: Expression; field: Identifier; }; /** * DotProduct */ declare type DotProduct = { this: Expression; expression: Expression; }; /** * DPipe */ declare type DPipe = { this: Expression; expression: Expression; safe: Expression | null; }; /** * DROP DATABASE statement */ declare type DropDatabase = { name: Identifier; if_exists: boolean; /** * ClickHouse: SYNC modifier */ sync: boolean; }; /** * DROP FUNCTION statement */ declare type DropFunction = { name: TableRef; parameters: Array | null; if_exists: boolean; cascade: boolean; }; /** * DROP INDEX statement */ declare type DropIndex = { name: TableRef; table: TableRef | null; if_exists: boolean; /** * PostgreSQL CONCURRENTLY modifier */ concurrently: boolean; }; /** * DROP NAMESPACE statement (Spark/Databricks - alias for DROP SCHEMA) */ declare type DropNamespace = { name: Identifier; if_exists: boolean; cascade: boolean; }; /** * DropPartition */ declare type DropPartition = { expressions: Array; exists: boolean; }; /** * DROP PROCEDURE statement */ declare type DropProcedure = { name: TableRef; parameters: Array | null; if_exists: boolean; cascade: boolean; }; /** * DROP SCHEMA statement */ declare type DropSchema = { name: Identifier; if_exists: boolean; cascade: boolean; }; /** * DROP SEQUENCE statement */ declare type DropSequence = { name: TableRef; if_exists: boolean; cascade: boolean; }; /** * DROP TABLE statement */ declare type DropTable = { names: Array; if_exists: boolean; cascade: boolean; /** * Oracle: CASCADE CONSTRAINTS */ cascade_constraints: boolean; /** * Oracle: PURGE */ purge: boolean; /** * Comments that appear before the DROP keyword (e.g., leading line comments) */ leading_comments: Array; /** * TSQL: OBJECT_ID arguments for reconstructing IF OBJECT_ID(...) IS NOT NULL pattern * When set, TSQL generator outputs IF NOT OBJECT_ID(...) IS NULL BEGIN DROP TABLE ...; END */ object_id_args?: string | null; /** * ClickHouse: SYNC modifier */ sync: boolean; /** * Snowflake: DROP ICEBERG TABLE */ iceberg: boolean; /** * RESTRICT modifier (opposite of CASCADE) */ restrict: boolean; }; /** * DROP TRIGGER statement */ declare type DropTrigger = { name: Identifier; table: TableRef | null; if_exists: boolean; cascade: boolean; }; /** * DROP TYPE statement */ declare type DropType = { name: TableRef; if_exists: boolean; cascade: boolean; }; /** * DROP VIEW statement */ declare type DropView = { name: TableRef; if_exists: boolean; materialized: boolean; }; /** * DuplicateKeyProperty */ declare type DuplicateKeyProperty = { expressions: Array; }; /** Types of edit operations */ export declare type EditType = 'insert' | 'remove' | 'move' | 'update' | 'keep'; /** * Elt */ declare type Elt = { this: Expression; expressions: Array; }; /** * Encode */ declare type Encode = { this: Expression; charset: Expression | null; }; /** * EncodeProperty */ declare type EncodeProperty = { this: Expression; properties: Array; key: Expression | null; }; /** * Encrypt */ declare type Encrypt = { this: Expression; passphrase: Expression | null; aad: Expression | null; encryption_method: Expression | null; }; /** * EncryptRaw */ declare type EncryptRaw = { this: Expression; key: Expression | null; iv: Expression | null; aad: Expression | null; encryption_method: Expression | null; }; /** * EngineProperty */ declare type EngineProperty = { this: Expression; }; /** * EnviromentProperty */ declare type EnviromentProperty = { expressions: Array; }; /** * EphemeralColumnConstraint */ declare type EphemeralColumnConstraint = { this: Expression | null; }; /** * EqualNull */ declare type EqualNull = { this: Expression; expression: Expression; }; /** * EuclideanDistance */ declare type EuclideanDistance = { this: Expression; expression: Expression; }; /** * Check if all nodes of a type match a predicate * * @example * ```typescript * const allColumnsQualified = every( * ast, * (node) => getExprType(node) !== 'column' || getExprData(node).table !== null * ); * ``` */ declare function every(node: Expression, predicate: NodePredicate): boolean; /** * Represent an EXCEPT (MINUS) set operation between two query expressions. * * Returns rows from the left operand that do not appear in the right operand. * When `all` is true, duplicates are subtracted according to their multiplicity. */ declare type Except = { /** * The left-hand query operand. */ left: Expression; /** * The right-hand query operand (rows to subtract). */ right: Expression; /** * Whether EXCEPT ALL (true) or EXCEPT (false, which deduplicates). */ all: boolean; /** * Whether DISTINCT was explicitly specified */ distinct: boolean; /** * Optional WITH clause */ with: With | null; /** * ORDER BY applied to entire EXCEPT result */ order_by: OrderBy | null; /** * LIMIT applied to entire EXCEPT result */ limit: Expression | null; /** * OFFSET applied to entire EXCEPT result */ offset: Expression | null; /** * DISTRIBUTE BY clause (Hive/Spark) */ distribute_by?: DistributeBy | null; /** * SORT BY clause (Hive/Spark) */ sort_by?: SortBy | null; /** * CLUSTER BY clause (Hive/Spark) */ cluster_by?: ClusterBy | null; /** * DuckDB BY NAME modifier */ by_name: boolean; /** * BigQuery: Set operation side (LEFT, RIGHT, FULL) */ side?: string | null; /** * BigQuery: Set operation kind (INNER) */ kind?: string | null; /** * BigQuery: CORRESPONDING modifier */ corresponding: boolean; /** * BigQuery: STRICT modifier (before CORRESPONDING) */ strict: boolean; /** * BigQuery: BY (columns) after CORRESPONDING */ on_columns?: Array; }; /** Create an EXCEPT of two SELECT queries. */ export declare function except(left: SelectBuilder, right: SelectBuilder): SetOpBuilder; /** * Element in an EXCLUDE constraint: expression WITH operator */ declare type ExcludeElement = { /** * The column expression (may include operator class, ordering, nulls) */ expression: string; /** * The operator (e.g., &&, =) */ operator: string; }; /** * ExecuteAsProperty */ declare type ExecuteAsProperty = { this: Expression; }; /** * Named parameter in EXEC statement: @name=value */ declare type ExecuteParameter = { /** * Parameter name (including @) */ name: string; /** * Parameter value */ value: Expression; /** * Whether this is a positional parameter (no = sign) */ positional?: boolean; /** * TSQL OUTPUT modifier on parameter */ output?: boolean; }; /** * EXEC/EXECUTE statement (TSQL stored procedure call) * Syntax: EXEC [schema.]procedure_name [@param=value, ...] */ declare type ExecuteStatement = { /** * The procedure name (can be qualified: schema.proc_name) */ this: Expression; /** * Named parameters: @param=value pairs */ parameters: Array; /** * Positional prepared statement arguments, used by PostgreSQL EXECUTE name(...). */ arguments?: Array; /** * Whether this statement represents PostgreSQL-style prepared statement execution. */ prepared?: boolean; /** * Trailing clause text (e.g. WITH RESULT SETS ((...))) */ suffix?: string | null; }; /** * Represent an EXISTS predicate (`EXISTS (SELECT ...)` or `NOT EXISTS (...)`). */ declare type Exists = { /** * The subquery expression. */ this: Expression; /** * Whether this is NOT EXISTS. */ not: boolean; }; export declare function exp(expr: ExprInput): Expr; /** * Export */ declare type Export = { this: Expression; connection: Expression | null; options: Array; }; /** * A SQL expression. Wraps a WASM handle and provides operator methods. * * All methods return new Expr instances (original is reusable). * * @example * ```typescript * const cond = col('age').gte(lit(18)).and(col('status').neq(lit('banned'))); * ``` */ export declare class Expr { /* Excluded from this release type: _w */ /* Excluded from this release type: __constructor */ eq(other: ExprInput): Expr; neq(other: ExprInput): Expr; lt(other: ExprInput): Expr; lte(other: ExprInput): Expr; gt(other: ExprInput): Expr; gte(other: ExprInput): Expr; and(other: ExprInput): Expr; or(other: ExprInput): Expr; not(): Expr; xor(other: ExprInput): Expr; add(other: ExprInput): Expr; sub(other: ExprInput): Expr; mul(other: ExprInput): Expr; div(other: ExprInput): Expr; like(pattern: ExprInput): Expr; ilike(pattern: ExprInput): Expr; rlike(pattern: ExprInput): Expr; isNull(): Expr; isNotNull(): Expr; between(low: ExprInput, high: ExprInput): Expr; inList(...values: ExprInput[]): Expr; notIn(...values: ExprInput[]): Expr; alias(name: string): Expr; as(name: string): Expr; cast(to: string): Expr; asc(): Expr; desc(): Expr; /** Generate SQL string. Defaults to generic dialect. */ toSql(dialect?: string): string; /** Return the expression AST as a plain JS object. */ toJSON(): any; /** Free the underlying WASM handle. */ free(): void; } /** * Represent any SQL expression or statement as a single, recursive AST node. * * `Expression` is the root type of the polyglot AST. Every parsed SQL * construct -- from a simple integer literal to a multi-CTE query with * window functions -- is represented as a variant of this enum. * * Variants are organized into logical groups (see the module-level docs). * Most non-trivial variants box their payload so that `size_of::()` * stays small (currently two words: tag + pointer). * * # Constructing Expressions * * Use the convenience constructors on `impl Expression` for common cases: * * ```rust,ignore * use polyglot_sql::expressions::Expression; * * let col = Expression::column("id"); * let lit = Expression::number(42); * let star = Expression::star(); * ``` * * # Generating SQL * * ```rust,ignore * let expr = Expression::column("name"); * assert_eq!(expr.sql(), "name"); * ``` */ declare type Expression = { "literal": Literal; } | { "boolean": BooleanLiteral; } | { "null": Null; } | { "identifier": Identifier; } | { "column": Column; } | { "table": TableRef; } | { "star": Star; } | { "braced_wildcard": Expression; } | { "select": Select; } | { "union": Union; } | { "intersect": Intersect; } | { "except": Except; } | { "subquery": Subquery; } | { "pipe_operator": PipeOperator; } | { "pivot": Pivot; } | { "pivot_alias": PivotAlias; } | { "unpivot": Unpivot; } | { "values": Values; } | { "pre_where": PreWhere; } | { "stream": Stream; } | { "using_data": UsingData; } | { "xml_namespace": XmlNamespace; } | { "insert": Insert; } | { "update": Update; } | { "delete": Delete; } | { "copy": CopyStmt; } | { "put": PutStmt; } | { "stage_reference": StageReference; } | { "try_catch": TryCatch; } | { "alias": Alias; } | { "cast": Cast; } | { "collation": CollationExpr; } | { "case": Case; } | { "and": BinaryOp; } | { "or": BinaryOp; } | { "add": BinaryOp; } | { "sub": BinaryOp; } | { "mul": BinaryOp; } | { "div": BinaryOp; } | { "mod": BinaryOp; } | { "eq": BinaryOp; } | { "neq": BinaryOp; } | { "lt": BinaryOp; } | { "lte": BinaryOp; } | { "gt": BinaryOp; } | { "gte": BinaryOp; } | { "like": LikeOp; } | { "i_like": LikeOp; } | { "match": BinaryOp; } | { "bitwise_and": BinaryOp; } | { "bitwise_or": BinaryOp; } | { "bitwise_xor": BinaryOp; } | { "concat": BinaryOp; } | { "adjacent": BinaryOp; } | { "ts_match": BinaryOp; } | { "property_e_q": BinaryOp; } | { "array_contains_all": BinaryOp; } | { "array_contained_by": BinaryOp; } | { "array_overlaps": BinaryOp; } | { "j_s_o_n_b_contains_all_top_keys": BinaryOp; } | { "j_s_o_n_b_contains_any_top_keys": BinaryOp; } | { "j_s_o_n_b_delete_at_path": BinaryOp; } | { "extends_left": BinaryOp; } | { "extends_right": BinaryOp; } | { "not": UnaryOp; } | { "neg": UnaryOp; } | { "bitwise_not": UnaryOp; } | { "in": In; } | { "between": Between; } | { "is_null": IsNull; } | { "is_true": IsTrueFalse; } | { "is_false": IsTrueFalse; } | { "is_json": IsJson; } | { "is": BinaryOp; } | { "exists": Exists; } | { "member_of": BinaryOp; } | { "function": Function_2; } | { "aggregate_function": AggregateFunction; } | { "window_function": WindowFunction; } | { "from": From; } | { "join": Join; } | { "joined_table": JoinedTable; } | { "where": Where; } | { "group_by": GroupBy; } | { "having": Having; } | { "order_by": OrderBy; } | { "limit": Limit; } | { "offset": Offset; } | { "qualify": Qualify; } | { "with": With; } | { "cte": Cte; } | { "distribute_by": DistributeBy; } | { "cluster_by": ClusterBy; } | { "sort_by": SortBy; } | { "lateral_view": LateralView; } | { "hint": Hint; } | { "pseudocolumn": Pseudocolumn; } | { "connect": Connect; } | { "prior": Prior; } | { "connect_by_root": ConnectByRoot; } | { "match_recognize": MatchRecognize; } | { "ordered": Ordered; } | { "window": WindowSpec; } | { "over": Over; } | { "within_group": WithinGroup; } | { "data_type": DataType; } | { "array": SqlArray; } | { "struct": Struct; } | { "tuple": Tuple; } | { "interval": Interval; } | { "concat_ws": ConcatWs; } | { "substring": SubstringFunc; } | { "upper": UnaryFunc; } | { "lower": UnaryFunc; } | { "length": UnaryFunc; } | { "trim": TrimFunc; } | { "l_trim": UnaryFunc; } | { "r_trim": UnaryFunc; } | { "replace": ReplaceFunc; } | { "reverse": UnaryFunc; } | { "left": LeftRightFunc; } | { "right": LeftRightFunc; } | { "repeat": RepeatFunc; } | { "lpad": PadFunc; } | { "rpad": PadFunc; } | { "split": SplitFunc; } | { "regexp_like": RegexpFunc; } | { "regexp_replace": RegexpReplaceFunc; } | { "regexp_extract": RegexpExtractFunc; } | { "overlay": OverlayFunc; } | { "abs": UnaryFunc; } | { "round": RoundFunc; } | { "floor": FloorFunc; } | { "ceil": CeilFunc; } | { "power": BinaryFunc; } | { "sqrt": UnaryFunc; } | { "cbrt": UnaryFunc; } | { "ln": UnaryFunc; } | { "log": LogFunc; } | { "exp": UnaryFunc; } | { "sign": UnaryFunc; } | { "greatest": VarArgFunc; } | { "least": VarArgFunc; } | { "current_date": CurrentDate; } | { "current_time": CurrentTime; } | { "current_timestamp": CurrentTimestamp; } | { "current_timestamp_l_t_z": CurrentTimestampLTZ; } | { "at_time_zone": AtTimeZone; } | { "date_add": DateAddFunc; } | { "date_sub": DateAddFunc; } | { "date_diff": DateDiffFunc; } | { "date_trunc": DateTruncFunc; } | { "extract": ExtractFunc; } | { "to_date": ToDateFunc; } | { "to_timestamp": ToTimestampFunc; } | { "date": UnaryFunc; } | { "time": UnaryFunc; } | { "date_from_unix_date": UnaryFunc; } | { "unix_date": UnaryFunc; } | { "unix_seconds": UnaryFunc; } | { "unix_millis": UnaryFunc; } | { "unix_micros": UnaryFunc; } | { "unix_to_time_str": BinaryFunc; } | { "time_str_to_date": UnaryFunc; } | { "date_to_di": UnaryFunc; } | { "di_to_date": UnaryFunc; } | { "ts_or_di_to_di": UnaryFunc; } | { "ts_or_ds_to_datetime": UnaryFunc; } | { "ts_or_ds_to_timestamp": UnaryFunc; } | { "year_of_week": UnaryFunc; } | { "year_of_week_iso": UnaryFunc; } | { "coalesce": VarArgFunc; } | { "null_if": BinaryFunc; } | { "if_func": IfFunc; } | { "if_null": BinaryFunc; } | { "nvl": BinaryFunc; } | { "nvl2": Nvl2Func; } | { "try_cast": Cast; } | { "safe_cast": Cast; } | { "count": CountFunc; } | { "sum": AggFunc; } | { "avg": AggFunc; } | { "min": AggFunc; } | { "max": AggFunc; } | { "group_concat": GroupConcatFunc; } | { "string_agg": StringAggFunc; } | { "list_agg": ListAggFunc; } | { "array_agg": AggFunc; } | { "count_if": AggFunc; } | { "sum_if": SumIfFunc; } | { "stddev": AggFunc; } | { "stddev_pop": AggFunc; } | { "stddev_samp": AggFunc; } | { "variance": AggFunc; } | { "var_pop": AggFunc; } | { "var_samp": AggFunc; } | { "median": AggFunc; } | { "mode": AggFunc; } | { "first": AggFunc; } | { "last": AggFunc; } | { "any_value": AggFunc; } | { "approx_distinct": AggFunc; } | { "approx_count_distinct": AggFunc; } | { "approx_percentile": ApproxPercentileFunc; } | { "percentile": PercentileFunc; } | { "logical_and": AggFunc; } | { "logical_or": AggFunc; } | { "skewness": AggFunc; } | { "bitwise_count": UnaryFunc; } | { "array_concat_agg": AggFunc; } | { "array_unique_agg": AggFunc; } | { "bool_xor_agg": AggFunc; } | { "row_number": RowNumber; } | { "rank": Rank; } | { "dense_rank": DenseRank; } | { "n_tile": NTileFunc; } | { "lead": LeadLagFunc; } | { "lag": LeadLagFunc; } | { "first_value": ValueFunc; } | { "last_value": ValueFunc; } | { "nth_value": NthValueFunc; } | { "percent_rank": PercentRank; } | { "cume_dist": CumeDist; } | { "percentile_cont": PercentileFunc; } | { "percentile_disc": PercentileFunc; } | { "contains": BinaryFunc; } | { "starts_with": BinaryFunc; } | { "ends_with": BinaryFunc; } | { "position": PositionFunc; } | { "initcap": UnaryFunc; } | { "ascii": UnaryFunc; } | { "chr": UnaryFunc; } | { "char_func": CharFunc; } | { "soundex": UnaryFunc; } | { "levenshtein": BinaryFunc; } | { "byte_length": UnaryFunc; } | { "hex": UnaryFunc; } | { "lower_hex": UnaryFunc; } | { "unicode": UnaryFunc; } | { "mod_func": BinaryFunc; } | { "random": Random; } | { "rand": Rand; } | { "trunc_func": TruncateFunc; } | { "pi": Pi; } | { "radians": UnaryFunc; } | { "degrees": UnaryFunc; } | { "sin": UnaryFunc; } | { "cos": UnaryFunc; } | { "tan": UnaryFunc; } | { "asin": UnaryFunc; } | { "acos": UnaryFunc; } | { "atan": UnaryFunc; } | { "atan2": BinaryFunc; } | { "is_nan": UnaryFunc; } | { "is_inf": UnaryFunc; } | { "int_div": BinaryFunc; } | { "decode": DecodeFunc; } | { "date_format": DateFormatFunc; } | { "format_date": DateFormatFunc; } | { "year": UnaryFunc; } | { "month": UnaryFunc; } | { "day": UnaryFunc; } | { "hour": UnaryFunc; } | { "minute": UnaryFunc; } | { "second": UnaryFunc; } | { "day_of_week": UnaryFunc; } | { "day_of_week_iso": UnaryFunc; } | { "day_of_month": UnaryFunc; } | { "day_of_year": UnaryFunc; } | { "week_of_year": UnaryFunc; } | { "quarter": UnaryFunc; } | { "add_months": BinaryFunc; } | { "months_between": BinaryFunc; } | { "last_day": LastDayFunc; } | { "next_day": BinaryFunc; } | { "epoch": UnaryFunc; } | { "epoch_ms": UnaryFunc; } | { "from_unixtime": FromUnixtimeFunc; } | { "unix_timestamp": UnixTimestampFunc; } | { "make_date": MakeDateFunc; } | { "make_timestamp": MakeTimestampFunc; } | { "timestamp_trunc": DateTruncFunc; } | { "time_str_to_unix": UnaryFunc; } | { "session_user": SessionUser; } | { "s_h_a": UnaryFunc; } | { "s_h_a1_digest": UnaryFunc; } | { "time_to_unix": UnaryFunc; } | { "array_func": ArrayConstructor_2; } | { "array_length": UnaryFunc; } | { "array_size": UnaryFunc; } | { "cardinality": UnaryFunc; } | { "array_contains": BinaryFunc; } | { "array_position": BinaryFunc; } | { "array_append": BinaryFunc; } | { "array_prepend": BinaryFunc; } | { "array_concat": VarArgFunc; } | { "array_sort": ArraySortFunc; } | { "array_reverse": UnaryFunc; } | { "array_distinct": UnaryFunc; } | { "array_join": ArrayJoinFunc; } | { "array_to_string": ArrayJoinFunc; } | { "unnest": UnnestFunc; } | { "explode": UnaryFunc; } | { "explode_outer": UnaryFunc; } | { "array_filter": ArrayFilterFunc; } | { "array_transform": ArrayTransformFunc; } | { "array_flatten": UnaryFunc; } | { "array_compact": UnaryFunc; } | { "array_intersect": VarArgFunc; } | { "array_union": BinaryFunc; } | { "array_except": BinaryFunc; } | { "array_remove": BinaryFunc; } | { "array_zip": VarArgFunc; } | { "sequence": SequenceFunc; } | { "generate": SequenceFunc; } | { "exploding_generate_series": SequenceFunc; } | { "to_array": UnaryFunc; } | { "star_map": BinaryFunc; } | { "struct_func": StructConstructor; } | { "struct_extract": StructExtractFunc; } | { "named_struct": NamedStructFunc; } | { "map_func": MapConstructor_2; } | { "map_from_entries": UnaryFunc; } | { "map_from_arrays": BinaryFunc; } | { "map_keys": UnaryFunc; } | { "map_values": UnaryFunc; } | { "map_contains_key": BinaryFunc; } | { "map_concat": VarArgFunc; } | { "element_at": BinaryFunc; } | { "transform_keys": TransformFunc; } | { "transform_values": TransformFunc; } | { "function_emits": FunctionEmits; } | { "json_extract": JsonExtractFunc; } | { "json_extract_scalar": JsonExtractFunc; } | { "json_extract_path": JsonPathFunc; } | { "json_array": VarArgFunc; } | { "json_object": JsonObjectFunc; } | { "json_query": JsonExtractFunc; } | { "json_value": JsonExtractFunc; } | { "json_array_length": UnaryFunc; } | { "json_keys": UnaryFunc; } | { "json_type": UnaryFunc; } | { "parse_json": UnaryFunc; } | { "to_json": UnaryFunc; } | { "json_set": JsonModifyFunc; } | { "json_insert": JsonModifyFunc; } | { "json_remove": JsonPathFunc; } | { "json_merge_patch": BinaryFunc; } | { "json_array_agg": JsonArrayAggFunc; } | { "json_object_agg": JsonObjectAggFunc; } | { "convert": ConvertFunc; } | { "typeof": UnaryFunc; } | { "lambda": LambdaExpr; } | { "parameter": Parameter; } | { "placeholder": Placeholder; } | { "named_argument": NamedArgument; } | { "table_argument": TableArgument; } | { "sql_comment": SqlComment; } | { "null_safe_eq": BinaryOp; } | { "null_safe_neq": BinaryOp; } | { "glob": BinaryOp; } | { "similar_to": SimilarToExpr; } | { "any": QuantifiedExpr; } | { "all": QuantifiedExpr; } | { "overlaps": OverlapsExpr; } | { "bitwise_left_shift": BinaryOp; } | { "bitwise_right_shift": BinaryOp; } | { "bitwise_and_agg": AggFunc; } | { "bitwise_or_agg": AggFunc; } | { "bitwise_xor_agg": AggFunc; } | { "subscript": Subscript; } | { "dot": DotAccess; } | { "method_call": MethodCall; } | { "array_slice": ArraySlice; } | { "create_table": CreateTable; } | { "drop_table": DropTable; } | { "undrop": Undrop; } | { "alter_table": AlterTable; } | { "create_index": CreateIndex; } | { "drop_index": DropIndex; } | { "create_view": CreateView; } | { "drop_view": DropView; } | { "alter_view": AlterView; } | { "alter_index": AlterIndex; } | { "truncate": Truncate; } | { "use": Use; } | { "cache": Cache_2; } | { "uncache": Uncache; } | { "load_data": LoadData; } | { "pragma": Pragma; } | { "grant": Grant; } | { "revoke": Revoke; } | { "comment": Comment_2; } | { "set_statement": SetStatement; } | { "create_schema": CreateSchema; } | { "drop_schema": DropSchema; } | { "drop_namespace": DropNamespace; } | { "create_database": CreateDatabase; } | { "drop_database": DropDatabase; } | { "create_function": CreateFunction; } | { "drop_function": DropFunction; } | { "create_procedure": CreateProcedure; } | { "drop_procedure": DropProcedure; } | { "create_sequence": CreateSequence; } | { "create_synonym": CreateSynonym; } | { "drop_sequence": DropSequence; } | { "alter_sequence": AlterSequence; } | { "create_trigger": CreateTrigger; } | { "drop_trigger": DropTrigger; } | { "create_type": CreateType; } | { "drop_type": DropType; } | { "describe": Describe; } | { "show": Show; } | { "command": Command; } | { "kill": Kill; } | { "prepare": PrepareStatement; } | { "execute": ExecuteStatement; } | { "create_task": CreateTask; } | { "raw": Raw; } | { "paren": Paren; } | { "annotated": Annotated; } | { "refresh": Refresh; } | { "locking_statement": LockingStatement; } | { "sequence_properties": SequenceProperties; } | { "truncate_table": TruncateTable; } | { "clone": Clone; } | { "attach": Attach; } | { "detach": Detach; } | { "install": Install; } | { "summarize": Summarize; } | { "declare": Declare; } | { "declare_item": DeclareItem; } | { "set": Set_2; } | { "heredoc": Heredoc; } | { "set_item": SetItem; } | { "query_band": QueryBand; } | { "user_defined_function": UserDefinedFunction; } | { "recursive_with_search": RecursiveWithSearch; } | { "projection_def": ProjectionDef; } | { "table_alias": TableAlias; } | { "byte_string": ByteString; } | { "hex_string_expr": HexStringExpr; } | { "unicode_string": UnicodeString; } | { "column_position": ColumnPosition; } | { "column_def": ColumnDef; } | { "alter_column": AlterColumn; } | { "alter_sort_key": AlterSortKey; } | { "alter_set": AlterSet; } | { "rename_column": RenameColumn; } | { "comprehension": Comprehension; } | { "merge_tree_t_t_l_action": MergeTreeTTLAction; } | { "merge_tree_t_t_l": MergeTreeTTL; } | { "index_constraint_option": IndexConstraintOption; } | { "column_constraint": ColumnConstraint; } | { "period_for_system_time_constraint": PeriodForSystemTimeConstraint; } | { "case_specific_column_constraint": CaseSpecificColumnConstraint; } | { "character_set_column_constraint": CharacterSetColumnConstraint; } | { "check_column_constraint": CheckColumnConstraint; } | { "assume_column_constraint": AssumeColumnConstraint; } | { "compress_column_constraint": CompressColumnConstraint; } | { "date_format_column_constraint": DateFormatColumnConstraint; } | { "ephemeral_column_constraint": EphemeralColumnConstraint; } | { "with_operator": WithOperator; } | { "generated_as_identity_column_constraint": GeneratedAsIdentityColumnConstraint; } | { "auto_increment_column_constraint": AutoIncrementColumnConstraint; } | { "comment_column_constraint": CommentColumnConstraint; } | { "generated_as_row_column_constraint": GeneratedAsRowColumnConstraint; } | { "index_column_constraint": IndexColumnConstraint; } | { "masking_policy_column_constraint": MaskingPolicyColumnConstraint; } | { "not_null_column_constraint": NotNullColumnConstraint; } | { "primary_key_column_constraint": PrimaryKeyColumnConstraint; } | { "unique_column_constraint": UniqueColumnConstraint; } | { "watermark_column_constraint": WatermarkColumnConstraint; } | { "computed_column_constraint": ComputedColumnConstraint; } | { "in_out_column_constraint": InOutColumnConstraint; } | { "default_column_constraint": DefaultColumnConstraint; } | { "path_column_constraint": PathColumnConstraint; } | { "constraint": Constraint; } | { "export": Export; } | { "filter": Filter; } | { "changes": Changes; } | { "copy_parameter": CopyParameter; } | { "credentials": Credentials; } | { "directory": Directory; } | { "foreign_key": ForeignKey; } | { "column_prefix": ColumnPrefix; } | { "primary_key": PrimaryKey; } | { "into_clause": IntoClause; } | { "join_hint": JoinHint; } | { "opclass": Opclass; } | { "index": Index; } | { "index_parameters": IndexParameters; } | { "conditional_insert": ConditionalInsert; } | { "multitable_inserts": MultitableInserts; } | { "on_conflict": OnConflict; } | { "on_condition": OnCondition; } | { "returning": Returning; } | { "introducer": Introducer; } | { "partition_range": PartitionRange; } | { "fetch": Fetch; } | { "group": Group; } | { "cube": Cube; } | { "rollup": Rollup; } | { "grouping_sets": GroupingSets; } | { "limit_options": LimitOptions; } | { "lateral": Lateral; } | { "table_from_rows": TableFromRows; } | { "rows_from": RowsFrom; } | { "match_recognize_measure": MatchRecognizeMeasure; } | { "with_fill": WithFill; } | { "property": Property; } | { "grant_privilege": GrantPrivilege; } | { "grant_principal": GrantPrincipal; } | { "allowed_values_property": AllowedValuesProperty; } | { "algorithm_property": AlgorithmProperty; } | { "auto_increment_property": AutoIncrementProperty; } | { "auto_refresh_property": AutoRefreshProperty; } | { "backup_property": BackupProperty; } | { "build_property": BuildProperty; } | { "block_compression_property": BlockCompressionProperty; } | { "character_set_property": CharacterSetProperty; } | { "checksum_property": ChecksumProperty; } | { "collate_property": CollateProperty; } | { "data_blocksize_property": DataBlocksizeProperty; } | { "data_deletion_property": DataDeletionProperty; } | { "definer_property": DefinerProperty; } | { "dist_key_property": DistKeyProperty; } | { "distributed_by_property": DistributedByProperty; } | { "dist_style_property": DistStyleProperty; } | { "duplicate_key_property": DuplicateKeyProperty; } | { "engine_property": EngineProperty; } | { "to_table_property": ToTableProperty; } | { "execute_as_property": ExecuteAsProperty; } | { "external_property": ExternalProperty; } | { "fallback_property": FallbackProperty; } | { "file_format_property": FileFormatProperty; } | { "credentials_property": CredentialsProperty; } | { "freespace_property": FreespaceProperty; } | { "inherits_property": InheritsProperty; } | { "input_model_property": InputModelProperty; } | { "output_model_property": OutputModelProperty; } | { "isolated_loading_property": IsolatedLoadingProperty; } | { "journal_property": JournalProperty; } | { "language_property": LanguageProperty; } | { "enviroment_property": EnviromentProperty; } | { "clustered_by_property": ClusteredByProperty; } | { "dict_property": DictProperty; } | { "dict_range": DictRange; } | { "on_cluster": OnCluster; } | { "like_property": LikeProperty; } | { "location_property": LocationProperty; } | { "lock_property": LockProperty; } | { "locking_property": LockingProperty; } | { "log_property": LogProperty; } | { "materialized_property": MaterializedProperty; } | { "merge_block_ratio_property": MergeBlockRatioProperty; } | { "on_property": OnProperty; } | { "on_commit_property": OnCommitProperty; } | { "partitioned_by_property": PartitionedByProperty; } | { "partition_by_property": PartitionByProperty; } | { "partitioned_by_bucket": PartitionedByBucket; } | { "cluster_by_columns_property": ClusterByColumnsProperty; } | { "partition_by_truncate": PartitionByTruncate; } | { "partition_by_range_property": PartitionByRangeProperty; } | { "partition_by_range_property_dynamic": PartitionByRangePropertyDynamic; } | { "partition_by_list_property": PartitionByListProperty; } | { "partition_list": PartitionList; } | { "partition": Partition; } | { "refresh_trigger_property": RefreshTriggerProperty; } | { "unique_key_property": UniqueKeyProperty; } | { "rollup_property": RollupProperty; } | { "partition_bound_spec": PartitionBoundSpec; } | { "partitioned_of_property": PartitionedOfProperty; } | { "remote_with_connection_model_property": RemoteWithConnectionModelProperty; } | { "returns_property": ReturnsProperty; } | { "row_format_property": RowFormatProperty; } | { "row_format_delimited_property": RowFormatDelimitedProperty; } | { "row_format_serde_property": RowFormatSerdeProperty; } | { "query_transform": QueryTransform; } | { "sample_property": SampleProperty; } | { "security_property": SecurityProperty; } | { "schema_comment_property": SchemaCommentProperty; } | { "semantic_view": SemanticView; } | { "serde_properties": SerdeProperties; } | { "set_property": SetProperty; } | { "sharing_property": SharingProperty; } | { "set_config_property": SetConfigProperty; } | { "settings_property": SettingsProperty; } | { "sort_key_property": SortKeyProperty; } | { "sql_read_write_property": SqlReadWriteProperty; } | { "sql_security_property": SqlSecurityProperty; } | { "stability_property": StabilityProperty; } | { "storage_handler_property": StorageHandlerProperty; } | { "temporary_property": TemporaryProperty; } | { "tags": Tags; } | { "transform_model_property": TransformModelProperty; } | { "transient_property": TransientProperty; } | { "using_template_property": UsingTemplateProperty; } | { "view_attribute_property": ViewAttributeProperty; } | { "volatile_property": VolatileProperty; } | { "with_data_property": WithDataProperty; } | { "with_journal_table_property": WithJournalTableProperty; } | { "with_schema_binding_property": WithSchemaBindingProperty; } | { "with_system_versioning_property": WithSystemVersioningProperty; } | { "with_procedure_options": WithProcedureOptions; } | { "encode_property": EncodeProperty; } | { "include_property": IncludeProperty; } | { "properties": Properties; } | { "options_property": OptionsProperty; } | { "input_output_format": InputOutputFormat; } | { "reference": Reference; } | { "query_option": QueryOption; } | { "with_table_hint": WithTableHint; } | { "index_table_hint": IndexTableHint; } | { "historical_data": HistoricalData; } | { "get": Get; } | { "set_operation": SetOperation; } | { "var": Var; } | { "variadic": Variadic; } | { "version": Version; } | { "schema": Schema_2; } | { "lock": Lock_2; } | { "table_sample": TableSample; } | { "tag": Tag; } | { "unpivot_columns": UnpivotColumns; } | { "window_spec": WindowSpec; } | { "session_parameter": SessionParameter; } | { "pseudo_type": PseudoType; } | { "object_identifier": ObjectIdentifier; } | { "transaction": Transaction; } | { "commit": Commit; } | { "rollback": Rollback; } | { "alter_session": AlterSession; } | { "analyze": Analyze; } | { "analyze_statistics": AnalyzeStatistics; } | { "analyze_histogram": AnalyzeHistogram; } | { "analyze_sample": AnalyzeSample; } | { "analyze_list_chained_rows": AnalyzeListChainedRows; } | { "analyze_delete": AnalyzeDelete; } | { "analyze_with": AnalyzeWith; } | { "analyze_validate": AnalyzeValidate; } | { "add_partition": AddPartition; } | { "attach_option": AttachOption; } | { "drop_partition": DropPartition; } | { "replace_partition": ReplacePartition; } | { "d_pipe": DPipe; } | { "operator": Operator; } | { "pivot_any": PivotAny; } | { "aliases": Aliases; } | { "at_index": AtIndex; } | { "from_time_zone": FromTimeZone; } | { "format_phrase": FormatPhrase; } | { "for_in": ForIn; } | { "time_unit": TimeUnit; } | { "interval_op": IntervalOp; } | { "interval_span": IntervalSpan; } | { "having_max": HavingMax; } | { "cosine_distance": CosineDistance; } | { "dot_product": DotProduct; } | { "euclidean_distance": EuclideanDistance; } | { "manhattan_distance": ManhattanDistance; } | { "jarowinkler_similarity": JarowinklerSimilarity; } | { "booland": Booland; } | { "boolor": Boolor; } | { "parameterized_agg": ParameterizedAgg; } | { "arg_max": ArgMax; } | { "arg_min": ArgMin; } | { "approx_top_k": ApproxTopK; } | { "approx_top_k_accumulate": ApproxTopKAccumulate; } | { "approx_top_k_combine": ApproxTopKCombine; } | { "approx_top_k_estimate": ApproxTopKEstimate; } | { "approx_top_sum": ApproxTopSum; } | { "approx_quantiles": ApproxQuantiles; } | { "minhash": Minhash; } | { "farm_fingerprint": FarmFingerprint; } | { "float64": Float64; } | { "transform": Transform; } | { "translate": Translate; } | { "grouping": Grouping; } | { "grouping_id": GroupingId; } | { "anonymous": Anonymous; } | { "anonymous_agg_func": AnonymousAggFunc; } | { "combined_agg_func": CombinedAggFunc; } | { "combined_parameterized_agg": CombinedParameterizedAgg; } | { "hash_agg": HashAgg; } | { "hll": Hll; } | { "apply": Apply; } | { "to_boolean": ToBoolean; } | { "list": List; } | { "to_map": ToMap; } | { "pad": Pad; } | { "to_char": ToChar; } | { "to_number": ToNumber; } | { "to_double": ToDouble; } | { "int64": UnaryFunc; } | { "string_func": StringFunc; } | { "to_decfloat": ToDecfloat; } | { "try_to_decfloat": TryToDecfloat; } | { "to_file": ToFile; } | { "columns": Columns; } | { "convert_to_charset": ConvertToCharset; } | { "convert_timezone": ConvertTimezone; } | { "generate_series": GenerateSeries; } | { "a_i_agg": AIAgg; } | { "a_i_classify": AIClassify; } | { "array_all": ArrayAll; } | { "array_any": ArrayAny; } | { "array_construct_compact": ArrayConstructCompact; } | { "st_point": StPoint; } | { "st_distance": StDistance; } | { "string_to_array": StringToArray; } | { "array_sum": ArraySum; } | { "object_agg": ObjectAgg; } | { "cast_to_str_type": CastToStrType; } | { "check_json": CheckJson; } | { "check_xml": CheckXml; } | { "translate_characters": TranslateCharacters; } | { "current_schemas": CurrentSchemas; } | { "current_datetime": CurrentDatetime; } | { "localtime": Localtime; } | { "localtimestamp": Localtimestamp; } | { "systimestamp": Systimestamp; } | { "current_schema": CurrentSchema; } | { "current_user": CurrentUser; } | { "utc_time": UtcTime; } | { "utc_timestamp": UtcTimestamp; } | { "timestamp": TimestampFunc; } | { "date_bin": DateBin; } | { "datetime": Datetime; } | { "datetime_add": DatetimeAdd; } | { "datetime_sub": DatetimeSub; } | { "datetime_diff": DatetimeDiff; } | { "datetime_trunc": DatetimeTrunc; } | { "dayname": Dayname; } | { "make_interval": MakeInterval; } | { "previous_day": PreviousDay; } | { "elt": Elt; } | { "timestamp_add": TimestampAdd; } | { "timestamp_sub": TimestampSub; } | { "timestamp_diff": TimestampDiff; } | { "time_slice": TimeSlice; } | { "time_add": TimeAdd; } | { "time_sub": TimeSub; } | { "time_diff": TimeDiff; } | { "time_trunc": TimeTrunc; } | { "date_from_parts": DateFromParts; } | { "time_from_parts": TimeFromParts; } | { "decode_case": DecodeCase; } | { "decrypt": Decrypt; } | { "decrypt_raw": DecryptRaw; } | { "encode": Encode; } | { "encrypt": Encrypt; } | { "encrypt_raw": EncryptRaw; } | { "equal_null": EqualNull; } | { "to_binary": ToBinary; } | { "base64_decode_binary": Base64DecodeBinary; } | { "base64_decode_string": Base64DecodeString; } | { "base64_encode": Base64Encode; } | { "try_base64_decode_binary": TryBase64DecodeBinary; } | { "try_base64_decode_string": TryBase64DecodeString; } | { "gap_fill": GapFill; } | { "generate_date_array": GenerateDateArray; } | { "generate_timestamp_array": GenerateTimestampArray; } | { "get_extract": GetExtract; } | { "getbit": Getbit; } | { "overflow_truncate_behavior": OverflowTruncateBehavior; } | { "hex_encode": HexEncode; } | { "compress": Compress; } | { "decompress_binary": DecompressBinary; } | { "decompress_string": DecompressString; } | { "xor": Xor; } | { "nullif": Nullif; } | { "j_s_o_n": JSON_2; } | { "j_s_o_n_path": JSONPath; } | { "j_s_o_n_path_filter": JSONPathFilter; } | { "j_s_o_n_path_key": JSONPathKey; } | { "j_s_o_n_path_recursive": JSONPathRecursive; } | { "j_s_o_n_path_script": JSONPathScript; } | { "j_s_o_n_path_slice": JSONPathSlice; } | { "j_s_o_n_path_selector": JSONPathSelector; } | { "j_s_o_n_path_subscript": JSONPathSubscript; } | { "j_s_o_n_path_union": JSONPathUnion; } | { "format": Format; } | { "j_s_o_n_keys": JSONKeys; } | { "j_s_o_n_key_value": JSONKeyValue; } | { "j_s_o_n_keys_at_depth": JSONKeysAtDepth; } | { "j_s_o_n_object": JSONObject; } | { "j_s_o_n_object_agg": JSONObjectAgg; } | { "j_s_o_n_b_object_agg": JSONBObjectAgg; } | { "j_s_o_n_array": JSONArray; } | { "j_s_o_n_array_agg": JSONArrayAgg; } | { "j_s_o_n_exists": JSONExists; } | { "j_s_o_n_column_def": JSONColumnDef; } | { "j_s_o_n_schema": JSONSchema; } | { "j_s_o_n_set": JSONSet; } | { "j_s_o_n_strip_nulls": JSONStripNulls; } | { "j_s_o_n_value": JSONValue; } | { "j_s_o_n_value_array": JSONValueArray; } | { "j_s_o_n_remove": JSONRemove; } | { "j_s_o_n_table": JSONTable; } | { "j_s_o_n_type": JSONType; } | { "object_insert": ObjectInsert; } | { "open_j_s_o_n_column_def": OpenJSONColumnDef; } | { "open_j_s_o_n": OpenJSON; } | { "j_s_o_n_b_exists": JSONBExists; } | { "j_s_o_n_b_contains": BinaryFunc; } | { "j_s_o_n_b_extract": BinaryFunc; } | { "j_s_o_n_cast": JSONCast; } | { "j_s_o_n_extract": JSONExtract; } | { "j_s_o_n_extract_quote": JSONExtractQuote; } | { "j_s_o_n_extract_array": JSONExtractArray; } | { "j_s_o_n_extract_scalar": JSONExtractScalar; } | { "j_s_o_n_b_extract_scalar": JSONBExtractScalar; } | { "j_s_o_n_format": JSONFormat; } | { "j_s_o_n_bool": UnaryFunc; } | { "j_s_o_n_path_root": JSONPathRoot; } | { "j_s_o_n_array_append": JSONArrayAppend; } | { "j_s_o_n_array_contains": JSONArrayContains; } | { "j_s_o_n_array_insert": JSONArrayInsert; } | { "parse_j_s_o_n": ParseJSON; } | { "parse_url": ParseUrl; } | { "parse_ip": ParseIp; } | { "parse_time": ParseTime; } | { "parse_datetime": ParseDatetime; } | { "map": Map_2; } | { "map_cat": MapCat; } | { "map_delete": MapDelete; } | { "map_insert": MapInsert; } | { "map_pick": MapPick; } | { "scope_resolution": ScopeResolution; } | { "slice": Slice; } | { "var_map": VarMap; } | { "match_against": MatchAgainst; } | { "m_d5_digest": MD5Digest; } | { "m_d5_number_lower64": UnaryFunc; } | { "m_d5_number_upper64": UnaryFunc; } | { "monthname": Monthname; } | { "ntile": Ntile; } | { "normalize": Normalize; } | { "normal": Normal; } | { "predict": Predict; } | { "m_l_translate": MLTranslate; } | { "features_at_time": FeaturesAtTime; } | { "generate_embedding": GenerateEmbedding; } | { "m_l_forecast": MLForecast; } | { "model_attribute": ModelAttribute; } | { "vector_search": VectorSearch; } | { "quantile": Quantile; } | { "approx_quantile": ApproxQuantile; } | { "approx_percentile_estimate": ApproxPercentileEstimate; } | { "randn": Randn; } | { "randstr": Randstr; } | { "range_n": RangeN; } | { "range_bucket": RangeBucket; } | { "read_c_s_v": ReadCSV; } | { "read_parquet": ReadParquet; } | { "reduce": Reduce; } | { "regexp_extract_all": RegexpExtractAll; } | { "regexp_i_like": RegexpILike; } | { "regexp_full_match": RegexpFullMatch; } | { "regexp_instr": RegexpInstr; } | { "regexp_split": RegexpSplit; } | { "regexp_count": RegexpCount; } | { "regr_valx": RegrValx; } | { "regr_valy": RegrValy; } | { "regr_avgy": RegrAvgy; } | { "regr_avgx": RegrAvgx; } | { "regr_count": RegrCount; } | { "regr_intercept": RegrIntercept; } | { "regr_r2": RegrR2; } | { "regr_sxx": RegrSxx; } | { "regr_sxy": RegrSxy; } | { "regr_syy": RegrSyy; } | { "regr_slope": RegrSlope; } | { "safe_add": SafeAdd; } | { "safe_divide": SafeDivide; } | { "safe_multiply": SafeMultiply; } | { "safe_subtract": SafeSubtract; } | { "s_h_a2": SHA2; } | { "s_h_a2_digest": SHA2Digest; } | { "sort_array": SortArray; } | { "split_part": SplitPart; } | { "substring_index": SubstringIndex; } | { "standard_hash": StandardHash; } | { "str_position": StrPosition; } | { "search": Search; } | { "search_ip": SearchIp; } | { "str_to_date": StrToDate; } | { "date_str_to_date": UnaryFunc; } | { "date_to_date_str": UnaryFunc; } | { "str_to_time": StrToTime; } | { "str_to_unix": StrToUnix; } | { "str_to_map": StrToMap; } | { "number_to_str": NumberToStr; } | { "from_base": FromBase; } | { "stuff": Stuff; } | { "time_to_str": TimeToStr; } | { "time_str_to_time": TimeStrToTime; } | { "ts_or_ds_add": TsOrDsAdd; } | { "ts_or_ds_diff": TsOrDsDiff; } | { "ts_or_ds_to_date": TsOrDsToDate; } | { "ts_or_ds_to_time": TsOrDsToTime; } | { "unhex": Unhex; } | { "uniform": Uniform; } | { "unix_to_str": UnixToStr; } | { "unix_to_time": UnixToTime; } | { "uuid": Uuid; } | { "timestamp_from_parts": TimestampFromParts; } | { "timestamp_tz_from_parts": TimestampTzFromParts; } | { "corr": Corr; } | { "width_bucket": WidthBucket; } | { "covar_samp": CovarSamp; } | { "covar_pop": CovarPop; } | { "week": Week; } | { "x_m_l_element": XMLElement; } | { "x_m_l_get": XMLGet; } | { "x_m_l_table": XMLTable; } | { "x_m_l_key_value_option": XMLKeyValueOption; } | { "zipf": Zipf; } | { "merge": Merge; } | { "when": When; } | { "whens": Whens; } | { "next_value_for": NextValueFor; } | { "return_stmt": Expression; }; /** * Extract a specific Expression variant by its key name. * * @example * ```typescript * type SelectExpr = ExpressionByKey<'select'>; * // => { "select": Select } * ``` */ declare type ExpressionByKey = Extract>; /** * Extract a specific expression variant by its key name * * @example * ```typescript * type SelectExpr = ExpressionByType<'select'>; * // { "select": Select } * ``` */ declare type ExpressionByType = ExpressionByKey; /** * Extract the inner data type of a specific Expression variant. * * @example * ```typescript * type SelectData = ExpressionInner<'select'>; * // => Select * ``` */ declare type ExpressionInner = ExpressionByKey extends Record ? V : never; /** * Input type that can be normalized to an Expression * Used by builder functions that accept flexible input */ declare type ExpressionInput = Expression | string | number | boolean | null; /** * Distributive conditional type to extract all variant key names from Expression union. * * Each variant is { "key": Data }, so keyof each variant gives us the key name. * The distributive conditional distributes over the union members. */ declare type ExpressionType = Expression extends infer E ? E extends Record ? K extends string ? K : never : never : never; /** Anything that can be used as an expression: Expr, string (→ column), number/boolean/null (→ literal) */ export declare type ExprInput = Expr | string | number | boolean | null; /** * ExternalProperty */ declare type ExternalProperty = { this: Expression | null; }; export declare function extract(unit: string, from: ExprInput): Expr; /** * EXTRACT function */ declare type ExtractFunc = { this: Expression; field: DateTimeField; }; /** * FallbackProperty */ declare type FallbackProperty = { no: Expression | null; protection: Expression | null; }; /** * FarmFingerprint */ declare type FarmFingerprint = { expressions: Array; }; /** * FeaturesAtTime */ declare type FeaturesAtTime = { this: Expression; time: Expression | null; num_rows: Expression | null; ignore_feature_nulls: Expression | null; }; /** * FETCH FIRST/NEXT clause (SQL standard) */ declare type Fetch = { /** * FIRST or NEXT */ direction: string; /** * Count expression (optional) */ count: Expression | null; /** * PERCENT modifier */ percent: boolean; /** * ROWS or ROW keyword present */ rows: boolean; /** * WITH TIES modifier */ with_ties: boolean; }; /** * FileFormatProperty */ declare type FileFormatProperty = { this: Expression | null; expressions: Array; hive_format: Expression | null; }; /** * Filter */ declare type Filter = { this: Expression; expression: Expression; }; /** * Find all nodes matching a predicate * * @example * ```typescript * const columns = findAll(ast, (node) => getExprType(node) === 'column'); * ``` */ export declare function findAll(node: Expression, predicate: NodePredicate): Expression[]; /** * Find the nearest ancestor of a target node that matches a predicate. * * Walks the tree from the root, tracking the ancestor stack. When the * target is found, searches ancestors from nearest to farthest. * * Uses reference equality (`===`) to identify the target. * * @returns The matching ancestor, or `null` if none matches or target not found. */ declare function findAncestor(root: Expression, target: Expression, predicate: NodePredicate): Expression | null; /** * Find all nodes of a specific type * * @example * ```typescript * const selects = findByType(ast, 'select'); * const columns = findByType(ast, 'column'); * ``` */ declare function findByType(node: Expression, type: T): Expression[]; /** * Find the first node matching a predicate * * @example * ```typescript * const firstColumn = findFirst(ast, (node) => getExprType(node) === 'column'); * ``` */ declare function findFirst(node: Expression, predicate: NodePredicate): Expression | undefined; /** * Float64 */ declare type Float64 = { this: Expression; expression: Expression | null; }; export declare function floor(expr: ExprInput): Expr; /** * FLOOR function with optional scale and time unit (Druid: FLOOR(time TO unit)) */ declare type FloorFunc = { this: Expression; scale: Expression | null; /** * Time unit for Druid-style FLOOR(time TO unit) syntax */ to?: Expression | null; }; /** * ForeignKey */ declare type ForeignKey = { expressions: Array; reference: Expression | null; delete: Expression | null; update: Expression | null; options: Array; }; /** * Foreign key reference */ declare type ForeignKeyRef = { table: TableRef; columns: Array; on_delete: ReferentialAction | null; on_update: ReferentialAction | null; /** * True if ON UPDATE appears before ON DELETE in the original SQL */ on_update_first: boolean; /** * MATCH clause (FULL, PARTIAL, SIMPLE) */ match_type: MatchType | null; /** * True if MATCH appears after ON DELETE/ON UPDATE clauses */ match_after_actions: boolean; /** * CONSTRAINT name (e.g., CONSTRAINT fk_name REFERENCES ...) */ constraint_name: string | null; /** * DEFERRABLE / NOT DEFERRABLE */ deferrable: boolean | null; /** * Snowflake: FOREIGN KEY REFERENCES (includes FOREIGN KEY keywords before REFERENCES) */ has_foreign_key_keywords: boolean; }; /** * ForIn */ declare type ForIn = { this: Expression; expression: Expression; }; /** * Format */ declare type Format = { this: Expression; expressions: Array; }; /** * Format/pretty-print SQL. * * @param sql - The SQL string to format * @param dialect - The dialect to use * @returns The formatted SQL * * @example * ```typescript * const result = format("SELECT a,b FROM t WHERE x=1", Dialect.PostgreSQL); * // result.sql[0] = "SELECT\n a,\n b\nFROM t\nWHERE x = 1" * ``` */ export declare function format(sql: string, dialect?: Dialect): TranspileResult; /** * Guard options for formatting very large/complex SQL safely. */ export declare interface FormatOptions { /** Maximum SQL input size in bytes */ maxInputBytes?: number; /** Maximum token count after tokenization */ maxTokens?: number; /** Maximum AST node count after parsing */ maxAstNodes?: number; /** Maximum set-operation count (UNION/INTERSECT/EXCEPT) before parse */ maxSetOpChain?: number; } /** * Format override for a column in Teradata */ declare type FormatPhrase = { this: Expression; format: string; }; /** * Format/pretty-print SQL with explicit guard limits. * * This can be used to tune handling for very large SQL inputs. */ export declare function formatWithOptions(sql: string, dialect?: Dialect, options?: FormatOptions): TranspileResult; /** * FreespaceProperty */ declare type FreespaceProperty = { this: Expression; percent: Expression | null; }; /** * Represent the FROM clause of a SELECT statement. * * Contains one or more table sources (tables, subqueries, table-valued * functions, etc.). Multiple entries represent comma-separated implicit joins. */ declare type From = { /** * The table source expressions. */ expressions: Array; }; /** * FromBase */ declare type FromBase = { this: Expression; expression: Expression; }; /** * FromTimeZone */ declare type FromTimeZone = { this: Expression; zone: Expression | null; }; /** * FROM_UNIXTIME function */ declare type FromUnixtimeFunc = { this: Expression; format: Expression | null; }; /** Create a generic function call expression. */ export declare function func(name: string, ...args: ExprInput[]): Expr; /** * Represent a scalar function call (e.g. `UPPER(name)`, `COALESCE(a, b)`). * * This is the generic function node. Well-known aggregates, window functions, * and built-in functions each have their own dedicated `Expression` variants * (e.g. `Count`, `Sum`, `WindowFunction`). Functions that the parser does * not recognize as built-ins are represented with this struct. */ declare type Function_2 = { /** * The function name, as originally written (may be schema-qualified). */ name: string; /** * Positional arguments to the function. */ args: Array; /** * Whether DISTINCT was specified inside the call (e.g. `COUNT(DISTINCT x)`). */ distinct: boolean; trailing_comments: Array; /** * Whether this function uses bracket syntax (e.g., MAP[keys, values]) */ use_bracket_syntax: boolean; /** * Whether this function was called without parentheses (e.g., CURRENT_TIMESTAMP vs CURRENT_TIMESTAMP()) */ no_parens: boolean; /** * Whether the function name was quoted (e.g., `p.d.UdF` in BigQuery) */ quoted: boolean; /** * Source position span */ span?: Span | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Function body */ declare type FunctionBody = { "Block": string; } | { "StringLiteral": string; } | { "Expression": Expression; } | { "External": string; } | { "Return": Expression; } | { "Statements": Array; } | { "DollarQuoted": { content: string; tag: string | null; }; } | { "RawBlock": string; }; /** * Function call with EMITS clause (Exasol) * Used for JSON_EXTRACT(...) EMITS (col1 TYPE1, col2 TYPE2) */ declare type FunctionEmits = { /** * The function call expression */ this: Expression; /** * The EMITS schema definition */ emits: Expression; }; /** * Union of all function-related expression types */ declare type FunctionExpression = ExpressionByType<'function'> | ExpressionByType<'aggregate_function'> | ExpressionByType<'window_function'>; /** * Function parameter */ declare type FunctionParameter = { name: Identifier | null; data_type: DataType; mode: ParameterMode | null; default: Expression | null; /** * Original text of the mode keyword for case-preserving output (e.g., "inout", "VARIADIC") */ mode_text?: string | null; }; /** * Types of properties in CREATE FUNCTION for tracking their original order */ declare type FunctionPropertyKind = "Set" | "As" | "Using" | "Language" | "Determinism" | "NullInput" | "Security" | "SqlDataAccess" | "Options" | "Environment" | "Handler" | "RuntimeVersion" | "Packages" | "ParameterStyle"; /** * Function security (DEFINER, INVOKER, or NONE) */ declare type FunctionSecurity = "Definer" | "Invoker" | "None"; /** * A SET option in CREATE FUNCTION (PostgreSQL) */ declare type FunctionSetOption = { name: string; value: FunctionSetValue; }; /** * The value of a SET option */ declare type FunctionSetValue = { "Value": { value: string; use_to: boolean; }; } | "FromCurrent"; /** * Hive CREATE FUNCTION resource in a USING clause */ declare type FunctionUsingResource = { kind: string; uri: string; }; /** * GapFill */ declare type GapFill = { this: Expression; ts_column: Expression | null; bucket_width: Expression | null; partitioning_columns: Expression | null; value_columns: Expression | null; origin: Expression | null; ignore_nulls: Expression | null; }; /** * Generate SQL from an AST. * * @param ast - The AST to generate SQL from * @param dialect - The target dialect * @returns The generated SQL */ export declare function generate(ast: any, dialect?: Dialect): TranspileResult; /** * Generated identity column constraint */ declare type GeneratedAsIdentity = { /** * True for ALWAYS, False for BY DEFAULT */ always: boolean; /** * ON NULL (only valid with BY DEFAULT) */ on_null: boolean; /** * START WITH value */ start: Expression | null; /** * INCREMENT BY value */ increment: Expression | null; /** * MINVALUE */ minvalue: Expression | null; /** * MAXVALUE */ maxvalue: Expression | null; /** * CYCLE option - Some(true) = CYCLE, Some(false) = NO CYCLE, None = not specified */ cycle: boolean | null; }; /** * GeneratedAsIdentityColumnConstraint */ declare type GeneratedAsIdentityColumnConstraint = { this: Expression | null; expression: Expression | null; on_null: Expression | null; start: Expression | null; increment: Expression | null; minvalue: Expression | null; maxvalue: Expression | null; cycle: Expression | null; order: Expression | null; }; /** * TSQL temporal column constraint: GENERATED ALWAYS AS ROW START|END [HIDDEN] */ declare type GeneratedAsRow = { /** * true = ROW START, false = ROW END */ start: boolean; /** * HIDDEN modifier */ hidden: boolean; }; /** * GeneratedAsRowColumnConstraint */ declare type GeneratedAsRowColumnConstraint = { start: Expression | null; hidden: Expression | null; }; /** * Generate SQL from a standalone DataType AST node. * * @param dataType - The DataType object to render * @param dialect - The target dialect * @returns The generated data type SQL * * @example * ```typescript * const parsed = parseDataType("VARCHAR(255)", Dialect.DuckDB); * const rendered = generateDataType(parsed.dataType!, Dialect.PostgreSQL); * // rendered.sql = "VARCHAR(255)" * ``` */ export declare function generateDataType(dataType: DataType, dialect?: Dialect): GenerateDataTypeResult; /** * Result of a standalone data type generation operation */ export declare interface GenerateDataTypeResult { success: boolean; sql?: string; error?: string; /** 1-based line number where the error occurred */ errorLine?: number; /** 1-based column number where the error occurred */ errorColumn?: number; /** Start byte offset of the error range */ errorStart?: number; /** End byte offset of the error range (exclusive) */ errorEnd?: number; } /** * GenerateDateArray */ declare type GenerateDateArray = { start: Expression | null; end: Expression | null; step: Expression | null; }; /** * GenerateEmbedding */ declare type GenerateEmbedding = { this: Expression; expression: Expression; params_struct: Expression | null; is_text: Expression | null; }; /** * GenerateSeries */ declare type GenerateSeries = { start: Expression | null; end: Expression | null; step: Expression | null; is_end_exclusive: Expression | null; }; /** * GenerateTimestampArray */ declare type GenerateTimestampArray = { start: Expression | null; end: Expression | null; step: Expression | null; }; /** * Get */ declare type Get = { this: Expression; target: Expression | null; properties: Array; }; /** * Get all aggregate function calls in the AST (via WASM) */ declare function getAggregateFunctions(node: Expression): Expression[]; /** * Getbit */ declare type Getbit = { this: Expression; expression: Expression; zero_is_msb: Expression | null; }; /** * Get all child expressions from a node. * * Unwraps the outer Expression envelope, then iterates the inner data * looking for Expression children — including those nested inside * non-Expression structs like From, Where, GroupBy, etc. */ declare function getChildren(node: Expression): Array<{ key: string; value: Expression | Expression[]; }>; /** * Get all column names as strings (via WASM) */ declare function getColumnNames(node: Expression): string[]; /** * Get all column references in the AST * * @example * ```typescript * const columns = getColumns(ast); * ``` */ export declare function getColumns(node: Expression): Expression[]; /** * Get the depth of the AST */ declare function getDepth(node: Expression): number; /** * Get list of supported dialects in this build. * * The full build (`@polyglot-sql/sdk`) includes all 34 dialects. * Per-dialect builds (e.g., `@polyglot-sql/sdk/clickhouse`) include only * `"generic"` and the selected dialect. * * Use this function to check dialect availability before calling {@link transpile}. * * @returns Array of dialect name strings available in this build * * @example * ```typescript * const dialects = getDialects(); * // Full build: ["generic", "postgresql", "mysql", "bigquery", ...] * // Per-dialect: ["generic", "clickhouse"] * * if (dialects.includes("postgresql")) { * // Safe to transpile to PostgreSQL * } * ``` */ export declare function getDialects(): string[]; /** * Get the inner data of an Expression at runtime. * * @example * ```typescript * const expr = parse("SELECT 1")[0]; * const selectData = getExprData(expr); * // selectData.expressions, selectData.from, etc. * ``` */ declare function getExprData(expr: Expression): Record; /** * Get the type tag (variant key) of an Expression at runtime. * * @example * ```typescript * const expr = parse("SELECT 1")[0]; * getExprType(expr) // => "select" * ``` */ declare function getExprType(expr: Expression): ExpressionType; /** * GetExtract */ declare type GetExtract = { this: Expression; expression: Expression; }; /** * Get all function calls in the AST (via WASM) */ declare function getFunctions(node: Expression): Expression[]; /** * Get all identifiers in the AST */ declare function getIdentifiers(node: Expression): Expression[]; /** * Get the inferred data type from an Expression, if it has been type-annotated. * * After calling `annotateTypes()`, value-producing expressions (columns, operators, * functions, casts, etc.) carry an `inferred_type` field with their resolved SQL type. * * @example * ```typescript * const result = annotateTypes("SELECT 1 + 2", Dialect.Generic); * if (result.success) { * const addExpr = result.ast![0]; // the SELECT * // Navigate to the "1 + 2" expression and check its type: * const dt = getInferredType(someExpr); * // dt => { data_type: "int", length: null, integer_spelling: false } * } * ``` * * @returns The inferred DataType, or `undefined` if not annotated or not a value-producing expression. */ export declare function getInferredType(expr: Expression): DataType | undefined; /** * Get all literals in the AST (via WASM) */ declare function getLiterals(node: Expression): Expression[]; /** * Get the depth of a specific node within the AST. * * The root node has depth 1. Returns 0 if the target is not found. * * Uses reference equality (`===`) to identify the target. */ declare function getNodeDepth(root: Expression, target: Expression): number; /** * Find the parent of a target node in the AST. * * Uses reference equality (`===`) to identify the target, so the target * must be a reference obtained from the same AST object graph (e.g. via * `findFirst()` or `findAll()`). * * @returns The parent Expression, or `null` if target is the root or not found. */ declare function getParent(root: Expression, target: Expression): Expression | null; /** * Get all source tables that feed into a column. * * @param column - Column name to trace * @param sql - SQL string to analyze * @param dialect - Dialect for parsing (default: 'generic') * * @example * ```typescript * const result = getSourceTables("a", "SELECT t.a FROM t JOIN s ON t.id = s.id"); * // result.tables === ["t"] * ``` */ export declare function getSourceTables(column: string, sql: string, dialect?: string): SourceTablesResult; /** * Get all subqueries in the AST (via WASM) */ declare function getSubqueries(node: Expression): Expression[]; /** * Get all table names as strings (via WASM) */ declare function getTableNames(node: Expression): string[]; /** * Get all table references in the AST */ declare function getTables(node: Expression): Expression[]; /** * Get the version of the Polyglot library. * * @returns Version string */ export declare function getVersion(): string; /** * Get all window function calls in the AST (via WASM) */ declare function getWindowFunctions(node: Expression): Expression[]; /** * GRANT statement */ declare type Grant = { /** * Privileges to grant (e.g., SELECT, INSERT, UPDATE(col1, col2)) */ privileges: Array; /** * Object kind (TABLE, SCHEMA, FUNCTION, etc.) */ kind: string | null; /** * The object to grant on */ securable: Identifier; /** * Function parameter types (for FUNCTION kind) */ function_params?: Array; /** * The grantees */ principals: Array; /** * WITH GRANT OPTION */ grant_option: boolean; /** * TSQL: AS principal (the grantor role) */ as_principal?: Identifier | null; }; /** * Principal in GRANT/REVOKE (user, role, etc.) */ declare type GrantPrincipal = { /** * The name of the principal */ name: Identifier; /** * Whether prefixed with ROLE keyword */ is_role: boolean; /** * Whether prefixed with GROUP keyword (Redshift) */ is_group: boolean; /** * Whether prefixed with SHARE keyword (Snowflake) */ is_share: boolean; }; /** * GrantPrivilege */ declare type GrantPrivilege = { this: Expression; expressions: Array; }; export declare function greatest(...exprs: ExprInput[]): Expr; /** * Group */ declare type Group = { expressions: Array; grouping_sets: Expression | null; cube: Expression | null; rollup: Expression | null; totals: Expression | null; /** * GROUP BY modifier: Some(true) = ALL, Some(false) = DISTINCT, None = no modifier */ all: boolean | null; }; /** * Represent a GROUP BY clause with optional ALL/DISTINCT and WITH TOTALS modifiers. * * The `expressions` list may contain plain columns, ordinal positions, * ROLLUP/CUBE/GROUPING SETS expressions, or the special empty-set `()`. */ declare type GroupBy = { /** * The grouping expressions. */ expressions: Array; /** * GROUP BY modifier: Some(true) = ALL, Some(false) = DISTINCT, None = no modifier */ all: boolean | null; /** * ClickHouse: WITH TOTALS modifier */ totals: boolean; /** * Leading comments that appeared before the GROUP BY keyword */ comments?: Array; }; /** * GROUP_CONCAT function (MySQL style) */ declare type GroupConcatFunc = { this: Expression; separator: Expression | null; order_by: Array | null; distinct: boolean; filter: Expression | null; /** * MySQL 8.0.19+: LIMIT n inside GROUP_CONCAT */ limit?: Expression | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Grouping */ declare type Grouping = { expressions: Array; }; /** * GroupingId */ declare type GroupingId = { expressions: Array; }; /** * GroupingSets */ declare type GroupingSets = { expressions: Array; }; /** * Check if the AST contains any aggregate functions */ declare function hasAggregates(node: Expression): boolean; /** Check if any edits represent actual changes (not keeps) */ export declare function hasChanges(edits: DiffEdit[]): boolean; /** * HashAgg */ declare type HashAgg = { this: Expression; expressions: Array; }; /** * Check if the AST contains any subqueries */ declare function hasSubqueries(node: Expression): boolean; /** * Check if the AST contains any window functions */ declare function hasWindowFunctions(node: Expression): boolean; /** * Represent a HAVING clause containing a predicate over aggregate results. */ declare type Having = { /** * The filter predicate, typically involving aggregate functions. */ this: Expression; /** * Leading comments that appeared before the HAVING keyword */ comments?: Array; }; /** * HavingMax */ declare type HavingMax = { this: Expression; expression: Expression; max: Expression | null; }; /** * Heredoc */ declare type Heredoc = { this: Expression; tag: Expression | null; }; /** * HexEncode */ declare type HexEncode = { this: Expression; case: Expression | null; }; /** * HexStringExpr - Hex string expression (not literal) * BigQuery: converts to FROM_HEX(this) */ declare type HexStringExpr = { this: Expression; is_integer: boolean | null; }; /** * Query hint */ declare type Hint = { expressions: Array; }; /** * Individual hint expression */ declare type HintExpression = { "Function": { name: string; args: Array; }; } | { "Identifier": string; } | { "Raw": string; }; /** * Historical data / Time travel (Snowflake) - BEFORE (STATEMENT => ...) or AT (TIMESTAMP => ...) */ declare type HistoricalData = { /** * The time travel kind: "BEFORE", "AT", or "END" (as an Identifier expression) */ this: Expression; /** * The time travel type: "STATEMENT", "TIMESTAMP", "OFFSET", "STREAM", or "VERSION" */ kind: string; /** * The expression value (e.g., the statement ID or timestamp) */ expression: Expression; }; /** * Hll */ declare type Hll = { this: Expression; expressions: Array; }; /** * Represent a SQL identifier (table name, column name, alias, keyword-as-name, etc.). * * The `quoted` flag indicates whether the identifier was originally delimited * (double-quoted, backtick-quoted, or bracket-quoted depending on the * dialect). The generator uses this flag to decide whether to emit quoting * characters. */ declare type Identifier = { /** * The raw text of the identifier, without any quoting characters. */ name: string; /** * Whether the identifier was quoted in the source SQL. */ quoted: boolean; trailing_comments: Array; /** * Source position span (populated during parsing, None for programmatically constructed nodes) */ span?: Span | null; }; /** * IF function */ declare type IfFunc = { condition: Expression; true_value: Expression; false_value: Expression | null; /** * Original function name (IF, IFF, IIF) for round-trip preservation */ original_name?: string | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; export declare function ifNull(expr: ExprInput, fallback: ExprInput): Expr; /** * Represent an IN predicate (`x IN (1, 2, 3)` or `x IN (SELECT ...)`). * * Either `expressions` (a value list) or `query` (a subquery) is populated, * but not both. When `not` is true, the predicate is `NOT IN`. */ declare type In = { /** * The expression being tested. */ this: Expression; /** * The value list (mutually exclusive with `query`). */ expressions: Array; /** * A subquery (mutually exclusive with `expressions`). */ query: Expression | null; /** * Whether this is NOT IN. */ not: boolean; global?: boolean; /** * BigQuery: IN UNNEST(expr) */ unnest?: Expression | null; /** * Whether the right side is a bare field reference (no parentheses). * Matches Python sqlglot's `field` attribute on `In` expression. * e.g., `a IN subquery1` vs `a IN (subquery1)` */ is_field?: boolean; }; /** * IncludeProperty */ declare type IncludeProperty = { this: Expression; alias: string | null; column_def: Expression | null; }; /** * Index */ declare type Index = { this: Expression | null; table: Expression | null; unique: boolean; primary: Expression | null; amp: Expression | null; params: Array; }; /** * Index column specification */ declare type IndexColumn = { column: Identifier; desc: boolean; /** * Explicit ASC keyword was present */ asc: boolean; nulls_first: boolean | null; /** * PostgreSQL operator class (e.g., varchar_pattern_ops, public.gin_trgm_ops) */ opclass?: string | null; }; /** * IndexColumnConstraint */ declare type IndexColumnConstraint = { this: Expression | null; expressions: Array; kind: string | null; index_type: Expression | null; options: Array; expression: Expression | null; granularity: Expression | null; }; /** * IndexConstraintOption */ declare type IndexConstraintOption = { key_block_size: Expression | null; using: Expression | null; parser: Expression | null; comment: Expression | null; visible: Expression | null; engine_attr: Expression | null; secondary_engine_attr: Expression | null; }; /** * IndexParameters */ declare type IndexParameters = { using: Expression | null; include: Expression | null; columns: Array; with_storage: Expression | null; partition_by: Expression | null; tablespace: Expression | null; where_: Expression | null; on: Expression | null; }; /** * IndexTableHint */ declare type IndexTableHint = { this: Expression; expressions: Array; target: Expression | null; }; /** * InheritsProperty */ declare type InheritsProperty = { expressions: Array; }; /** * Initialize the WASM module. * With the bundler target, the WASM module is synchronously initialized * on import. This function is kept for backwards compatibility. */ export declare function init(): Promise; export declare function initcap(expr: ExprInput): Expr; /** * InOutColumnConstraint */ declare type InOutColumnConstraint = { input_: Expression | null; output: Expression | null; }; /** * InputModelProperty */ declare type InputModelProperty = { this: Expression; }; /** * InputOutputFormat */ declare type InputOutputFormat = { input_format: Expression | null; output_format: Expression | null; }; /** * INSERT statement */ declare type Insert = { table: TableRef; columns: Array; values: Array>; query: Expression | null; /** * INSERT OVERWRITE for Hive/Spark */ overwrite: boolean; /** * PARTITION clause for Hive/Spark */ partition: Array<[Identifier, Expression | null]>; /** * INSERT OVERWRITE DIRECTORY for Hive/Spark */ directory: DirectoryInsert | null; /** * RETURNING clause (PostgreSQL, SQLite) */ returning: Array; /** * OUTPUT clause (TSQL) */ output: OutputClause | null; /** * ON CONFLICT clause (PostgreSQL, SQLite) */ on_conflict: Expression | null; /** * Leading comments before the statement */ leading_comments: Array; /** * IF EXISTS clause (Hive) */ if_exists: boolean; /** * WITH clause (CTEs) */ with: With | null; /** * INSERT IGNORE (MySQL) - ignore duplicate key errors */ ignore: boolean; /** * Source alias for VALUES clause (MySQL): VALUES (1, 2) AS new_data */ source_alias: Identifier | null; /** * Table alias (PostgreSQL): INSERT INTO table AS t(...) */ alias: Identifier | null; /** * Whether the alias uses explicit AS keyword */ alias_explicit_as: boolean; /** * DEFAULT VALUES (PostgreSQL): INSERT INTO t DEFAULT VALUES */ default_values: boolean; /** * BY NAME modifier (DuckDB): INSERT INTO x BY NAME SELECT ... */ by_name: boolean; /** * SQLite conflict action: INSERT OR ABORT|FAIL|IGNORE|REPLACE|ROLLBACK INTO ... */ conflict_action?: string | null; /** * MySQL/SQLite REPLACE INTO statement (treat like INSERT) */ is_replace: boolean; /** * Oracle-style hint: `INSERT INTO ...` (for example Oracle APPEND hints) */ hint?: Hint | null; /** * REPLACE WHERE clause (Databricks): INSERT INTO a REPLACE WHERE cond VALUES ... */ replace_where: Expression | null; /** * Source table (Hive/Spark): INSERT OVERWRITE TABLE target TABLE source */ source: Expression | null; /** * ClickHouse: INSERT INTO FUNCTION func_name(...) - the function call */ function_target?: Expression | null; /** * ClickHouse: PARTITION BY expr */ partition_by?: Expression | null; /** * ClickHouse: SETTINGS key = val, ... */ settings?: Array; }; /** Alias for insertInto. */ export declare function insert(tableName: string): InsertBuilder; /** * Fluent builder for INSERT INTO statements. * * @example * ```typescript * const sql = insertInto('users') * .columns('id', 'name') * .values(lit(1), lit('Alice')) * .toSql(); * ``` */ export declare class InsertBuilder { /* Excluded from this release type: _w */ constructor(tableName: string); /** Set the target column names. */ columns(...cols: string[]): this; /** Append a row of values. Call multiple times for multiple rows. */ values(...vals: ExprInput[]): this; /** Set the source query for INSERT ... SELECT. */ query(q: SelectBuilder): this; /** Generate SQL string. Defaults to generic dialect. */ toSql(dialect?: string): string; /** Return the Expression AST as a plain JS object. */ build(): any; /** Free the underlying WASM handle. */ free(): void; } /** Create an InsertBuilder for the given table. */ export declare function insertInto(tableName: string): InsertBuilder; /** * Install */ declare type Install = { this: Expression; from_: Expression | null; force: Expression | null; }; /** * Represent an INTERSECT set operation between two query expressions. * * Returns only rows that appear in both operands. When `all` is true, * duplicates are preserved according to their multiplicity. */ declare type Intersect = { /** * The left-hand query operand. */ left: Expression; /** * The right-hand query operand. */ right: Expression; /** * Whether INTERSECT ALL (true) or INTERSECT (false, which deduplicates). */ all: boolean; /** * Whether DISTINCT was explicitly specified */ distinct: boolean; /** * Optional WITH clause */ with: With | null; /** * ORDER BY applied to entire INTERSECT result */ order_by: OrderBy | null; /** * LIMIT applied to entire INTERSECT result */ limit: Expression | null; /** * OFFSET applied to entire INTERSECT result */ offset: Expression | null; /** * DISTRIBUTE BY clause (Hive/Spark) */ distribute_by?: DistributeBy | null; /** * SORT BY clause (Hive/Spark) */ sort_by?: SortBy | null; /** * CLUSTER BY clause (Hive/Spark) */ cluster_by?: ClusterBy | null; /** * DuckDB BY NAME modifier */ by_name: boolean; /** * BigQuery: Set operation side (LEFT, RIGHT, FULL) */ side?: string | null; /** * BigQuery: Set operation kind (INNER) */ kind?: string | null; /** * BigQuery: CORRESPONDING modifier */ corresponding: boolean; /** * BigQuery: STRICT modifier (before CORRESPONDING) */ strict: boolean; /** * BigQuery: BY (columns) after CORRESPONDING */ on_columns?: Array; }; /** Create an INTERSECT of two SELECT queries. */ export declare function intersect(left: SelectBuilder, right: SelectBuilder): SetOpBuilder; /** * Interval expression */ declare type Interval = { /** * The value expression (e.g., '1', 5, column_ref) */ this: Expression | null; /** * The unit specification (optional - can be None, a simple unit, a span, or an expression) */ unit: IntervalUnitSpec | null; }; /** * IntervalOp */ declare type IntervalOp = { unit: string | null; expression: Expression; }; /** * Interval span for ranges like HOUR TO SECOND */ declare type IntervalSpan = { /** * Start unit (e.g., HOUR) */ this: IntervalUnit; /** * End unit (e.g., SECOND) */ expression: IntervalUnit; }; /** * Expression-based interval span for Oracle (e.g., DAY(9) TO SECOND(3)) * Unlike IntervalSpan, this uses expressions to represent units with optional precision */ declare type IntervalSpanExpr = { /** * Start unit expression (e.g., Var("DAY") or Anonymous("DAY", [9])) */ this: Expression; /** * End unit expression (e.g., Var("SECOND") or Anonymous("SECOND", [3])) */ expression: Expression; }; declare type IntervalUnit = "Year" | "Quarter" | "Month" | "Week" | "Day" | "Hour" | "Minute" | "Second" | "Millisecond" | "Microsecond" | "Nanosecond"; /** * Specification for interval unit - can be a simple unit, a span (HOUR TO SECOND), or an expression */ declare type IntervalUnitSpec = { "type": "simple"; unit: IntervalUnit; /** * Whether to use plural form (e.g., DAYS vs DAY) */ use_plural: boolean; } | { "type": "span"; } & IntervalSpan | { "type": "expr_span"; } & IntervalSpanExpr | { "type": "expr"; } & Expression; /** * Into */ declare type IntoClause = { this: Expression | null; temporary: boolean; unlogged: Expression | null; bulk_collect: Expression | null; expressions: Array; }; /** * Introducer */ declare type Introducer = { this: Expression; expression: Expression; }; /** Type guard for addition (+) expressions */ declare const isAdd: (expr: Expression) => expr is { add: BinaryOp; }; /** Type guard for aggregate function calls */ declare const isAggregateFunction: (expr: Expression) => expr is { aggregate_function: AggregateFunction; }; /** Type guard for alias expressions */ declare const isAlias: (expr: Expression) => expr is { alias: Alias; }; /** Type guard for ALTER TABLE expressions */ declare const isAlterTable: (expr: Expression) => expr is { alter_table: AlterTable; }; /** Type guard for AND expressions */ declare const isAnd: (expr: Expression) => expr is { and: BinaryOp; }; /** Check if expression is an arithmetic operator */ declare function isArithmetic(expr: Expression): boolean; /** Type guard for AVG function */ declare const isAvg: (expr: Expression) => expr is { avg: AggFunc; }; /** Type guard for BETWEEN expressions */ declare const isBetween: (expr: Expression) => expr is { between: Between; }; /** Type guard for boolean literals */ declare const isBoolean: (expr: Expression) => expr is { boolean: BooleanLiteral; }; /** Type guard for CASE expressions */ declare const isCase: (expr: Expression) => expr is { case: Case; }; /** Type guard for CAST expressions */ declare const isCast: (expr: Expression) => expr is { cast: Cast; }; /** Type guard for COALESCE function */ declare const isCoalesce: (expr: Expression) => expr is { coalesce: VarArgFunc; }; /** Type guard for column references */ export declare const isColumn: (expr: Expression) => expr is { column: Column; }; /** Check if expression is a comparison operator */ declare function isComparison(expr: Expression): boolean; /** Type guard for concatenation (||) expressions */ declare const isConcat: (expr: Expression) => expr is { concat: BinaryOp; }; /** Type guard for COUNT function */ declare const isCount: (expr: Expression) => expr is { count: CountFunc; }; /** Type guard for CREATE INDEX expressions */ declare const isCreateIndex: (expr: Expression) => expr is { create_index: CreateIndex; }; /** Type guard for CREATE TABLE expressions */ declare const isCreateTable: (expr: Expression) => expr is { create_table: CreateTable; }; /** Type guard for CREATE VIEW expressions */ declare const isCreateView: (expr: Expression) => expr is { create_view: CreateView; }; /** Type guard for CTE expressions */ declare const isCte: (expr: Expression) => expr is { cte: Cte; }; /** Check if expression is a DDL statement */ declare function isDDL(expr: Expression): boolean; /** Type guard for DELETE expressions */ declare const isDelete: (expr: Expression) => expr is { delete: Delete; }; /** Type guard for division (/) expressions */ declare const isDiv: (expr: Expression) => expr is { div: BinaryOp; }; /** Type guard for DROP INDEX expressions */ declare const isDropIndex: (expr: Expression) => expr is { drop_index: DropIndex; }; /** Type guard for DROP TABLE expressions */ declare const isDropTable: (expr: Expression) => expr is { drop_table: DropTable; }; /** Type guard for DROP VIEW expressions */ declare const isDropView: (expr: Expression) => expr is { drop_view: DropView; }; /** Type guard for equality (=) expressions */ declare const isEq: (expr: Expression) => expr is { eq: BinaryOp; }; /** Type guard for EXCEPT expressions */ declare const isExcept: (expr: Expression) => expr is { except: Except; }; /** Type guard for EXISTS expressions */ declare const isExists: (expr: Expression) => expr is { exists: Exists; }; /** * Check if a runtime value looks like an Expression. * * Expressions in the externally tagged format are single-key objects * where the key is the variant name and the value is the inner data object. * * Important: The inner value must be a non-null, non-array plain object. * Structs like From { expressions: Vec } serialize as * { "expressions": [...] } — a single-key object with an array value. * These must NOT be treated as Expressions, or the transformer will corrupt them. */ declare function isExpressionValue(value: unknown): value is Expression; /** Type guard for FROM clause */ declare const isFrom: (expr: Expression) => expr is { from: From; }; /** Type guard for generic function calls */ export declare const isFunction: (expr: Expression) => expr is { function: Function_2; }; /** Type guard for GROUP BY clause */ declare const isGroupBy: (expr: Expression) => expr is { group_by: GroupBy; }; /** Type guard for greater than (>) expressions */ declare const isGt: (expr: Expression) => expr is { gt: BinaryOp; }; /** Type guard for greater than or equal (>=) expressions */ declare const isGte: (expr: Expression) => expr is { gte: BinaryOp; }; /** Type guard for HAVING clause */ declare const isHaving: (expr: Expression) => expr is { having: Having; }; /** Type guard for identifier expressions */ declare const isIdentifier: (expr: Expression) => expr is { identifier: Identifier; }; /** Type guard for ILIKE expressions */ declare const isILike: (expr: Expression) => expr is { i_like: LikeOp; }; /** Type guard for IN expressions */ declare const isIn: (expr: Expression) => expr is { in: In; }; /** * Check if the WASM module is initialized. */ export declare function isInitialized(): boolean; /** Type guard for INSERT expressions */ declare const isInsert: (expr: Expression) => expr is { insert: Insert; }; /** Type guard for INTERSECT expressions */ declare const isIntersect: (expr: Expression) => expr is { intersect: Intersect; }; /** Type guard for IS NULL expressions */ declare const isIsNull: (expr: Expression) => expr is { is_null: IsNull; }; /** Type guard for JOIN clause */ declare const isJoin: (expr: Expression) => expr is { join: Join; }; /** * IS JSON predicate (SQL standard) * Checks if a value is valid JSON */ declare type IsJson = { this: Expression; /** * JSON type: VALUE, SCALAR, OBJECT, or ARRAY (None = just IS JSON) */ json_type: string | null; /** * Key uniqueness constraint */ unique_keys: JsonUniqueKeys | null; /** * Whether IS NOT JSON */ negated: boolean; }; /** Type guard for LIKE expressions */ declare const isLike: (expr: Expression) => expr is { like: LikeOp; }; /** Type guard for LIMIT clause */ declare const isLimit: (expr: Expression) => expr is { limit: Limit; }; /** Type guard for literal expressions */ export declare const isLiteral: (expr: Expression) => expr is { literal: Literal; }; /** Check if expression is a logical operator */ declare function isLogical(expr: Expression): boolean; /** Type guard for less than (<) expressions */ declare const isLt: (expr: Expression) => expr is { lt: BinaryOp; }; /** Type guard for less than or equal (<=) expressions */ declare const isLte: (expr: Expression) => expr is { lte: BinaryOp; }; /** Type guard for MAX function */ declare const isMax: (expr: Expression) => expr is { max: AggFunc; }; /** Type guard for MIN function */ declare const isMin: (expr: Expression) => expr is { min: AggFunc; }; /** Type guard for modulo (%) expressions */ declare const isMod: (expr: Expression) => expr is { mod: BinaryOp; }; /** Type guard for multiplication (*) expressions */ declare const isMul: (expr: Expression) => expr is { mul: BinaryOp; }; /** Type guard for inequality (<>) expressions */ declare const isNeq: (expr: Expression) => expr is { neq: BinaryOp; }; /** Type guard for NOT expressions */ declare const isNot: (expr: Expression) => expr is { not: UnaryOp; }; /** * IS NULL predicate */ declare type IsNull = { this: Expression; not: boolean; /** * Whether this was the postfix form (ISNULL/NOTNULL) vs standard (IS NULL/IS NOT NULL) */ postfix_form: boolean; }; /** Type guard for NULLIF function */ declare const isNullIf: (expr: Expression) => expr is { null_if: BinaryFunc; }; /** Type guard for NULL literals */ declare const isNullLiteral: (expr: Expression) => expr is { null: Null; }; /** Type guard for OFFSET clause */ declare const isOffset: (expr: Expression) => expr is { offset: Offset; }; /** * IsolatedLoadingProperty */ declare type IsolatedLoadingProperty = { no: Expression | null; concurrent: Expression | null; target: Expression | null; }; /** Type guard for OR expressions */ declare const isOr: (expr: Expression) => expr is { or: BinaryOp; }; /** Type guard for ORDER BY clause */ declare const isOrderBy: (expr: Expression) => expr is { order_by: OrderBy; }; /** Type guard for ordered expressions (for ORDER BY) */ declare const isOrdered: (expr: Expression) => expr is { ordered: Ordered; }; /** Type guard for parenthesized expressions */ declare const isParen: (expr: Expression) => expr is { paren: Paren; }; /** Check if expression is a DML query (SELECT, INSERT, UPDATE, DELETE) */ declare function isQuery(expr: Expression): boolean; /** Type guard for SAFE_CAST expressions */ declare const isSafeCast: (expr: Expression) => expr is { safe_cast: Cast; }; /** Type guard for SELECT expressions */ export declare const isSelect: (expr: Expression) => expr is { select: Select; }; /** Check if expression is a set operation (UNION, INTERSECT, EXCEPT) */ declare function isSetOperation(expr: Expression): boolean; /** Type guard for star (*) expressions */ declare const isStar: (expr: Expression) => expr is { star: Star; }; /** Type guard for subtraction (-) expressions */ declare const isSub: (expr: Expression) => expr is { sub: BinaryOp; }; /** Type guard for subquery expressions */ declare const isSubquery: (expr: Expression) => expr is { subquery: Subquery; }; /** Type guard for SUM function */ declare const isSum: (expr: Expression) => expr is { sum: AggFunc; }; /** Type guard for table references */ declare const isTable: (expr: Expression) => expr is { table: TableRef; }; /** * IS TRUE / IS FALSE predicate */ declare type IsTrueFalse = { this: Expression; not: boolean; }; /** Type guard for TRY_CAST expressions */ declare const isTryCast: (expr: Expression) => expr is { try_cast: Cast; }; /** Type guard for UNION expressions */ declare const isUnion: (expr: Expression) => expr is { union: Union; }; /** Type guard for UPDATE expressions */ declare const isUpdate: (expr: Expression) => expr is { update: Update; }; /** Type guard for WHERE clause */ declare const isWhere: (expr: Expression) => expr is { where: Where; }; /** Type guard for window function calls */ declare const isWindowFunction: (expr: Expression) => expr is { window_function: WindowFunction; }; /** Type guard for WITH clause */ declare const isWith: (expr: Expression) => expr is { with: With; }; /** * JarowinklerSimilarity */ declare type JarowinklerSimilarity = { this: Expression; expression: Expression; }; /** * Represent a JOIN clause between two table sources. * * The join condition can be specified via `on` (ON predicate) or `using` * (USING column list), but not both. The `kind` field determines the join * type (INNER, LEFT, CROSS, etc.). */ declare type Join = { /** * The right-hand table expression being joined. */ this: Expression; /** * The ON condition (mutually exclusive with `using`). */ on: Expression | null; /** * The USING column list (mutually exclusive with `on`). */ using: Array; /** * The join type (INNER, LEFT, RIGHT, FULL, CROSS, etc.). */ kind: JoinKind; /** * Whether INNER keyword was explicitly used (INNER JOIN vs JOIN) */ use_inner_keyword: boolean; /** * Whether OUTER keyword was explicitly used (LEFT OUTER JOIN vs LEFT JOIN) */ use_outer_keyword: boolean; /** * Whether the ON/USING condition was deferred (assigned right-to-left for chained JOINs) */ deferred_condition: boolean; /** * TSQL join hint: LOOP, HASH, MERGE (e.g., INNER LOOP JOIN) */ join_hint?: string | null; /** * Snowflake ASOF JOIN match condition (MATCH_CONDITION clause) */ match_condition?: Expression | null; /** * PIVOT/UNPIVOT operations that follow this join (Oracle/TSQL syntax) */ pivots?: Array; /** * Comments collected between join-kind keywords (for example `INNER JOIN`) */ comments?: Array; /** * Nesting group identifier for nested join pretty-printing. * Joins in the same group were parsed together; group boundaries come from * deferred condition resolution phases. */ nesting_group: number; /** * Snowflake: DIRECTED keyword in JOIN (e.g., CROSS DIRECTED JOIN) */ directed: boolean; }; /** * Parenthesized table expression with joins * Represents: (tbl1 CROSS JOIN tbl2) or ((SELECT 1) CROSS JOIN (SELECT 2)) */ declare type JoinedTable = { /** * The left-hand side table expression */ left: Expression; /** * The joins applied to the left table */ joins: Array; /** * LATERAL VIEW clauses (Hive/Spark) */ lateral_views: Array; /** * Optional alias for the joined table expression */ alias: Identifier | null; }; /** * JoinHint */ declare type JoinHint = { this: Expression; expressions: Array; }; /** * Enumerate all supported SQL join types. * * Covers the standard join types (INNER, LEFT, RIGHT, FULL, CROSS, NATURAL) * as well as dialect-specific variants: SEMI/ANTI joins, LATERAL joins, * CROSS/OUTER APPLY (TSQL), ASOF joins (DuckDB/Snowflake), ARRAY joins * (ClickHouse), STRAIGHT_JOIN (MySQL), and implicit comma-joins. */ declare type JoinKind = "Inner" | "Left" | "Right" | "Full" | "Outer" | "Cross" | "Natural" | "NaturalLeft" | "NaturalRight" | "NaturalFull" | "Semi" | "Anti" | "LeftSemi" | "LeftAnti" | "RightSemi" | "RightAnti" | "CrossApply" | "OuterApply" | "AsOf" | "AsOfLeft" | "AsOfRight" | "Lateral" | "LeftLateral" | "Straight" | "Implicit" | "Array" | "LeftArray" | "Paste" | "Positional"; /** * JournalProperty */ declare type JournalProperty = { no: Expression | null; dual: Expression | null; before: Expression | null; local: Expression | null; after: Expression | null; }; /** * JSON */ declare type JSON_2 = { this: Expression | null; with_: Expression | null; unique: boolean; }; /** * JSONArray */ declare type JSONArray = { expressions: Array; null_handling: Expression | null; return_type: Expression | null; strict: Expression | null; }; /** * JSONArrayAgg */ declare type JSONArrayAgg = { this: Expression; order: Expression | null; null_handling: Expression | null; return_type: Expression | null; strict: Expression | null; }; /** * JSON_ARRAYAGG function */ declare type JsonArrayAggFunc = { this: Expression; order_by: Array | null; null_handling: JsonNullHandling | null; filter: Expression | null; }; /** * JSONArrayAppend */ declare type JSONArrayAppend = { this: Expression; expressions: Array; }; /** * JSONArrayContains */ declare type JSONArrayContains = { this: Expression; expression: Expression; json_type: Expression | null; }; /** * JSONArrayInsert */ declare type JSONArrayInsert = { this: Expression; expressions: Array; }; /** * JSONBExists */ declare type JSONBExists = { this: Expression; path: Expression | null; }; /** * JSONBExtractScalar */ declare type JSONBExtractScalar = { this: Expression; expression: Expression; json_type: Expression | null; }; /** * JSONBObjectAgg */ declare type JSONBObjectAgg = { this: Expression; expression: Expression; }; /** * JSONCast */ declare type JSONCast = { this: Expression; to: DataType; }; /** * JSONColumnDef */ declare type JSONColumnDef = { this: Expression | null; kind: string | null; format_json: boolean; path: Expression | null; nested_schema: Expression | null; ordinality: Expression | null; }; /** * JSONExists */ declare type JSONExists = { this: Expression; path: Expression | null; passing: Expression | null; on_condition: Expression | null; from_dcolonqmark: Expression | null; }; /** * JSONExtract */ declare type JSONExtract = { this: Expression; expression: Expression; only_json_types: Expression | null; expressions: Array; variant_extract: Expression | null; json_query: Expression | null; option: Expression | null; quote: Expression | null; on_condition: Expression | null; requires_json: Expression | null; }; /** * JSONExtractArray */ declare type JSONExtractArray = { this: Expression; expression: Expression | null; }; /** * JSON_EXTRACT / JSON_EXTRACT_SCALAR function */ declare type JsonExtractFunc = { this: Expression; path: Expression; returning: DataType | null; /** * True if parsed from -> or ->> operator syntax */ arrow_syntax: boolean; /** * True if parsed from #>> operator syntax (PostgreSQL JSONB path text extraction) */ hash_arrow_syntax: boolean; /** * Wrapper option: WITH/WITHOUT [CONDITIONAL|UNCONDITIONAL] [ARRAY] WRAPPER */ wrapper_option: string | null; /** * Quotes handling: KEEP QUOTES or OMIT QUOTES */ quotes_option: string | null; /** * ON SCALAR STRING flag */ on_scalar_string: boolean; /** * Error handling: NULL ON ERROR, ERROR ON ERROR, etc. */ on_error: string | null; }; /** * JSONExtractQuote */ declare type JSONExtractQuote = { option: Expression | null; scalar: Expression | null; }; /** * JSONExtractScalar */ declare type JSONExtractScalar = { this: Expression; expression: Expression; only_json_types: Expression | null; expressions: Array; json_type: Expression | null; scalar_only: Expression | null; }; /** * JSONFormat */ declare type JSONFormat = { this: Expression | null; options: Array; is_json: Expression | null; to_json: Expression | null; }; /** * JSONKeys */ declare type JSONKeys = { this: Expression; expression: Expression | null; expressions: Array; }; /** * JSONKeysAtDepth */ declare type JSONKeysAtDepth = { this: Expression; expression: Expression | null; mode: Expression | null; }; /** * JSONKeyValue */ declare type JSONKeyValue = { this: Expression; expression: Expression; }; /** * JSON_SET / JSON_INSERT function */ declare type JsonModifyFunc = { this: Expression; path_values: Array<[Expression, Expression]>; }; /** * JSON null handling options */ declare type JsonNullHandling = "NullOnNull" | "AbsentOnNull"; /** * JSONObject */ declare type JSONObject = { expressions: Array; null_handling: Expression | null; unique_keys: Expression | null; return_type: Expression | null; encoding: Expression | null; }; /** * JSONObjectAgg */ declare type JSONObjectAgg = { expressions: Array; null_handling: Expression | null; unique_keys: Expression | null; return_type: Expression | null; encoding: Expression | null; }; /** * JSON_OBJECTAGG function */ declare type JsonObjectAggFunc = { key: Expression; value: Expression; null_handling: JsonNullHandling | null; filter: Expression | null; }; /** * JSON_OBJECT function */ declare type JsonObjectFunc = { pairs: Array<[Expression, Expression]>; null_handling: JsonNullHandling | null; with_unique_keys: boolean; returning_type: DataType | null; format_json: boolean; encoding: string | null; /** * For JSON_OBJECT(*) syntax */ star: boolean; }; /** * JSONPath */ declare type JSONPath = { expressions: Array; escape: Expression | null; }; /** * JSONPathFilter */ declare type JSONPathFilter = { this: Expression; }; /** * JSON path extraction */ declare type JsonPathFunc = { this: Expression; paths: Array; }; /** * JSONPathKey */ declare type JSONPathKey = { this: Expression; }; /** * JSONPathRecursive */ declare type JSONPathRecursive = { this: Expression | null; }; /** * JSONPathRoot - Represents $ in JSON path expressions */ declare type JSONPathRoot = null; /** * JSONPathScript */ declare type JSONPathScript = { this: Expression; }; /** * JSONPathSelector */ declare type JSONPathSelector = { this: Expression; }; /** * JSONPathSlice */ declare type JSONPathSlice = { start: Expression | null; end: Expression | null; step: Expression | null; }; /** * JSONPathSubscript */ declare type JSONPathSubscript = { this: Expression; }; /** * JSONPathUnion */ declare type JSONPathUnion = { expressions: Array; }; /** * JSONRemove */ declare type JSONRemove = { this: Expression; expressions: Array; }; /** * JSONSchema */ declare type JSONSchema = { expressions: Array; }; /** * JSONSet */ declare type JSONSet = { this: Expression; expressions: Array; }; /** * JSONStripNulls */ declare type JSONStripNulls = { this: Expression; expression: Expression | null; include_arrays: Expression | null; remove_empty: Expression | null; }; /** * JSONTable */ declare type JSONTable = { this: Expression; schema: Expression | null; path: Expression | null; error_handling: Expression | null; empty_handling: Expression | null; }; /** * JSONType */ declare type JSONType = { this: Expression; expression: Expression | null; }; /** * JSON unique keys constraint variants */ declare type JsonUniqueKeys = "With" | "Without" | "Shorthand"; /** * JSONValue */ declare type JSONValue = { this: Expression; path: Expression | null; returning: Expression | null; on_condition: Expression | null; }; /** * JSONValueArray */ declare type JSONValueArray = { this: Expression; expression: Expression | null; }; /** * Oracle KEEP clause for aggregate functions * Syntax: aggregate_function KEEP (DENSE_RANK FIRST|LAST ORDER BY column [ASC|DESC]) */ declare type Keep = { /** * true = FIRST, false = LAST */ first: boolean; /** * ORDER BY clause inside KEEP */ order_by: Array; }; /** * KILL statement (MySQL/MariaDB) * KILL [CONNECTION | QUERY] */ declare type Kill = { /** * The target (process ID or connection ID) */ this: Expression; /** * Optional kind: "CONNECTION" or "QUERY" */ kind: string | null; }; /** * Lambda expression */ declare type LambdaExpr = { parameters: Array; body: Expression; /** * True if using DuckDB's LAMBDA x : expr syntax (vs x -> expr) */ colon: boolean; /** * Optional type annotations for parameters (Snowflake: a int -> a + 1) * Maps parameter index to data type */ parameter_types: Array; }; /** * LanguageProperty */ declare type LanguageProperty = { this: Expression; }; /** * LAST_DAY function with optional date part (for BigQuery granularity like WEEK(SUNDAY)) */ declare type LastDayFunc = { this: Expression; /** * Optional date part for granularity (e.g., MONTH, YEAR, WEEK(SUNDAY)) */ unit?: DateTimeField | null; }; /** * Lateral */ declare type Lateral = { this: Expression; view: Expression | null; outer: Expression | null; alias: string | null; /** * Whether the alias was originally quoted (backtick/double-quote) */ alias_quoted?: boolean; cross_apply: Expression | null; ordinality: Expression | null; /** * Column aliases for the lateral expression (e.g., LATERAL func() AS alias(col1, col2)) */ column_aliases?: Array; }; /** * LATERAL VIEW clause (Hive/Spark) * Used for unnesting arrays/maps with EXPLODE, POSEXPLODE, etc. */ declare type LateralView = { /** * The table-generating function (EXPLODE, POSEXPLODE, etc.) */ this: Expression; /** * Table alias for the generated table */ table_alias: Identifier | null; /** * Column aliases for the generated columns */ column_aliases: Array; /** * OUTER keyword - preserve nulls when input is empty/null */ outer: boolean; }; /** * LEAD / LAG function */ declare type LeadLagFunc = { this: Expression; offset: Expression | null; default: Expression | null; /** * None = not specified, Some(true) = IGNORE NULLS, Some(false) = RESPECT NULLS */ ignore_nulls?: boolean | null; }; export declare function least(...exprs: ExprInput[]): Expr; /** * LEFT/RIGHT function */ declare type LeftRightFunc = { this: Expression; length: Expression; }; declare function length_2(expr: ExprInput): Expr; export { length_2 as length } /** * LIKE/ILIKE operation with optional ESCAPE clause and quantifier (ANY/ALL) */ declare type LikeOp = { left: Expression; right: Expression; /** * ESCAPE character/expression */ escape: Expression | null; /** * Quantifier: ANY, ALL, or SOME */ quantifier: string | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Action for LIKE clause options */ declare type LikeOptionAction = "Including" | "Excluding"; /** * LikeProperty */ declare type LikeProperty = { this: Expression; expressions: Array; }; /** * Represent a LIMIT clause that restricts the number of returned rows. */ declare type Limit = { /** * The limit count expression. */ this: Expression; /** * Whether PERCENT modifier is present (DuckDB: LIMIT 10 PERCENT) */ percent?: boolean; /** * Comments from before the LIMIT keyword (emitted after the limit value) */ comments?: Array; }; /** * LimitOptions */ declare type LimitOptions = { percent: Expression | null; rows: Expression | null; with_ties: Expression | null; }; /** * Trace the lineage of a column through a SQL query. * * @param column - Column name to trace (e.g. "id", "users.name") * @param sql - SQL string to analyze * @param dialect - Dialect for parsing (default: 'generic') * @param trimSelects - Trim SELECT to only target column (default: false) * * @example * ```typescript * const result = lineage("a", "SELECT a FROM t"); * // result.lineage.name === "a" * // result.lineage.downstream[0].name === "t.a" * ``` */ export declare function lineage(column: string, sql: string, dialect?: string, trimSelects?: boolean): LineageResult; /** A node in the column lineage tree */ export declare interface LineageNode { name: string; expression: Expression; source: Expression; downstream: LineageNode[]; source_name: string; source_kind: LineageSourceKind; source_alias?: string; reference_node_name: string; } /** Result from lineage analysis */ export declare interface LineageResult { success: boolean; lineage?: LineageNode; error?: string; } export declare type LineageSourceKind = 'root' | 'table' | 'derived_table' | 'cte' | 'virtual' | 'unknown'; /** * Trace the lineage of a column through a SQL query using schema metadata. * * When a schema is provided, columns are fully qualified and type-annotated. * Each `LineageNode.expression` will have its `inferred_type` field populated * with the resolved SQL data type. Use `ast.getInferredType(node.expression)` * to read it. * * @param column - Column name to trace * @param sql - SQL string to analyze * @param schema - ValidationSchema-compatible schema object * @param dialect - Dialect for parsing/qualification (default: 'generic') * @param trimSelects - Trim SELECT to only target column (default: false) * * @example * ```typescript * import { lineageWithSchema, ast } from '@polyglot-sql/sdk'; * * const result = lineageWithSchema("name", "SELECT name FROM users", { * tables: { users: { name: "TEXT", id: "INT" } } * }); * * if (result.success) { * const dt = ast.getInferredType(result.lineage!.expression); * // dt => { data_type: "text" } * } * ``` */ export declare function lineageWithSchema(column: string, sql: string, schema: Schema, dialect?: string, trimSelects?: boolean): LineageResult; /** * List */ declare type List = { expressions: Array; }; /** * LISTAGG function (Oracle style) */ declare type ListAggFunc = { this: Expression; separator: Expression | null; on_overflow: ListAggOverflow | null; order_by: Array | null; distinct: boolean; filter: Expression | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * LISTAGG ON OVERFLOW behavior */ declare type ListAggOverflow = "Error" | { "Truncate": { filler: Expression | null; with_count: boolean; }; }; /** Create a literal value (string, number, boolean, or null). */ export declare function lit(value: string | number | boolean | null): Expr; /** * Represent a SQL literal value. * * Numeric values are stored as their original text representation (not parsed * to `i64`/`f64`) so that precision, trailing zeros, and hex notation are * preserved across round-trips. * * Dialect-specific literal forms (triple-quoted strings, dollar-quoted * strings, raw strings, etc.) each have a dedicated variant so that the * generator can emit them with the correct syntax. */ declare type Literal = { "literal_type": "string"; "value": string; } | { "literal_type": "number"; "value": string; } | { "literal_type": "hex_string"; "value": string; } | { "literal_type": "hex_number"; "value": string; } | { "literal_type": "bit_string"; "value": string; } | { "literal_type": "byte_string"; "value": string; } | { "literal_type": "national_string"; "value": string; } | { "literal_type": "date"; "value": string; } | { "literal_type": "time"; "value": string; } | { "literal_type": "timestamp"; "value": string; } | { "literal_type": "datetime"; "value": string; } | { "literal_type": "triple_quoted_string"; "value": [string, string]; } | { "literal_type": "escape_string"; "value": string; } | { "literal_type": "dollar_string"; "value": string; } | { "literal_type": "raw_string"; "value": string; }; /** * Union of all literal expression types */ declare type LiteralExpression = ExpressionByType<'literal'> | ExpressionByType<'boolean'>; export declare function ln(expr: ExprInput): Expr; /** * LOAD DATA statement (Hive) */ declare type LoadData = { /** * LOCAL keyword - load from local filesystem */ local: boolean; /** * The path to load data from (INPATH value) */ inpath: string; /** * Whether to overwrite existing data */ overwrite: boolean; /** * The target table */ table: Expression; /** * Optional PARTITION clause with key-value pairs */ partition: Array<[Identifier, Expression]>; /** * Optional INPUTFORMAT clause */ input_format: string | null; /** * Optional SERDE clause */ serde: string | null; }; /** * Localtime */ declare type Localtime = { this: Expression | null; }; /** * Localtimestamp */ declare type Localtimestamp = { this: Expression | null; }; /** * LocationProperty */ declare type LocationProperty = { this: Expression; }; /** * Lock */ declare type Lock_2 = { update: Expression | null; expressions: Array; wait: Expression | null; key: Expression | null; }; /** * LockingProperty */ declare type LockingProperty = { this: Expression | null; kind: string; for_or_in: Expression | null; lock_type: Expression | null; override_: Expression | null; }; /** * LockingStatement */ declare type LockingStatement = { this: Expression; expression: Expression; }; /** * LockProperty */ declare type LockProperty = { this: Expression; }; /** * LOG function */ declare type LogFunc = { this: Expression; base: Expression | null; }; /** * Union of all logical operator types */ declare type LogicalExpression = ExpressionByType<'and'> | ExpressionByType<'or'> | ExpressionByType<'not'>; /** * LogProperty */ declare type LogProperty = { no: Expression | null; }; export declare function lower(expr: ExprInput): Expr; export declare function ltrim(expr: ExprInput): Expr; /** * MAKE_DATE function */ declare type MakeDateFunc = { year: Expression; month: Expression; day: Expression; }; /** * Create an Expression from a variant key and inner data. * * @example * ```typescript * const expr = makeExpr('literal', { literal_type: 'number', value: '42' }); * ``` */ declare function makeExpr(type: string, data: unknown): Expression; /** * MakeInterval */ declare type MakeInterval = { year: Expression | null; month: Expression | null; week: Expression | null; day: Expression | null; hour: Expression | null; minute: Expression | null; second: Expression | null; }; /** * MAKE_TIMESTAMP function */ declare type MakeTimestampFunc = { year: Expression; month: Expression; day: Expression; hour: Expression; minute: Expression; second: Expression; timezone: Expression | null; }; /** * ManhattanDistance */ declare type ManhattanDistance = { this: Expression; expression: Expression; }; /** * Map */ declare type Map_2 = { keys: Array; values: Array; }; /** * MapCat */ declare type MapCat = { this: Expression; expression: Expression; }; /** * MAP constructor */ declare type MapConstructor_2 = { keys: Array; values: Array; /** * Whether curly brace syntax was used (`{'a': 1}`) vs MAP function (`MAP(...)`) */ curly_brace_syntax: boolean; /** * Whether MAP keyword was present (`MAP {'a': 1}`) vs bare curly braces (`{'a': 1}`) */ with_map_keyword: boolean; }; /** * MapDelete */ declare type MapDelete = { this: Expression; expressions: Array; }; /** * MapInsert */ declare type MapInsert = { this: Expression; key: Expression | null; value: Expression | null; update_flag: Expression | null; }; /** * MapPick */ declare type MapPick = { this: Expression; expressions: Array; }; /** * MaskingPolicyColumnConstraint */ declare type MaskingPolicyColumnConstraint = { this: Expression; expressions: Array; }; /** * MatchAgainst */ declare type MatchAgainst = { this: Expression; expressions: Array; modifier: Expression | null; }; /** * MATCH_RECOGNIZE clause for row pattern matching (Oracle/Snowflake/Presto/Trino) */ declare type MatchRecognize = { /** * Source table/expression */ this: Expression | null; /** * PARTITION BY expressions */ partition_by: Array | null; /** * ORDER BY expressions */ order_by: Array | null; /** * MEASURES definitions */ measures: Array | null; /** * Row semantics (ONE ROW PER MATCH, ALL ROWS PER MATCH, etc.) */ rows: MatchRecognizeRows | null; /** * AFTER MATCH SKIP behavior */ after: MatchRecognizeAfter | null; /** * PATTERN definition (stored as raw string for complex regex patterns) */ pattern: string | null; /** * DEFINE clauses (pattern variable definitions) */ define: Array<[Identifier, Expression]> | null; /** * Optional alias for the result */ alias: Identifier | null; /** * Whether AS keyword was explicitly present before alias */ alias_explicit_as?: boolean; }; /** * AFTER MATCH SKIP behavior */ declare type MatchRecognizeAfter = "PastLastRow" | "ToNextRow" | { "ToFirst": Identifier; } | { "ToLast": Identifier; }; /** * MEASURES expression with optional RUNNING/FINAL semantics */ declare type MatchRecognizeMeasure = { /** * The measure expression */ this: Expression; /** * RUNNING or FINAL semantics (Snowflake-specific) */ window_frame: MatchRecognizeSemantics | null; }; /** * Row output semantics for MATCH_RECOGNIZE */ declare type MatchRecognizeRows = "OneRowPerMatch" | "AllRowsPerMatch" | "AllRowsPerMatchShowEmptyMatches" | "AllRowsPerMatchOmitEmptyMatches" | "AllRowsPerMatchWithUnmatchedRows"; /** * Semantics for MEASURES in MATCH_RECOGNIZE */ declare type MatchRecognizeSemantics = "Running" | "Final"; /** * MATCH type for foreign keys */ declare type MatchType = "Full" | "Partial" | "Simple"; /** * MaterializedProperty */ declare type MaterializedProperty = { this: Expression | null; }; export declare function max(expr: ExprInput): Expr; /** * MD5Digest */ declare type MD5Digest = { this: Expression; expressions: Array; }; /** * Merge */ declare type Merge = { this: Expression; using: Expression; on: Expression | null; using_cond: Expression | null; whens: Expression | null; with_: Expression | null; returning: Expression | null; }; /** * MergeBlockRatioProperty */ declare type MergeBlockRatioProperty = { this: Expression | null; no: Expression | null; default: Expression | null; percent: Expression | null; }; /** * Fluent builder for MERGE INTO statements. * * @example * ```typescript * const sql = mergeInto('target') * .using('source', col('target.id').eq(col('source.id'))) * .whenMatchedUpdate({ name: col('source.name') }) * .whenNotMatchedInsert(['id', 'name'], [col('source.id'), col('source.name')]) * .toSql(); * ``` */ export declare class MergeBuilder { /* Excluded from this release type: _w */ constructor(target: string); /** Set the source table and ON condition. */ using(source: string, on: ExprInput): this; /** Add a WHEN MATCHED THEN UPDATE SET clause. */ whenMatchedUpdate(assignments: Record): this; /** Add a WHEN MATCHED THEN DELETE clause. */ whenMatchedDelete(): this; /** Add a WHEN NOT MATCHED THEN INSERT clause. */ whenNotMatchedInsert(columns: string[], values: ExprInput[]): this; /** Generate SQL string. Defaults to generic dialect. */ toSql(dialect?: string): string; /** Return the Expression AST as a plain JS object. */ build(): any; /** Free the underlying WASM handle. */ free(): void; } /** Create a MergeBuilder for the given target table. */ export declare function mergeInto(target: string): MergeBuilder; /** * MergeTreeTTL */ declare type MergeTreeTTL = { expressions: Array; where_: Expression | null; group: Expression | null; aggregates: Expression | null; }; /** * MergeTreeTTLAction */ declare type MergeTreeTTLAction = { this: Expression; delete: Expression | null; recompress: Expression | null; to_disk: Expression | null; to_volume: Expression | null; }; /** * Method call (expr.method(args)) */ declare type MethodCall = { this: Expression; method: Identifier; args: Array; }; export declare function min(expr: ExprInput): Expr; /** * Minhash */ declare type Minhash = { this: Expression; expressions: Array; }; /** * MLForecast */ declare type MLForecast = { this: Expression; expression: Expression | null; params_struct: Expression | null; }; /** * MLTranslate */ declare type MLTranslate = { this: Expression; expression: Expression; params_struct: Expression | null; }; /** * ModelAttribute */ declare type ModelAttribute = { this: Expression; expression: Expression; }; /** * Monthname */ declare type Monthname = { this: Expression; abbreviated: Expression | null; }; /** * MultitableInserts */ declare type MultitableInserts = { expressions: Array; kind: string; source: Expression | null; /** * Leading comments before the statement */ leading_comments: Array; /** * OVERWRITE modifier (Snowflake: INSERT OVERWRITE ALL) */ overwrite?: boolean; }; /** * Separator style for named arguments */ declare type NamedArgSeparator = "DArrow" | "ColonEq" | "Eq"; /** * Named argument in function call: name => value or name := value */ declare type NamedArgument = { name: Identifier; value: Expression; /** * The separator used: `=>`, `:=`, or `=` */ separator: NamedArgSeparator; }; /** * NAMED_STRUCT function */ declare type NamedStructFunc = { pairs: Array<[Expression, Expression]>; }; /** * Named window definition (WINDOW w AS (...)) */ declare type NamedWindow = { name: Identifier; spec: Over; }; /** * NextValueFor */ declare type NextValueFor = { this: Expression; order: Expression | null; }; /** * Count the total number of nodes in the AST (via WASM) */ declare function nodeCount(node: Expression): number; /** * Path to a node in the AST */ declare interface NodePath { node: Expression; parent: Expression | null; key: string | null; index: number | null; ancestors: Expression[]; } /** * Predicate function for finding nodes */ declare type NodePredicate = (node: Expression, parent: Expression | null) => boolean; /** * Normal */ declare type Normal = { this: Expression; stddev: Expression | null; gen: Expression | null; }; /** * Normalize */ declare type Normalize = { this: Expression; form: Expression | null; is_casefold: Expression | null; }; /** Create a NOT expression. */ export declare function not(expr: ExprInput): Expr; /** * NotNullColumnConstraint */ declare type NotNullColumnConstraint = { allow_null: Expression | null; }; /** * NTH_VALUE function */ declare type NthValueFunc = { this: Expression; offset: Expression; /** * None = not specified, Some(true) = IGNORE NULLS, Some(false) = RESPECT NULLS */ ignore_nulls?: boolean | null; /** * Snowflake FROM FIRST / FROM LAST clause * None = not specified, Some(true) = FROM FIRST, Some(false) = FROM LAST */ from_first?: boolean | null; }; /** * Ntile */ declare type Ntile = { this: Expression | null; }; /** * NTILE function (DuckDB allows ORDER BY inside) */ declare type NTileFunc = { /** * num_buckets is optional to support Databricks NTILE() without arguments */ num_buckets?: Expression | null; /** * DuckDB: NTILE(n ORDER BY col) - order by inside function */ order_by?: Array | null; }; /** * NULL literal */ declare type Null = null; /** * Nullif */ declare type Nullif = { this: Expression; expression: Expression; }; export declare function nullIf(expr1: ExprInput, expr2: ExprInput): Expr; /** * NumberToStr */ declare type NumberToStr = { this: Expression; format: string; culture: Expression | null; }; /** * NVL2 function */ declare type Nvl2Func = { this: Expression; true_value: Expression; false_value: Expression; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * ObjectAgg */ declare type ObjectAgg = { this: Expression; expression: Expression; }; /** * ObjectIdentifier */ declare type ObjectIdentifier = { this: Expression; }; /** * ObjectInsert */ declare type ObjectInsert = { this: Expression; key: Expression | null; value: Expression | null; update_flag: Expression | null; }; /** * OFFSET clause */ declare type Offset = { this: Expression; /** * Whether ROW/ROWS keyword was used (SQL standard syntax) */ rows?: boolean | null; }; /** * OnCluster */ declare type OnCluster = { this: Expression; }; /** * ON COMMIT behavior for temporary tables */ declare type OnCommit = "PreserveRows" | "DeleteRows"; /** * OnCommitProperty */ declare type OnCommitProperty = { delete: Expression | null; }; /** * OnCondition */ declare type OnCondition = { error: Expression | null; empty: Expression | null; null: Expression | null; }; /** * OnConflict */ declare type OnConflict = { duplicate: Expression | null; expressions: Array; action: Expression | null; conflict_keys: Expression | null; index_predicate: Expression | null; constraint: Expression | null; where_: Expression | null; }; /** * OnProperty */ declare type OnProperty = { this: Expression; }; /** * Opclass */ declare type Opclass = { this: Expression; expression: Expression; }; /** * OpenJSON */ declare type OpenJSON = { this: Expression; path: Expression | null; expressions: Array; }; /** * OpenJSONColumnDef */ declare type OpenJSONColumnDef = { this: Expression; kind: string; path: Expression | null; as_json: Expression | null; /** * The parsed data type for proper generation */ data_type?: DataType | null; }; /** * Build a standalone OpenLineage columnLineage facet with input/output datasets. */ export declare function openLineageColumnLineage(sql: string, options: OpenLineageOptions): OpenLineageColumnLineageResult; export declare interface OpenLineageColumnLineageFacet { _producer: string; _schemaURL: string; fields: Record; } export declare interface OpenLineageColumnLineageField { inputFields: OpenLineageInputField[]; } export declare interface OpenLineageColumnLineageResult { success: boolean; facet?: OpenLineageColumnLineageFacet; inputs?: OpenLineageDataset[]; outputs?: OpenLineageDataset[]; warnings: OpenLineageWarning[]; error?: string; } export declare interface OpenLineageDataset { namespace: string; name: string; facets?: Record; } export declare interface OpenLineageDatasetId { namespace: string; name: string; } export declare interface OpenLineageEventResult { success: boolean; event?: Record; warnings: OpenLineageWarning[]; error?: string; } export declare interface OpenLineageInputField { namespace: string; name: string; field: string; transformations?: OpenLineageTransformation[]; } /** * Build an OpenLineage JobEvent payload. This does not send the event. */ export declare function openLineageJobEvent(sql: string, options: OpenLineageOptions): OpenLineageEventResult; export declare interface OpenLineageOptions { dialect?: string; producer: string; datasetNamespace?: string; datasetMappings?: Record; outputDataset?: OpenLineageDatasetId; schema?: Schema; jobNamespace?: string; jobName?: string; eventTime?: string; runId?: string; eventType?: OpenLineageRunEventType; } /** * Build an OpenLineage RunEvent payload. This does not send the event. */ export declare function openLineageRunEvent(sql: string, options: OpenLineageOptions): OpenLineageEventResult; export declare type OpenLineageRunEventType = 'START' | 'RUNNING' | 'COMPLETE' | 'ABORT' | 'FAIL' | 'OTHER'; export declare interface OpenLineageTransformation { type: 'DIRECT' | string; subtype: 'IDENTITY' | 'TRANSFORMATION' | 'AGGREGATION' | string; description?: string; masking?: boolean; } export declare interface OpenLineageWarning { code: string; message: string; } /** * Operator */ declare type Operator = { this: Expression; operator: Expression | null; expression: Expression; /** * Comments between OPERATOR() and the RHS expression */ comments?: Array; }; /** * Key/value pair in a BigQuery OPTIONS (...) clause. */ declare type OptionEntry = { key: Identifier; value: Expression; }; /** * Typed BigQuery OPTIONS (...) property for CREATE TABLE and related DDL. */ declare type OptionsProperty = { entries: Array; }; /** Chain multiple conditions with OR. */ export declare function or(...conditions: ExprInput[]): Expr; /** * Represent an ORDER BY clause containing one or more sort specifications. */ declare type OrderBy = { /** * The sort specifications, each with direction and null ordering. */ expressions: Array; /** * Whether this is ORDER SIBLINGS BY (Oracle hierarchical queries) */ siblings?: boolean; /** * Leading comments that appeared before the ORDER BY keyword */ comments?: Array; }; /** * Represent an expression with sort direction and null ordering. * * Used inside ORDER BY clauses, window frame ORDER BY, and index definitions. * When `desc` is false the sort is ascending. The `nulls_first` field * controls the NULLS FIRST / NULLS LAST modifier; `None` means unspecified * (database default). */ declare type Ordered = { /** * The expression to sort by. */ this: Expression; /** * Whether the sort direction is descending (true) or ascending (false). */ desc: boolean; /** * `Some(true)` = NULLS FIRST, `Some(false)` = NULLS LAST, `None` = unspecified. */ nulls_first: boolean | null; /** * Whether ASC was explicitly written (not just implied) */ explicit_asc: boolean; /** * ClickHouse WITH FILL clause */ with_fill?: WithFill | null; }; /** * Input type for order specifications */ declare type OrderInput = string | ExpressionByType<'ordered'> | { expr: Expression; desc?: boolean; nullsFirst?: boolean; }; /** * OUTPUT clause (TSQL) - used in INSERT, UPDATE, DELETE */ declare type OutputClause = { /** * Columns/expressions to output */ columns: Array; /** * Optional INTO target table or table variable */ into_table: Expression | null; }; /** * OutputModelProperty */ declare type OutputModelProperty = { this: Expression; }; /** * OVER clause */ declare type Over = { /** * Named window reference (e.g., OVER w or OVER (w ORDER BY x)) */ window_name: Identifier | null; partition_by: Array; order_by: Array; frame: WindowFrame | null; alias: Identifier | null; }; /** * OverflowTruncateBehavior */ declare type OverflowTruncateBehavior = { this: Expression | null; with_count: Expression | null; }; /** * OVERLAPS expression * Supports two forms: * 1. Simple binary: a OVERLAPS b (this, expression are set) * 2. Full ANSI: (a, b) OVERLAPS (c, d) (left_start, left_end, right_start, right_end are set) */ declare type OverlapsExpr = { /** * Left operand for simple binary form */ this: Expression | null; /** * Right operand for simple binary form */ expression: Expression | null; /** * Left range start for full ANSI form */ left_start: Expression | null; /** * Left range end for full ANSI form */ left_end: Expression | null; /** * Right range start for full ANSI form */ right_start: Expression | null; /** * Right range end for full ANSI form */ right_end: Expression | null; }; /** * OVERLAY function - OVERLAY(string PLACING replacement FROM position [FOR length]) */ declare type OverlayFunc = { this: Expression; replacement: Expression; from: Expression; length: Expression | null; }; /** * Pad */ declare type Pad = { this: Expression; expression: Expression; fill_pattern: Expression | null; is_left: Expression | null; }; /** * LPAD/RPAD function */ declare type PadFunc = { this: Expression; length: Expression; fill: Expression | null; }; /** * Parameter (parameterized queries) */ declare type Parameter = { name: string | null; index: number | null; style: ParameterStyle; /** * Whether the name was quoted (e.g., @"x" vs @x) */ quoted: boolean; /** * Whether the name was string-quoted with single quotes (e.g., @'foo') */ string_quoted: boolean; /** * Optional secondary expression for ${kind:name} syntax (Hive hiveconf variables) */ expression: string | null; }; /** * ParameterizedAgg */ declare type ParameterizedAgg = { this: Expression; expressions: Array; params: Array; }; /** * Parameter mode (IN, OUT, INOUT, VARIADIC) */ declare type ParameterMode = "In" | "Out" | "InOut" | "Variadic"; /** * Parameter placeholder styles */ declare type ParameterStyle = "Question" | "Dollar" | "DollarBrace" | "Brace" | "Colon" | "At" | "DoubleAt" | "DoubleDollar" | "Percent"; /** * Represent an explicit parenthesized expression for grouping precedence. * * Preserves user-written parentheses so that `(a + b) * c` round-trips * correctly instead of being flattened to `a + b * c`. */ declare type Paren = { /** * The inner expression wrapped by parentheses. */ this: Expression; trailing_comments: Array; }; /** * Parse SQL into an Abstract Syntax Tree (AST). * * @param sql - The SQL string to parse * @param dialect - The dialect to use for parsing * @returns The parsed AST * * @example * ```typescript * const result = parse("SELECT a, b FROM t", Dialect.PostgreSQL); * console.log(result.ast); * ``` */ export declare function parse(sql: string, dialect?: Dialect): ParseResult; /** * Parse a standalone SQL data type. * * @param sql - The data type string to parse * @param dialect - The dialect to use * @returns The parsed DataType AST node * * @example * ```typescript * const result = parseDataType("DECIMAL(10, 2)", Dialect.DuckDB); * console.log(result.dataType); * ``` */ export declare function parseDataType(sql: string, dialect?: Dialect): DataTypeResult; /** * ParseDatetime */ declare type ParseDatetime = { this: Expression; format: string | null; zone: Expression | null; }; /** * ParseIp */ declare type ParseIp = { this: Expression; type_: Expression | null; permissive: Expression | null; }; /** * ParseJSON */ declare type ParseJSON = { this: Expression; expression: Expression | null; safe: Expression | null; }; /** * Result of a parse operation */ export declare interface ParseResult { success: boolean; ast?: any; error?: string; /** 1-based line number where the error occurred */ errorLine?: number; /** 1-based column number where the error occurred */ errorColumn?: number; /** Start byte offset of the error range */ errorStart?: number; /** End byte offset of the error range (exclusive) */ errorEnd?: number; } /** * ParseTime */ declare type ParseTime = { this: Expression; format: string; }; /** * ParseUrl */ declare type ParseUrl = { this: Expression; part_to_extract: Expression | null; key: Expression | null; permissive: Expression | null; }; /** * Partition - represents PARTITION/SUBPARTITION clause */ declare type Partition = { expressions: Array; subpartition: boolean; }; /** * PartitionBoundSpec */ declare type PartitionBoundSpec = { this: Expression | null; expression: Expression | null; from_expressions: Expression | null; to_expressions: Expression | null; }; /** * PartitionByListProperty */ declare type PartitionByListProperty = { partition_expressions: Expression | null; create_expressions: Expression | null; }; /** * BigQuery PARTITION BY property in CREATE TABLE statements. */ declare type PartitionByProperty = { expressions: Array; }; /** * PartitionByRangeProperty */ declare type PartitionByRangeProperty = { partition_expressions: Expression | null; create_expressions: Expression | null; }; /** * PartitionByRangePropertyDynamic */ declare type PartitionByRangePropertyDynamic = { this: Expression | null; start: Expression | null; /** * Use START/END/EVERY keywords (StarRocks) instead of FROM/TO/INTERVAL (Doris) */ use_start_end: boolean; end: Expression | null; every: Expression | null; }; /** * PartitionByTruncate */ declare type PartitionByTruncate = { this: Expression; expression: Expression; }; /** * PartitionedByBucket */ declare type PartitionedByBucket = { this: Expression; expression: Expression; }; /** * PartitionedByProperty */ declare type PartitionedByProperty = { this: Expression; }; /** * PartitionedOfProperty */ declare type PartitionedOfProperty = { this: Expression; expression: Expression; }; /** * PartitionList */ declare type PartitionList = { this: Expression; expressions: Array; }; /** * PartitionRange */ declare type PartitionRange = { this: Expression; expression: Expression | null; expressions: Array; }; /** * PathColumnConstraint - PATH 'xpath' for XMLTABLE/JSON_TABLE columns */ declare type PathColumnConstraint = { this: Expression; }; /** * PERCENTILE_CONT / PERCENTILE_DISC function */ declare type PercentileFunc = { this: Expression; percentile: Expression; order_by: Array | null; filter: Expression | null; }; /** * PERCENT_RANK function (DuckDB allows ORDER BY inside, Oracle allows hypothetical args with WITHIN GROUP) */ declare type PercentRank = { /** * DuckDB: PERCENT_RANK(ORDER BY col) - order by inside function */ order_by?: Array | null; /** * Oracle hypothetical rank: PERCENT_RANK(val1, val2, ...) WITHIN GROUP (ORDER BY ...) */ args?: Array; }; /** * PeriodForSystemTimeConstraint */ declare type PeriodForSystemTimeConstraint = { this: Expression; expression: Expression; }; /** * PI function (no arguments) */ declare type Pi = null; /** * Pipe operator expression: query |> transform * * Used in DataFusion and BigQuery pipe syntax: * FROM t |> WHERE x > 1 |> SELECT x, y |> ORDER BY x |> LIMIT 10 */ declare type PipeOperator = { /** * The input query/expression (left side of |>) */ this: Expression; /** * The piped operation (right side of |>) */ expression: Expression; }; /** * PIVOT operation - supports both standard and DuckDB simplified syntax * * Standard syntax (in FROM clause): * table PIVOT(agg_func [AS alias], ... FOR column IN (value [AS alias], ...)) * table UNPIVOT(value_col FOR name_col IN (col1, col2, ...)) * * DuckDB simplified syntax (statement-level): * PIVOT table ON columns [IN (...)] USING agg_func [AS alias], ... [GROUP BY ...] * UNPIVOT table ON columns INTO NAME name_col VALUE val_col */ declare type Pivot = { /** * Source table/expression */ this: Expression; /** * For standard PIVOT: the aggregation function(s) (first is primary) * For DuckDB simplified: unused (use `using` instead) */ expressions: Array; /** * For standard PIVOT: the FOR...IN clause(s) as In expressions */ fields: Array; /** * For standard: unused. For DuckDB simplified: the USING aggregation functions */ using: Array; /** * GROUP BY clause (used in both standard inside-parens and DuckDB simplified) */ group: Expression | null; /** * Whether this is an UNPIVOT (vs PIVOT) */ unpivot: boolean; /** * For DuckDB UNPIVOT: INTO NAME col VALUE col */ into: Expression | null; /** * Optional alias */ alias: Identifier | null; /** * Optional output column aliases from `PIVOT(...) AS alias(col1, col2, ...)` */ alias_columns?: Array; /** * Include/exclude nulls (for UNPIVOT) */ include_nulls: boolean | null; /** * Default on null value (Snowflake) */ default_on_null: Expression | null; /** * WITH clause (CTEs) */ with?: With | null; }; /** * PIVOT alias for aliasing pivot expressions * The alias can be an identifier or an expression (for Oracle/BigQuery string concatenation aliases) */ declare type PivotAlias = { this: Expression; alias: Expression; }; /** * PivotAny */ declare type PivotAny = { this: Expression | null; }; /** * Placeholder expression */ declare type Placeholder = { index: number | null; }; /** * Build an execution plan from a SQL query. * * @param sql - SQL string to plan * @param dialect - Dialect for parsing (default: 'generic') * * @example * ```typescript * const result = plan("SELECT x, SUM(y) FROM t GROUP BY x"); * // result.plan.root.kind === "aggregate" * // result.plan.leaves[0].kind === "scan" * ``` */ export declare function plan(sql: string, dialect?: string): PlanResult; export declare type PlanJoinType = 'inner' | 'left' | 'right' | 'full' | 'cross'; /** Result from planning a query */ export declare interface PlanResult { success: boolean; plan?: QueryPlan; error?: string; } /** A single step in the execution plan */ export declare interface PlanStep { name: string; kind: StepKind; projections: Expression[]; dependencies: PlanStep[]; aggregations: Expression[]; group_by: Expression[]; condition: Expression | null; order_by: Expression[]; limit: Expression | null; } /** * Main Polyglot class for object-oriented usage. */ export declare class Polyglot { private static instance; private constructor(); /** * Get or create the Polyglot instance. * The WASM module is automatically initialized on import. */ static getInstance(): Polyglot; /** * Transpile SQL from one dialect to another. * * @remarks * Per-dialect builds only support same-dialect and to/from Generic transpilation. * Use {@link Polyglot.getDialects} to check available dialects. */ transpile(sql: string, read: Dialect, write: Dialect, options?: TranspileOptions): TranspileResult; /** * Parse SQL into an AST. */ parse(sql: string, dialect?: Dialect): ParseResult; /** * Parse a standalone SQL data type. */ parseDataType(sql: string, dialect?: Dialect): DataTypeResult; /** * Tokenize SQL into a token stream. */ tokenize(sql: string, dialect?: Dialect): TokenizeResult; /** * Generate SQL from an AST. */ generate(ast: any, dialect?: Dialect): TranspileResult; /** * Generate SQL from a standalone DataType AST node. */ generateDataType(dataType: DataType, dialect?: Dialect): GenerateDataTypeResult; /** * Format SQL. */ format(sql: string, dialect?: Dialect): TranspileResult; /** * Format SQL with explicit guard limits. */ formatWithOptions(sql: string, dialect?: Dialect, options?: FormatOptions): TranspileResult; /** * Get supported dialects in this build. * Per-dialect builds return only `"generic"` and the selected dialect. */ getDialects(): string[]; /** * Get library version. */ getVersion(): string; /** * Parse SQL and annotate the AST with inferred type information. */ annotateTypes(sql: string, dialect?: Dialect, schema?: Schema): AnnotateTypesResult; /** * Return compact query analysis facts for a SELECT or set operation. */ analyzeQuery(sql: string, dialect: Dialect | string): QueryAnalysisResult; analyzeQuery(sql: string, options?: AnalyzeQueryOptions): QueryAnalysisResult; } /** * POSITION/INSTR function */ declare type PositionFunc = { substring: Expression; string: Expression; start: Expression | null; }; export declare function power(base: ExprInput, exp: ExprInput): Expr; /** * PRAGMA statement (SQLite) */ declare type Pragma = { /** * Optional schema prefix (e.g., "schema" in "schema.pragma_name") */ schema: Identifier | null; /** * The pragma name */ name: Identifier; /** * Optional value for assignment (PRAGMA name = value) */ value: Expression | null; /** * Optional arguments for function-style pragmas (PRAGMA name(arg)) */ args: Array; /** * Whether this pragma should be generated using assignment syntax. */ use_assignment_syntax: boolean; }; /** * Union of all predicate expression types */ declare type PredicateExpression = ExpressionByType<'in'> | ExpressionByType<'between'> | ExpressionByType<'is_null'> | ExpressionByType<'exists'> | ExpressionByType<'similar_to'> | ExpressionByType<'any'> | ExpressionByType<'all'> | ExpressionByType<'overlaps'>; /** * Predict */ declare type Predict = { this: Expression; expression: Expression; params_struct: Expression | null; }; /** * PREPARE statement (PostgreSQL/generic prepared statement definition) * Syntax: PREPARE name [(type, ...)] AS statement */ declare type PrepareStatement = { /** * The prepared statement name. */ name: Identifier; /** * Optional PostgreSQL parameter type list. */ parameter_types?: Array; /** * The statement to execute when the prepared statement is invoked. */ statement: Expression; }; /** * PreviousDay */ declare type PreviousDay = { this: Expression; expression: Expression; }; /** * PREWHERE clause (ClickHouse) - early filtering before WHERE */ declare type PreWhere = { this: Expression; }; /** * PrimaryKey */ declare type PrimaryKey = { this: Expression | null; expressions: Array; options: Array; include: Expression | null; }; /** * PrimaryKeyColumnConstraint */ declare type PrimaryKeyColumnConstraint = { desc: Expression | null; options: Array; }; /** * Oracle PRIOR expression - references parent row's value in CONNECT BY */ declare type Prior = { this: Expression; }; /** * A privilege with optional column list for GRANT/REVOKE * Examples: SELECT, UPDATE(col1, col2), ALL(col1, col2, col3) */ declare type Privilege = { /** * The privilege name (e.g., SELECT, INSERT, UPDATE, ALL) */ name: string; /** * Optional column list for column-level privileges (e.g., UPDATE(col1, col2)) */ columns?: Array; }; /** * ProjectionDef */ declare type ProjectionDef = { this: Expression; expression: Expression; }; export declare interface ProjectionFact { index: number; name?: string; isStar: boolean; starTable?: string; transformKind: TransformKind; transformFunction?: TransformFunctionFact; castType?: string; typeHint?: string; nullability: ProjectionNullability; upstream: ColumnReferenceFact[]; } export declare type ProjectionNullability = 'non_null' | 'nullable' | 'unknown'; /** * Properties */ declare type Properties = { expressions: Array; }; /** * Property */ declare type Property = { this: Expression; value: Expression | null; }; /** * Pseudocolumn expression (Oracle ROWNUM, ROWID, LEVEL, etc.) * These are special identifiers that should not be quoted */ declare type Pseudocolumn = { kind: PseudocolumnType; }; /** * Pseudocolumn type */ declare type PseudocolumnType = "Rownum" | "Rowid" | "Level" | "Sysdate" | "ObjectId" | "ObjectValue"; /** * PseudoType */ declare type PseudoType = { this: Expression; }; /** * PUT statement (Snowflake) */ declare type PutStmt = { /** * Source file path */ source: string; /** * Whether source was quoted in the original SQL */ source_quoted: boolean; /** * Target stage */ target: Expression; /** * PUT parameters */ params: Array; }; /** * Represent a QUALIFY clause for filtering on window function results. * * Supported by Snowflake, BigQuery, DuckDB, and Databricks. The predicate * typically references a window function (e.g. * `QUALIFY ROW_NUMBER() OVER (PARTITION BY id ORDER BY ts DESC) = 1`). */ declare type Qualify = { /** * The filter predicate over window function results. */ this: Expression; }; /** * Qualify unqualified column references with a table name (via WASM) * * @example * ```typescript * // Add table prefix to all unqualified columns * const newAst = qualifyColumns(ast, 'users'); * // col('id') => col('id', 'users') * ``` */ declare function qualifyColumns(node: Expression, tableName: string): Expression; /** * Qualify table references and optionally generate stable aliases (via WASM) * * @example * ```typescript * const newAst = qualifyTables(ast, { * canonicalizeTableAliases: true * }); * ``` */ declare function qualifyTables(node: Expression, options?: QualifyTablesOptions): Expression; declare interface QualifyTablesOptions { db?: string; catalog?: string; dialect?: string; canonicalizeTableAliases?: boolean; aliasUnaliasedTables?: boolean; aliasUnaliasedSubqueries?: boolean; aliasPrefix?: string; normalizeSetOperationSubqueries?: boolean; } /** * ANY / ALL quantified expression */ declare type QuantifiedExpr = { this: Expression; subquery: Expression; op: QuantifiedOp | null; }; /** * Comparison operator for quantified expressions */ declare type QuantifiedOp = "Eq" | "Neq" | "Lt" | "Lte" | "Gt" | "Gte"; /** * Quantile */ declare type Quantile = { this: Expression; quantile: Expression | null; }; export declare interface QueryAnalysis { shape: QueryShape; ctes: string[]; cteFacts: CteFact[]; projections: ProjectionFact[]; relations: RelationFact[]; baseTables: RelationFact[]; starProjections: StarProjectionFact[]; setOperations: SetOperationFact[]; } export declare interface QueryAnalysisResult { success: boolean; analysis?: QueryAnalysis; error?: string; } export declare type QueryAnalysisSourceKind = 'root' | 'table' | 'derived_table' | 'cte' | 'virtual' | 'unknown'; /** * QueryBand */ declare type QueryBand = { this: Expression; scope: Expression | null; update: Expression | null; }; /** * Union of all DML query expression types */ declare type QueryExpression = ExpressionByType<'select'> | ExpressionByType<'insert'> | ExpressionByType<'update'> | ExpressionByType<'delete'>; /** * QueryOption */ declare type QueryOption = { this: Expression; expression: Expression | null; }; /** Full query execution plan */ export declare interface QueryPlan { root: PlanStep; dag: Record; leaves: PlanStep[]; } export declare type QueryShape = 'select' | 'set_operation'; /** * QueryTransform */ declare type QueryTransform = { expressions: Array; command_script: Expression | null; schema: Expression | null; row_format_before: Expression | null; record_writer: Expression | null; row_format_after: Expression | null; record_reader: Expression | null; }; /** * RAND function (optional seed, or Teradata RANDOM(lower, upper)) */ declare type Rand = { seed: Expression | null; /** * Teradata RANDOM lower bound */ lower: Expression | null; /** * Teradata RANDOM upper bound */ upper: Expression | null; }; /** * Randn */ declare type Randn = { this: Expression | null; }; /** * RANDOM function (no arguments) */ declare type Random = null; /** * Randstr */ declare type Randstr = { this: Expression; generator: Expression | null; }; /** * RangeBucket */ declare type RangeBucket = { this: Expression; expression: Expression; }; /** * RangeN */ declare type RangeN = { this: Expression; expressions: Array; each: Expression | null; }; /** * RANK function (DuckDB allows ORDER BY inside, Oracle allows hypothetical args with WITHIN GROUP) */ declare type Rank = { /** * DuckDB: RANK(ORDER BY col) - order by inside function */ order_by?: Array | null; /** * Oracle hypothetical rank: RANK(val1, val2, ...) WITHIN GROUP (ORDER BY ...) */ args?: Array; }; export declare function rank(): Expr; /** * Raw/unparsed SQL */ declare type Raw = { sql: string; }; /** * ReadCSV */ declare type ReadCSV = { this: Expression; expressions: Array; }; /** * ReadParquet */ declare type ReadParquet = { expressions: Array; }; /** * RecursiveWithSearch */ declare type RecursiveWithSearch = { kind: string; this: Expression; expression: Expression; using: Expression | null; }; /** * Reduce */ declare type Reduce = { this: Expression; initial: Expression | null; merge: Expression | null; finish: Expression | null; }; /** * Reference */ declare type Reference = { this: Expression; expressions: Array; options: Array; }; export declare type ReferenceConfidence = 'resolved' | 'ambiguous' | 'unknown'; /** * Union of all reference expression types (identifiers, columns, tables) */ declare type ReferenceExpression = ExpressionByType<'identifier'> | ExpressionByType<'column'> | ExpressionByType<'table'> | ExpressionByType<'star'>; /** * Referential action for foreign keys */ declare type ReferentialAction = "Cascade" | "SetNull" | "SetDefault" | "Restrict" | "NoAction"; /** * Refresh */ declare type Refresh = { this: Expression; kind: string; }; /** * RefreshTriggerProperty - Doris REFRESH clause for materialized views * e.g., REFRESH COMPLETE ON MANUAL, REFRESH AUTO ON SCHEDULE EVERY 5 MINUTE */ declare type RefreshTriggerProperty = { /** * Method: COMPLETE or AUTO */ method: string; /** * Trigger kind: MANUAL, COMMIT, or SCHEDULE */ kind: string | null; /** * For SCHEDULE: EVERY n (the number) */ every: Expression | null; /** * For SCHEDULE: the time unit (MINUTE, HOUR, DAY, etc.) */ unit: string | null; /** * For SCHEDULE: STARTS 'datetime' */ starts: Expression | null; }; /** * RegexpCount */ declare type RegexpCount = { this: Expression; expression: Expression; position: Expression | null; parameters: Expression | null; }; /** * RegexpExtractAll */ declare type RegexpExtractAll = { this: Expression; expression: Expression; group: Expression | null; parameters: Expression | null; position: Expression | null; occurrence: Expression | null; }; /** * REGEXP_EXTRACT function */ declare type RegexpExtractFunc = { this: Expression; pattern: Expression; group: Expression | null; }; /** * RegexpFullMatch */ declare type RegexpFullMatch = { this: Expression; expression: Expression; options: Array; }; /** * REGEXP_LIKE function */ declare type RegexpFunc = { this: Expression; pattern: Expression; flags: Expression | null; }; /** * RegexpILike */ declare type RegexpILike = { this: Expression; expression: Expression; flag: Expression | null; }; /** * RegexpInstr */ declare type RegexpInstr = { this: Expression; expression: Expression; position: Expression | null; occurrence: Expression | null; option: Expression | null; parameters: Expression | null; group: Expression | null; }; /** * REGEXP_REPLACE function */ declare type RegexpReplaceFunc = { this: Expression; pattern: Expression; replacement: Expression; flags: Expression | null; }; /** * RegexpSplit */ declare type RegexpSplit = { this: Expression; expression: Expression; limit: Expression | null; }; /** * RegrAvgx */ declare type RegrAvgx = { this: Expression; expression: Expression; }; /** * RegrAvgy */ declare type RegrAvgy = { this: Expression; expression: Expression; }; /** * RegrCount */ declare type RegrCount = { this: Expression; expression: Expression; }; /** * RegrIntercept */ declare type RegrIntercept = { this: Expression; expression: Expression; }; /** * RegrR2 */ declare type RegrR2 = { this: Expression; expression: Expression; }; /** * RegrSlope */ declare type RegrSlope = { this: Expression; expression: Expression; }; /** * RegrSxx */ declare type RegrSxx = { this: Expression; expression: Expression; }; /** * RegrSxy */ declare type RegrSxy = { this: Expression; expression: Expression; }; /** * RegrSyy */ declare type RegrSyy = { this: Expression; expression: Expression; }; /** * RegrValx */ declare type RegrValx = { this: Expression; expression: Expression; }; /** * RegrValy */ declare type RegrValy = { this: Expression; expression: Expression; }; export declare interface RelationFact { name: string; alias?: string | null; kind: QueryAnalysisSourceKind; columns: string[]; catalog?: string | null; schema?: string | null; table?: string | null; } /** * RemoteWithConnectionModelProperty */ declare type RemoteWithConnectionModelProperty = { this: Expression; }; /** * Remove all nodes matching a predicate * Note: This can only remove nodes that are in arrays (like expressions in SELECT) * Removing required nodes will leave them unchanged */ declare function remove(node: Expression, predicate: NodePredicate): Expression; /** * Remove LIMIT and OFFSET clauses */ declare function removeLimitOffset(node: Expression): Expression; /** * Remove columns from a SELECT expression by predicate */ declare function removeSelectColumns(node: Expression, predicate: (col: Expression) => boolean): Expression; /** * Remove the WHERE clause from a SELECT (via WASM) */ declare function removeWhere(node: Expression): Expression; /** * RenameColumn */ declare type RenameColumn = { this: Expression; to: Expression | null; exists: boolean; }; /** * Rename columns in the AST (via WASM) * * @example * ```typescript * const newAst = renameColumns(ast, { * old_name: 'new_name', * another_old: 'another_new' * }); * ``` */ export declare function renameColumns(node: Expression, mapping: Record): Expression; /** * Rename tables in the AST (via WASM) * * @example * ```typescript * const newAst = renameTables(ast, { * old_table: 'new_table', * temp_users: 'users' * }); * ``` */ declare function renameTables(node: Expression, mapping: Record, options?: RenameTablesOptions): Expression; declare interface RenameTablesOptions { aliasRenamedTables?: boolean; preserveExistingAliases?: boolean; } /** * REPEAT function */ declare type RepeatFunc = { this: Expression; times: Expression; }; export declare function replace(expr: ExprInput, from: ExprInput, to: ExprInput): Expr; /** * Replace nodes of a specific type */ declare function replaceByType(node: Expression, type: string, replacement: Expression | ((node: Expression) => Expression)): Expression; /** * REPLACE function */ declare type ReplaceFunc = { this: Expression; old: Expression; new: Expression; }; /** * Replace nodes matching a predicate with a new node * * @example * ```typescript * // Replace all NULL literals with 0 * const newAst = replaceNodes( * ast, * (node) => getExprType(node) === 'null', * { literal: { literal_type: 'number', value: '0' } } as Expression * ); * ``` */ declare function replaceNodes(node: Expression, predicate: NodePredicate, replacement: Expression | ((node: Expression) => Expression)): Expression; /** * ReplacePartition */ declare type ReplacePartition = { expression: Expression; source: Expression | null; }; /** * Returning */ declare type Returning = { expressions: Array; into: Expression | null; }; /** * ReturnsProperty */ declare type ReturnsProperty = { this: Expression | null; is_table: Expression | null; table: Expression | null; null: Expression | null; }; export declare function reverse(expr: ExprInput): Expr; /** * REVOKE statement */ declare type Revoke = { /** * Privileges to revoke (e.g., SELECT, INSERT, UPDATE(col1, col2)) */ privileges: Array; /** * Object kind (TABLE, SCHEMA, FUNCTION, etc.) */ kind: string | null; /** * The object to revoke from */ securable: Identifier; /** * Function parameter types (for FUNCTION kind) */ function_params?: Array; /** * The grantees */ principals: Array; /** * GRANT OPTION FOR */ grant_option: boolean; /** * CASCADE */ cascade: boolean; /** * RESTRICT */ restrict: boolean; }; /** * Rollback */ declare type Rollback = { savepoint: Expression | null; this: Expression | null; }; /** * Rollup */ declare type Rollup = { expressions: Array; }; /** * RollupIndex - A single rollup index: name(col1, col2) */ declare type RollupIndex = { name: Identifier; expressions: Array; }; /** * RollupProperty - StarRocks ROLLUP (index_name(col1, col2), ...) */ declare type RollupProperty = { expressions: Array; }; export declare function round(expr: ExprInput, decimals?: ExprInput): Expr; /** * ROUND function */ declare type RoundFunc = { this: Expression; decimals: Expression | null; }; /** * ROW FORMAT clause for Hive/Spark */ declare type RowFormat = { delimited: boolean; fields_terminated_by: string | null; collection_items_terminated_by: string | null; map_keys_terminated_by: string | null; lines_terminated_by: string | null; null_defined_as: string | null; }; /** * RowFormatDelimitedProperty */ declare type RowFormatDelimitedProperty = { fields: Expression | null; escaped: Expression | null; collection_items: Expression | null; map_keys: Expression | null; lines: Expression | null; null: Expression | null; serde: Expression | null; }; /** * RowFormatProperty */ declare type RowFormatProperty = { this: Expression; }; /** * RowFormatSerdeProperty */ declare type RowFormatSerdeProperty = { this: Expression; serde_properties: Expression | null; }; /** * ROW_NUMBER function (no arguments) */ declare type RowNumber = null; export declare function rowNumber(): Expr; /** * RowsFrom - PostgreSQL ROWS FROM (func1(args) AS alias1(...), func2(args) AS alias2(...)) syntax * Used for set-returning functions with typed column definitions */ declare type RowsFrom = { /** * List of function expressions, each potentially with an alias and typed columns */ expressions: Array; /** * WITH ORDINALITY modifier */ ordinality: boolean; /** * Optional outer alias: ROWS FROM (...) AS alias(col1 type1, col2 type2) */ alias: Expression | null; }; export declare function rtrim(expr: ExprInput): Expr; /** * SafeAdd */ declare type SafeAdd = { this: Expression; expression: Expression; }; /** * SafeDivide */ declare type SafeDivide = { this: Expression; expression: Expression; }; /** * SafeMultiply */ declare type SafeMultiply = { this: Expression; expression: Expression; }; /** * SafeSubtract */ declare type SafeSubtract = { this: Expression; expression: Expression; }; /** * SAMPLE / TABLESAMPLE clause */ declare type Sample = { method: SampleMethod; size: Expression; seed: Expression | null; /** * ClickHouse OFFSET expression after SAMPLE size */ offset: Expression | null; /** * Whether the unit comes after the size (e.g., "100 ROWS" vs "ROW 100") */ unit_after_size: boolean; /** * Whether the keyword was SAMPLE (true) or TABLESAMPLE (false) */ use_sample_keyword: boolean; /** * Whether the method was explicitly specified (BERNOULLI, SYSTEM, etc.) */ explicit_method: boolean; /** * Whether the method keyword appeared before the size (TABLESAMPLE BERNOULLI (10)) */ method_before_size: boolean; /** * Whether SEED keyword was used (true) or REPEATABLE (false) */ use_seed_keyword: boolean; /** * BUCKET numerator for Hive bucket sampling (BUCKET 1 OUT OF 5) */ bucket_numerator: Expression | null; /** * BUCKET denominator (the 5 in BUCKET 1 OUT OF 5) */ bucket_denominator: Expression | null; /** * BUCKET field for ON clause (BUCKET 1 OUT OF 5 ON x) */ bucket_field: Expression | null; /** * Whether this is a DuckDB USING SAMPLE clause (vs SAMPLE/TABLESAMPLE) */ is_using_sample: boolean; /** * Whether the unit was explicitly PERCENT (vs ROWS) */ is_percent: boolean; /** * Whether to suppress method output (for cross-dialect transpilation) */ suppress_method_output: boolean; }; /** * Sample method */ declare type SampleMethod = "Bernoulli" | "System" | "Block" | "Row" | "Percent" | "Bucket" | "Reservoir"; /** * SampleProperty */ declare type SampleProperty = { this: Expression; }; /** * Database schema definition for validation. */ export declare interface Schema { /** Table definitions */ tables: TableSchema[]; /** * If true (default), unknown tables/columns are errors. * If false, they are warnings. */ strict?: boolean; } /** * Schema */ declare type Schema_2 = { this: Expression | null; expressions: Array; }; /** * SchemaCommentProperty */ declare type SchemaCommentProperty = { this: Expression; }; /** * Options for schema-aware validation. */ export declare interface SchemaValidationOptions { /** * Check column types in expressions for compatibility. * @default false */ checkTypes?: boolean; /** * Check FK/reference integrity and JOIN/reference quality. * @default false */ checkReferences?: boolean; /** * Treat unknown identifiers as errors (true) or warnings (false). * Overrides Schema.strict if provided. * @default true */ strict?: boolean; /** * Enable semantic validation rules in addition to schema checks. * @default false */ semantic?: boolean; /** * Enable strict syntax checks in addition to schema/type/reference checks. * Rejects permissive parse forms such as trailing commas before clause boundaries. * @default false */ strictSyntax?: boolean; } /** * ScopeResolution */ declare type ScopeResolution = { this: Expression | null; expression: Expression; }; /** * Search */ declare type Search = { this: Expression; expression: Expression; json_scope: Expression | null; analyzer: Expression | null; analyzer_options: Expression | null; search_mode: Expression | null; }; /** * SearchIp */ declare type SearchIp = { this: Expression; expression: Expression; }; /** * SecurityProperty */ declare type SecurityProperty = { this: Expression; }; /** * Represent a complete SELECT statement. * * This is the most feature-rich AST node, covering the full surface area of * SELECT syntax across 30+ SQL dialects. Fields that are `Option` or empty * `Vec` are omitted from the generated SQL when absent. * * # Key Fields * * - `expressions` -- the select-list (columns, `*`, computed expressions). * - `from` -- the FROM clause. `None` for `SELECT 1` style queries. * - `joins` -- zero or more JOIN clauses, each with a [`JoinKind`]. * - `where_clause` -- the WHERE predicate. * - `group_by` -- GROUP BY, including ROLLUP/CUBE/GROUPING SETS. * - `having` -- HAVING predicate. * - `order_by` -- ORDER BY with ASC/DESC and NULLS FIRST/LAST. * - `limit` / `offset` / `fetch` -- result set limiting. * - `with` -- Common Table Expressions (CTEs). * - `distinct` / `distinct_on` -- DISTINCT and PostgreSQL DISTINCT ON. * - `windows` -- named window definitions (WINDOW w AS ...). * * Dialect-specific extensions are supported via fields like `prewhere` * (ClickHouse), `qualify` (Snowflake/BigQuery/DuckDB), `connect` (Oracle * CONNECT BY), `for_xml` (TSQL), and `settings` (ClickHouse). */ declare type Select = { /** * The select-list: columns, expressions, aliases, and wildcards. */ expressions: Array; /** * The FROM clause, containing one or more table sources. */ from: From | null; /** * JOIN clauses applied after the FROM source. */ joins: Array; lateral_views: Array; /** * ClickHouse PREWHERE clause */ prewhere?: Expression | null; where_clause: Where | null; group_by: GroupBy | null; having: Having | null; qualify: Qualify | null; order_by: OrderBy | null; distribute_by: DistributeBy | null; cluster_by: ClusterBy | null; sort_by: SortBy | null; limit: Limit | null; offset: Offset | null; /** * ClickHouse LIMIT BY clause expressions */ limit_by?: Array | null; fetch: Fetch | null; distinct: boolean; distinct_on: Array | null; top: Top | null; with: With | null; sample: Sample | null; /** * ClickHouse SETTINGS clause (e.g., SETTINGS max_threads = 4) */ settings?: Array | null; /** * ClickHouse FORMAT clause (e.g., FORMAT PrettyCompact) */ format?: Expression | null; windows: Array | null; hint: Hint | null; /** * Oracle CONNECT BY clause for hierarchical queries */ connect: Connect | null; /** * SELECT ... INTO table_name for creating tables */ into: SelectInto | null; /** * FOR UPDATE/SHARE locking clauses */ locks: Array; /** * T-SQL FOR XML clause options (PATH, RAW, AUTO, EXPLICIT, BINARY BASE64, ELEMENTS XSINIL, etc.) */ for_xml?: Array; /** * T-SQL FOR JSON clause options (PATH, AUTO, ROOT, INCLUDE_NULL_VALUES, WITHOUT_ARRAY_WRAPPER) */ for_json?: Array; /** * Leading comments before the statement */ leading_comments: Array; /** * Comments that appear after SELECT keyword (before expressions) * Example: `SELECT col` -> `post_select_comments: [""]` */ post_select_comments?: Array; /** * BigQuery SELECT AS STRUCT / SELECT AS VALUE kind */ kind?: string | null; /** * MySQL operation modifiers (HIGH_PRIORITY, STRAIGHT_JOIN, SQL_CALC_FOUND_ROWS, etc.) */ operation_modifiers?: Array; /** * Whether QUALIFY appears after WINDOW (DuckDB) vs before (Snowflake/BigQuery default) */ qualify_after_window?: boolean; /** * TSQL OPTION clause (e.g., OPTION(LABEL = 'foo')) */ option?: string | null; /** * Redshift-style EXCLUDE clause at the end of the projection list * e.g., SELECT *, 4 AS col4 EXCLUDE (col2, col3) FROM ... */ exclude?: Array | null; }; /** Create a SelectBuilder, optionally pre-populated with columns. */ export declare function select(...columns: (ExprInput | '*')[]): SelectBuilder; /** * Fluent builder for SELECT queries. * * @example * ```typescript * const sql = select('id', 'name') * .from('users') * .where(col('status').eq(lit('active'))) * .orderBy(col('name').asc()) * .limit(10) * .toSql('postgresql'); * ``` */ export declare class SelectBuilder { /* Excluded from this release type: _w */ constructor(); /** Add columns to the SELECT list. Accepts Expr, strings (→ col), or '*'. */ select(...columns: (ExprInput | '*')[]): this; /** Set the FROM clause. */ from(tableOrExpr: string | Expr): this; /** Add an INNER JOIN. */ join(tableName: string, on: ExprInput): this; /** Add a LEFT JOIN. */ leftJoin(tableName: string, on: ExprInput): this; /** Add a RIGHT JOIN. */ rightJoin(tableName: string, on: ExprInput): this; /** Add a CROSS JOIN. */ crossJoin(tableName: string): this; /** Set the WHERE clause. Accepts an Expr or a raw SQL string. */ where(condition: ExprInput | string): this; /** Set the GROUP BY clause. */ groupBy(...cols: ExprInput[]): this; /** Set the HAVING clause. */ having(condition: ExprInput): this; /** Set the ORDER BY clause. */ orderBy(...exprs: ExprInput[]): this; /** Set the LIMIT. */ limit(n: number): this; /** Set the OFFSET. */ offset(n: number): this; /** Enable DISTINCT. */ distinct(): this; /** Set the QUALIFY clause (Snowflake/BigQuery/DuckDB). */ qualify(condition: ExprInput): this; /** Set the SORT BY clause (Hive/Spark — sorts within each partition). */ sortBy(...exprs: ExprInput[]): this; /** Add a named WINDOW clause definition. */ window(name: string, def: WindowDefBuilder): this; /** Add a LATERAL VIEW clause (Hive/Spark UDTF expansion). */ lateral(funcExpr: Expr, tableAlias: string, colAliases: string[]): this; /** Add a query hint (e.g. Oracle hint expressions). */ hint(text: string): this; /** * Convert to CREATE TABLE AS SELECT and return the AST. * This is a terminal operation that consumes the builder. */ ctas(tableName: string): any; /** * Convert to CREATE TABLE AS SELECT and return generated SQL. * This is a terminal operation that consumes the builder. */ ctasSql(tableName: string, dialect?: string): string; /** Add FOR UPDATE locking. */ forUpdate(): this; /** Combine with UNION. */ union(other: SelectBuilder): SetOpBuilder; /** Combine with UNION ALL. */ unionAll(other: SelectBuilder): SetOpBuilder; /** Combine with INTERSECT. */ intersect(other: SelectBuilder): SetOpBuilder; /** Combine with EXCEPT. */ except(other: SelectBuilder): SetOpBuilder; /** Generate SQL string. Defaults to generic dialect. */ toSql(dialect?: string): string; /** Return the Expression AST as a plain JS object. */ build(): any; /** Free the underlying WASM handle. */ free(): void; } /** * INTO clause for SELECT INTO statements */ declare type SelectInto = { /** * Target table or variable (used when single target) */ this: Expression; /** * Whether TEMPORARY keyword was used */ temporary: boolean; /** * Whether UNLOGGED keyword was used (PostgreSQL) */ unlogged: boolean; /** * Whether BULK COLLECT INTO was used (Oracle PL/SQL) */ bulk_collect: boolean; /** * Multiple target variables (Oracle PL/SQL: BULK COLLECT INTO v1, v2) */ expressions?: Array; }; /** * SemanticView */ declare type SemanticView = { this: Expression; metrics: Expression | null; dimensions: Expression | null; facts: Expression | null; where_: Expression | null; }; /** * Sequence property tag for ordering */ declare type SeqPropKind = "Start" | "Increment" | "Minvalue" | "Maxvalue" | "Cache" | "NoCache" | "Cycle" | "NoCycle" | "OwnedBy" | "Order" | "NoOrder" | "Comment" | "Sharing" | "Keep" | "NoKeep" | "Scale" | "NoScale" | "Shard" | "NoShard" | "Session" | "Global" | "NoCacheWord" | "NoCycleWord" | "NoMinvalueWord" | "NoMaxvalueWord"; /** * Sequence bound (value or NO MINVALUE/NO MAXVALUE) */ declare type SequenceBound = { "Value": bigint; } | "None"; /** * SEQUENCE / GENERATE_SERIES function */ declare type SequenceFunc = { start: Expression; stop: Expression; step: Expression | null; }; /** * SequenceProperties */ declare type SequenceProperties = { increment: Expression | null; minvalue: Expression | null; maxvalue: Expression | null; cache: Expression | null; start: Expression | null; owned: Expression | null; options: Array; }; /** * SerdeProperties */ declare type SerdeProperties = { expressions: Array; with_: Expression | null; }; /** * SessionParameter */ declare type SessionParameter = { this: Expression; kind: string | null; }; /** * SessionUser - MySQL/PostgreSQL SESSION_USER function */ declare type SessionUser = null; /** * Set */ declare type Set_2 = { expressions: Array; unset: Expression | null; tag: Expression | null; }; /** * SetConfigProperty */ declare type SetConfigProperty = { this: Expression; }; /** * Set SELECT DISTINCT (via WASM) */ declare function setDistinct(node: Expression, distinct?: boolean): Expression; /** * A single SET item (variable assignment) */ declare type SetItem = { /** * The variable name */ name: Expression; /** * The value to set */ value: Expression; /** * Kind: None for plain SET, Some("GLOBAL") for SET GLOBAL, etc. */ kind: string | null; /** * Whether the SET item was parsed without an = sign (TSQL: SET KEY VALUE) */ no_equals?: boolean; }; /** * Set or update the LIMIT clause * * When limit is a number, delegates to WASM. When limit is an Expression, * falls back to pure-TS manipulation. */ declare function setLimit(node: Expression, limit: number | Expression): Expression; /** * Set or update the OFFSET clause */ declare function setOffset(node: Expression, offset: number | Expression): Expression; /** * Builder for set operations (UNION, INTERSECT, EXCEPT) with optional * ORDER BY, LIMIT, and OFFSET. */ export declare class SetOpBuilder { /* Excluded from this release type: _w */ /* Excluded from this release type: __constructor */ /** Set the ORDER BY clause. */ orderBy(...exprs: ExprInput[]): this; /** Set the LIMIT. */ limit(n: number): this; /** Set the OFFSET. */ offset(n: number): this; /** Generate SQL string. Defaults to generic dialect. */ toSql(dialect?: string): string; /** Return the Expression AST as a plain JS object. */ build(): any; /** Free the underlying WASM handle. */ free(): void; } /** * SetOperation */ declare type SetOperation = { with_: Expression | null; this: Expression; expression: Expression; distinct: boolean; by_name: Expression | null; side: Expression | null; kind: string | null; on: Expression | null; }; export declare interface SetOperationBranchFact { index: number; projections: ProjectionFact[]; } /** * Union of all set operation expression types */ declare type SetOperationExpression = ExpressionByType<'union'> | ExpressionByType<'intersect'> | ExpressionByType<'except'>; export declare interface SetOperationFact { kind: 'union' | 'intersect' | 'except' | string; all: boolean; distinct: boolean; outputColumns: string[]; branches: SetOperationBranchFact[]; } export declare type SetOperationType = 'union' | 'union_all' | 'intersect' | 'except'; /** * Set or update the ORDER BY clause. * * Bare expressions are normalized to ascending order entries. Existing * `ordered` expression nodes preserve their direction and null ordering. */ declare function setOrderBy(node: Expression, orderBy: Expression | Expression[]): Expression; /** * SetProperty */ declare type SetProperty = { multi: Expression | null; }; /** * SET variable statement */ declare type SetStatement = { /** * The items being set */ items: Array; }; /** * SettingsProperty */ declare type SettingsProperty = { expressions: Array; }; /** * SHA2 */ declare type SHA2 = { this: Expression; length: bigint | null; }; /** * SHA2Digest */ declare type SHA2Digest = { this: Expression; length: bigint | null; }; /** * SharingProperty */ declare type SharingProperty = { this: Expression | null; }; /** * SHOW statement - displays database objects */ declare type Show = { /** * The thing to show (DATABASES, TABLES, SCHEMAS, etc.) */ this: string; /** * Whether TERSE was specified */ terse: boolean; /** * Whether HISTORY was specified */ history: boolean; /** * LIKE pattern */ like: Expression | null; /** * IN scope kind (ACCOUNT, DATABASE, SCHEMA, TABLE) */ scope_kind: string | null; /** * IN scope object */ scope: Expression | null; /** * STARTS WITH pattern */ starts_with: Expression | null; /** * LIMIT clause */ limit: Limit | null; /** * FROM clause (for specific object) */ from: Expression | null; /** * WHERE clause (MySQL: SHOW STATUS WHERE ...) */ where_clause?: Expression | null; /** * FOR target (MySQL: SHOW GRANTS FOR user, SHOW PROFILE ... FOR QUERY n) */ for_target?: Expression | null; /** * Second FROM clause (MySQL: SHOW COLUMNS FROM tbl FROM db) */ db?: Expression | null; /** * Target identifier (MySQL: engine name in SHOW ENGINE, table in SHOW COLUMNS FROM) */ target?: Expression | null; /** * MUTEX flag for SHOW ENGINE (true=MUTEX, false=STATUS, None=neither) */ mutex?: boolean | null; /** * WITH PRIVILEGES clause (Snowflake: SHOW ... WITH PRIVILEGES USAGE, MODIFY) */ privileges?: Array; }; export declare function sign(expr: ExprInput): Expr; /** * SIMILAR TO expression */ declare type SimilarToExpr = { this: Expression; pattern: Expression; escape: Expression | null; not: boolean; }; /** * Slice */ declare type Slice = { this: Expression | null; expression: Expression | null; step: Expression | null; }; /** * Check if any node matches a predicate * * @example * ```typescript * const hasSubquery = some(ast, (node) => getExprType(node) === 'subquery'); * ``` */ declare function some(node: Expression, predicate: NodePredicate): boolean; /** * SortArray */ declare type SortArray = { this: Expression; asc: Expression | null; nulls_first: Expression | null; }; /** * SORT BY clause (Hive/Spark) * Sorts data within each reducer (local sort, not global) */ declare type SortBy = { expressions: Array; }; /** * SortKeyProperty */ declare type SortKeyProperty = { this: Expression; compound: Expression | null; }; /** * Sort order for PRIMARY KEY ASC/DESC */ declare type SortOrder = "Asc" | "Desc"; /** Result from source tables extraction */ export declare interface SourceTablesResult { success: boolean; tables?: string[]; error?: string; } /** * Represents a position in the source SQL */ declare type Span = { /** * Starting byte offset */ start: number; /** * Ending byte offset (exclusive) */ end: number; /** * Line number (1-based) */ line: number; /** * Column number (1-based) */ column: number; }; /** * Span information for a token, indicating its position in the source SQL. */ export declare interface SpanInfo { start: number; end: number; line: number; column: number; } /** * SPLIT function */ declare type SplitFunc = { this: Expression; delimiter: Expression; }; /** * SplitPart */ declare type SplitPart = { this: Expression; delimiter: Expression | null; part_index: Expression | null; }; /** * Array expression */ declare type SqlArray = { expressions: Array; }; /** * SQL Comment preservation */ declare type SqlComment = { text: string; is_block: boolean; }; /** * SQL data access characteristics for functions */ declare type SqlDataAccess = "NoSql" | "ContainsSql" | "ReadsSqlData" | "ModifiesSqlData"; /** Parse a raw SQL fragment into an expression. */ export declare function sqlExpr(sql: string): Expr; /** Create a SQL NULL expression. */ export declare function sqlNull(): Expr; /** * SqlReadWriteProperty */ declare type SqlReadWriteProperty = { this: Expression; }; /** * SqlSecurityProperty */ declare type SqlSecurityProperty = { this: Expression; }; export declare function sqrt(expr: ExprInput): Expr; /** * StabilityProperty */ declare type StabilityProperty = { this: Expression; }; /** * Stage reference (Snowflake) - @stage_name or @namespace.stage/path */ declare type StageReference = { /** * Stage name including @ prefix (e.g., "@mystage", "@namespace.mystage") */ name: string; /** * Optional path within the stage (e.g., "/path/to/file.csv") */ path: string | null; /** * Optional FILE_FORMAT parameter */ file_format: Expression | null; /** * Optional PATTERN parameter */ pattern: string | null; /** * Whether the stage reference was originally quoted (e.g., '@mystage') */ quoted?: boolean; }; /** * StandardHash */ declare type StandardHash = { this: Expression; expression: Expression | null; }; /** * Represent a wildcard star expression (`*`, `table.*`). * * Supports the EXCEPT/EXCLUDE, REPLACE, and RENAME modifiers found in * DuckDB, BigQuery, and Snowflake (e.g. `SELECT * EXCEPT (id) FROM t`). */ declare type Star = { /** * Optional table qualifier (e.g. `t` in `t.*`). */ table: Identifier | null; /** * EXCLUDE / EXCEPT columns (DuckDB, BigQuery, Snowflake) */ except: Array | null; /** * REPLACE expressions (BigQuery, Snowflake) */ replace: Array | null; /** * RENAME columns (Snowflake) */ rename: Array<[Identifier, Identifier]> | null; /** * Trailing comments that appeared after the star */ trailing_comments?: Array; /** * Source position span */ span?: Span | null; }; /** Create a star (*) expression. */ export declare function star(): Expr; export declare interface StarProjectionFact { index: number; table?: string; expandedColumns: string[]; } /** * StDistance */ declare type StDistance = { this: Expression; expression: Expression; use_spheroid: Expression | null; }; /** Step kind — string for simple types, object for parameterized types */ export declare type StepKind = 'scan' | 'aggregate' | 'sort' | { join: PlanJoinType; } | { set_operation: SetOperationType; }; /** * StorageHandlerProperty */ declare type StorageHandlerProperty = { this: Expression; }; /** * StPoint */ declare type StPoint = { this: Expression; expression: Expression; null: Expression | null; }; /** * STREAM definition (Snowflake) - for change data capture */ declare type Stream = { this: Expression; on: Expression | null; show_initial_rows: boolean | null; }; /** * STRING_AGG function (PostgreSQL/Standard SQL) */ declare type StringAggFunc = { this: Expression; separator: Expression | null; order_by: Array | null; distinct: boolean; filter: Expression | null; /** * BigQuery LIMIT inside STRING_AGG */ limit?: Expression | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * StringFunc - String type conversion function (BigQuery STRING) */ declare type StringFunc = { this: Expression; zone: Expression | null; }; /** * StringToArray */ declare type StringToArray = { this: Expression; expression: Expression | null; null: Expression | null; }; /** * StrPosition */ declare type StrPosition = { this: Expression; substr: Expression | null; position: Expression | null; occurrence: Expression | null; }; /** * StrToDate */ declare type StrToDate = { this: Expression; format: string | null; safe: Expression | null; }; /** * StrToMap */ declare type StrToMap = { this: Expression; pair_delim: Expression | null; key_value_delim: Expression | null; duplicate_resolution_callback: Expression | null; }; /** * StrToTime */ declare type StrToTime = { this: Expression; format: string; zone: Expression | null; safe: Expression | null; target_type: Expression | null; }; /** * StrToUnix */ declare type StrToUnix = { this: Expression | null; format: string | null; }; /** * Struct expression */ declare type Struct = { fields: Array<[string | null, Expression]>; }; /** * STRUCT constructor */ declare type StructConstructor = { fields: Array<[Identifier | null, Expression]>; }; /** * STRUCT_EXTRACT function */ declare type StructExtractFunc = { this: Expression; field: Identifier; }; /** * Struct field with optional OPTIONS clause (BigQuery) and COMMENT (Spark/Databricks) */ declare type StructField = { name: string; data_type: DataType; options?: Array; comment?: string | null; }; /** * Stuff */ declare type Stuff = { this: Expression; start: Expression | null; length: bigint | null; expression: Expression; }; /** * Represent a parenthesized subquery expression. * * A subquery wraps an inner query (typically a SELECT, UNION, etc.) in * parentheses and optionally applies an alias, column aliases, ORDER BY, * LIMIT, and OFFSET. The `modifiers_inside` flag controls whether the * modifiers are rendered inside or outside the parentheses. * * Subqueries appear in many SQL contexts: FROM clauses, WHERE IN/EXISTS, * scalar subqueries in select-lists, and derived tables. */ declare type Subquery = { /** * The inner query expression. */ this: Expression; /** * Optional alias for the derived table. */ alias: Identifier | null; /** * Optional column aliases: AS t(c1, c2) */ column_aliases: Array; /** * Whether AS keyword was explicitly used for the alias. */ alias_explicit_as: boolean; /** * Original alias keyword spelling, e.g. `AS` vs `as`. */ alias_keyword?: string | null; /** * ORDER BY clause (for parenthesized queries) */ order_by: OrderBy | null; /** * LIMIT clause */ limit: Limit | null; /** * OFFSET clause */ offset: Offset | null; /** * DISTRIBUTE BY clause (Hive/Spark) */ distribute_by?: DistributeBy | null; /** * SORT BY clause (Hive/Spark) */ sort_by?: SortBy | null; /** * CLUSTER BY clause (Hive/Spark) */ cluster_by?: ClusterBy | null; /** * Whether this is a LATERAL subquery (can reference earlier tables in FROM) */ lateral: boolean; /** * Whether modifiers (ORDER BY, LIMIT, OFFSET) should be generated inside the parentheses * true: (SELECT 1 LIMIT 1) - modifiers inside * false: (SELECT 1) LIMIT 1 - modifiers outside */ modifiers_inside: boolean; /** * Trailing comments after the closing paren */ trailing_comments: Array; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Wrap a SelectBuilder as a named subquery for use in FROM or JOIN clauses. * Note: this consumes the SelectBuilder. * * @example * ```typescript * const inner = select('id', 'name').from('users'); * const sql = select('sub.id').from(subquery(inner, 'sub')).toSql(); * ``` */ export declare function subquery(query: SelectBuilder, alias: string): Expr; /** * Subscript access (array[index] or map[key]) */ declare type Subscript = { this: Expression; index: Expression; }; export declare function substring(expr: ExprInput, start: ExprInput, length?: ExprInput): Expr; /** * SUBSTRING function */ declare type SubstringFunc = { this: Expression; start: Expression; length: Expression | null; /** * Whether SQL standard FROM/FOR syntax was used (true) vs comma-separated (false) */ from_for_syntax: boolean; }; /** * SUBSTRING_INDEX(str, delim, count) */ declare type SubstringIndex = { this: Expression; delimiter: Expression | null; count: Expression | null; }; export declare function sum(expr: ExprInput): Expr; /** * SUM_IF / COUNT_IF function */ declare type SumIfFunc = { this: Expression; condition: Expression; filter: Expression | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Summarize */ declare type Summarize = { this: Expression; table: Expression | null; }; /** * Systimestamp */ declare type Systimestamp = { this: Expression | null; }; /** Create a table reference. Supports dotted names like `'schema.table'`. */ export declare function table(name: string): Expr; /** * TableAlias */ declare type TableAlias = { this: Expression | null; columns: Array; }; /** * TABLE ref or MODEL ref used as a function argument (BigQuery) * e.g., GAP_FILL(TABLE device_data, ...) or ML.PREDICT(MODEL mydataset.mymodel, ...) */ declare type TableArgument = { /** * The keyword prefix: "TABLE" or "MODEL" */ prefix: string; /** * The table/model reference expression */ this: Expression; }; /** * Table-level constraint */ declare type TableConstraint = { "PrimaryKey": { name: Identifier | null; columns: Array; /** * INCLUDE (columns) - non-key columns included in the index (PostgreSQL) */ include_columns: Array; modifiers: ConstraintModifiers; /** * Whether the CONSTRAINT keyword was used (vs MySQL's `PRIMARY KEY name (cols)` syntax) */ has_constraint_keyword: boolean; }; } | { "Unique": { name: Identifier | null; columns: Array; /** * Whether columns are parenthesized (false for UNIQUE idx_name without parens) */ columns_parenthesized: boolean; modifiers: ConstraintModifiers; /** * Whether the CONSTRAINT keyword was used (vs MySQL's `UNIQUE name (cols)` syntax) */ has_constraint_keyword: boolean; /** * PostgreSQL 15+: NULLS NOT DISTINCT */ nulls_not_distinct: boolean; }; } | { "ForeignKey": { name: Identifier | null; columns: Array; references: ForeignKeyRef | null; /** * ON DELETE action when REFERENCES is absent */ on_delete: ReferentialAction | null; /** * ON UPDATE action when REFERENCES is absent */ on_update: ReferentialAction | null; modifiers: ConstraintModifiers; }; } | { "Check": { name: Identifier | null; expression: Expression; modifiers: ConstraintModifiers; }; } | { "Assume": { name: Identifier | null; expression: Expression; }; } | { "Default": { name: Identifier | null; expression: Expression; column: Identifier; }; } | { "Index": { name: Identifier | null; columns: Array; /** * Index kind: UNIQUE, FULLTEXT, SPATIAL, etc. */ kind: string | null; modifiers: ConstraintModifiers; /** * True if KEY keyword was used instead of INDEX */ use_key_keyword: boolean; /** * ClickHouse: indexed expression (instead of columns) */ expression?: Expression | null; /** * ClickHouse: TYPE type_func(args) */ index_type?: Expression | null; /** * ClickHouse: GRANULARITY n */ granularity?: Expression | null; }; } | { "Projection": { name: Identifier; expression: Expression; }; } | { "Like": { source: TableRef; /** * Options as (INCLUDING|EXCLUDING, property) pairs */ options: Array<[LikeOptionAction, string]>; }; } | { "PeriodForSystemTime": { start_col: Identifier; end_col: Identifier; }; } | { "Exclude": { name: Identifier | null; /** * Index access method (gist, btree, etc.) */ using: string | null; /** * Elements: (expression, operator) pairs */ elements: Array; /** * INCLUDE columns */ include_columns: Array; /** * WHERE predicate */ where_clause: Expression | null; /** * WITH (storage_parameters) */ with_params: Array<[string, string]>; /** * USING INDEX TABLESPACE tablespace_name */ using_index_tablespace: string | null; modifiers: ConstraintModifiers; }; } | { "Tags": Tags; } | { "InitiallyDeferred": { /** * true = INITIALLY DEFERRED, false = INITIALLY IMMEDIATE */ deferred: boolean; }; }; /** * Table-level foreign key constraint. */ declare interface TableForeignKey { /** Optional constraint name */ name?: string; /** Source columns in this table */ columns: string[]; /** Target reference */ references: { table: string; columns: string[]; schema?: string; }; } /** * TableFromRows */ declare type TableFromRows = { this: Expression; alias: string | null; joins: Array; pivots: Expression | null; sample: Expression | null; }; /** * Input type for table references */ declare type TableInput = string | ExpressionByType<'table'>; /** * Represent a table reference with optional schema and catalog qualifiers. * * Renders as `name`, `schema.name`, or `catalog.schema.name` depending on * which qualifiers are present. Supports aliases, column alias lists, * time-travel clauses (Snowflake, BigQuery), table hints (TSQL), and * several other dialect-specific extensions. */ declare type TableRef = { /** * The unqualified table name. */ name: Identifier; /** * Optional schema qualifier (e.g. `public` in `public.users`). */ schema: Identifier | null; /** * Optional catalog qualifier (e.g. `mydb` in `mydb.public.users`). */ catalog: Identifier | null; /** * Optional table alias (e.g. `t` in `FROM users AS t`). */ alias: Identifier | null; /** * Whether AS keyword was explicitly used for the alias */ alias_explicit_as: boolean; /** * Column aliases for table alias: AS t(c1, c2) */ column_aliases: Array; /** * Leading comments that appeared before this table reference in a FROM clause */ leading_comments?: Array; /** * Trailing comments that appeared after this table reference */ trailing_comments: Array; /** * Snowflake time travel: BEFORE (STATEMENT => ...) or AT (TIMESTAMP => ...) */ when: HistoricalData | null; /** * PostgreSQL ONLY modifier: prevents scanning child tables in inheritance hierarchy */ only: boolean; /** * ClickHouse FINAL modifier: forces final aggregation for MergeTree tables */ final_: boolean; /** * TABLESAMPLE clause attached to this table reference (DuckDB, BigQuery) */ table_sample?: Sample | null; /** * TSQL table hints: WITH (TABLOCK, INDEX(myindex), ...) */ hints: Array; /** * TSQL: FOR SYSTEM_TIME temporal clause * Contains the full clause text, e.g., "FOR SYSTEM_TIME BETWEEN c AND d" */ system_time?: string | null; /** * MySQL: PARTITION(p0, p1, ...) hint for reading from specific partitions */ partitions?: Array; /** * Snowflake IDENTIFIER() function: dynamic table name from string/variable * When set, this is used instead of the name field */ identifier_func?: Expression | null; /** * Snowflake CHANGES clause: CHANGES (INFORMATION => ...) AT (...) END (...) */ changes?: Changes | null; /** * Time travel version clause: FOR VERSION AS OF / FOR TIMESTAMP AS OF (Presto/Trino, BigQuery, Databricks) */ version?: Version | null; /** * Source position span */ span?: Span | null; }; /** * TableSample - wraps an expression with a TABLESAMPLE clause * Used when TABLESAMPLE follows a non-Table expression (subquery, function, etc.) */ declare type TableSample = { /** * The expression being sampled (subquery, function, etc.) */ this?: Expression | null; /** * The sample specification */ sample?: Sample | null; expressions: Array; method: string | null; bucket_numerator: Expression | null; bucket_denominator: Expression | null; bucket_field: Expression | null; percent: Expression | null; rows: Expression | null; size: bigint | null; seed: Expression | null; }; /** * Table definition in the schema. */ export declare interface TableSchema { /** Table name */ name: string; /** Schema/namespace name (e.g., "public", "dbo") */ schema?: string; /** Column definitions */ columns: ColumnSchema[]; /** Aliases that can refer to this table */ aliases?: string[]; /** Primary key columns */ primaryKey?: string[]; /** Unique key groups (composite keys allowed) */ uniqueKeys?: string[][]; /** Table-level foreign keys */ foreignKeys?: TableForeignKey[]; } /** * Tags are used for generating arbitrary sql like SELECT x. */ declare type Tag = { this: Expression | null; prefix: Expression | null; postfix: Expression | null; }; /** * Tags */ declare type Tags = { expressions: Array; }; /** * TemporaryProperty */ declare type TemporaryProperty = { this: Expression | null; }; /** * Teradata index specification for CREATE TABLE */ declare type TeradataIndex = { /** * Index kind: NoPrimary, Primary, PrimaryAmp, Unique, UniquePrimary */ kind: TeradataIndexKind; /** * Optional index name */ name: string | null; /** * Optional column list */ columns: Array; }; /** * Kind of Teradata index */ declare type TeradataIndexKind = "NoPrimary" | "Primary" | "PrimaryAmp" | "Unique" | "UniquePrimary" | "Secondary"; /** * TimeAdd */ declare type TimeAdd = { this: Expression; expression: Expression; unit: string | null; }; /** * TimeDiff */ declare type TimeDiff = { this: Expression; expression: Expression; unit: string | null; }; /** * TimeFromParts */ declare type TimeFromParts = { hour: Expression | null; min: Expression | null; sec: Expression | null; nano: Expression | null; fractions: Expression | null; precision: bigint | null; }; /** * TimeSlice */ declare type TimeSlice = { this: Expression; expression: Expression; unit: string; kind: string | null; }; /** * TimestampAdd */ declare type TimestampAdd = { this: Expression; expression: Expression; unit: string | null; }; /** * TimestampDiff */ declare type TimestampDiff = { this: Expression; expression: Expression; unit: string | null; }; /** * TimestampFromParts */ declare type TimestampFromParts = { zone: Expression | null; milli: Expression | null; this: Expression | null; expression: Expression | null; }; /** * TimestampFunc - TIMESTAMP constructor function */ declare type TimestampFunc = { this: Expression | null; zone: Expression | null; with_tz: boolean | null; safe: boolean | null; }; /** * TimestampSub */ declare type TimestampSub = { this: Expression; expression: Expression; unit: string | null; }; /** * TimestampTzFromParts */ declare type TimestampTzFromParts = { zone: Expression | null; }; /** * TimeStrToTime */ declare type TimeStrToTime = { this: Expression; zone: Expression | null; }; /** * TimeSub */ declare type TimeSub = { this: Expression; expression: Expression; unit: string | null; }; /** * TimeToStr */ declare type TimeToStr = { this: Expression; format: string; culture: Expression | null; zone: Expression | null; }; /** * TimeTrunc */ declare type TimeTrunc = { this: Expression; unit: string; zone: Expression | null; }; /** * Automatically converts unit arg into a var. */ declare type TimeUnit = { unit: string | null; }; /** * ToBinary */ declare type ToBinary = { this: Expression; format: string | null; safe: Expression | null; }; /** * ToBoolean */ declare type ToBoolean = { this: Expression; safe: Expression | null; }; /** * ToChar */ declare type ToChar = { this: Expression; format: string | null; nlsparam: Expression | null; is_numeric: Expression | null; }; /** * TO_DATE function */ declare type ToDateFunc = { this: Expression; format: Expression | null; }; /** * ToDecfloat */ declare type ToDecfloat = { this: Expression; format: string | null; }; /** * ToDouble */ declare type ToDouble = { this: Expression; format: string | null; safe: Expression | null; }; /** * ToFile */ declare type ToFile = { this: Expression; path: Expression | null; safe: Expression | null; }; /** * A single token from the SQL token stream. */ export declare interface TokenInfo { tokenType: string; text: string; span: SpanInfo; comments: string[]; trailingComments: string[]; } /** * Tokenize SQL into a token stream. * * @param sql - The SQL string to tokenize * @param dialect - The dialect to use for tokenization * @returns The token stream * * @example * ```typescript * const result = tokenize("SELECT a, b FROM t", Dialect.PostgreSQL); * if (result.success) { * for (const token of result.tokens!) { * console.log(token.tokenType, token.text, token.span); * } * } * ``` */ export declare function tokenize(sql: string, dialect?: Dialect): TokenizeResult; /** * Result of a tokenize operation */ export declare interface TokenizeResult { success: boolean; tokens?: TokenInfo[]; error?: string; /** 1-based line number where the error occurred */ errorLine?: number; /** 1-based column number where the error occurred */ errorColumn?: number; /** Start byte offset of the error range */ errorStart?: number; /** End byte offset of the error range (exclusive) */ errorEnd?: number; } /** * ToMap - Materialize-style map constructor * Can hold either: * - A SELECT subquery (MAP(SELECT 'a', 1)) * - A struct with key=>value entries (MAP['a' => 1, 'b' => 2]) */ declare type ToMap = { /** * Either a Select subquery or a Struct containing PropertyEQ entries */ this: Expression; }; /** * ToNumber */ declare type ToNumber = { this: Expression; format: Expression | null; nlsparam: Expression | null; precision: Expression | null; scale: Expression | null; safe: Expression | null; safe_name: Expression | null; }; /** * TOP clause (SQL Server) */ declare type Top = { this: Expression; percent: boolean; with_ties: boolean; /** * Whether the expression was parenthesized: TOP (10) vs TOP 10 */ parenthesized: boolean; }; /** * ToTableProperty */ declare type ToTableProperty = { this: Expression; }; /** * TO_TIMESTAMP function */ declare type ToTimestampFunc = { this: Expression; format: Expression | null; }; /** * Transaction */ declare type Transaction = { this: Expression | null; modes: Expression | null; mark: Expression | null; }; /** * Transform */ declare type Transform = { this: Expression; expression: Expression; }; /** * Transform an AST tree, returning a new tree with modifications * * @example * ```typescript * // Rename all columns named 'old' to 'new' * const newAst = transform(ast, { * column: (node) => { * const data = getExprData(node); * if (data.name.name === 'old') { * return makeExpr('column', { ...data, name: { ...data.name, name: 'new' } }); * } * } * }); * ``` */ export declare function transform(node: Expression, config: TransformConfig): Expression; /** * Transform callback - returns new node or undefined to keep original */ declare type TransformCallback = (node: Expression, parent: Expression | null, key: string | null, index: number | null) => Expression | undefined | null; /** * Transform configuration with callbacks for specific node types */ declare type TransformConfig = { [K in ExpressionType]?: TransformCallback; } & { /** Called before transforming any node */ enter?: TransformCallback; /** Called after transforming any node and its children */ leave?: TransformCallback; }; /** * TRANSFORM_KEYS / TRANSFORM_VALUES function */ declare type TransformFunc = { this: Expression; transform: Expression; }; export declare interface TransformFunctionFact { name: string; literalArgs: string[]; columnArgs: ColumnReferenceFact[]; } export declare type TransformKind = 'direct' | 'cast' | 'aggregation' | 'constant' | 'expression' | 'star'; /** * TransformModelProperty */ declare type TransformModelProperty = { expressions: Array; }; /** * TransientProperty */ declare type TransientProperty = { this: Expression | null; }; /** * Translate */ declare type Translate = { this: Expression; from_: Expression | null; to: Expression | null; }; /** * TranslateCharacters */ declare type TranslateCharacters = { this: Expression; expression: Expression; with_error: Expression | null; }; /** * Transpile SQL from one dialect to another. * * @param sql - The SQL string to transpile * @param read - Source dialect to parse the SQL with * @param write - Target dialect to generate SQL for * @returns The transpiled SQL statements * * @remarks * **Per-dialect builds:** When using a per-dialect sub-path import * (e.g., `@polyglot-sql/sdk/clickhouse`), only same-dialect transpilation * and conversion to/from {@link Dialect.Generic} are supported. * Cross-dialect transpilation (e.g., ClickHouse → PostgreSQL) will return * `{ success: false, error: "Cross-dialect transpilation not available in this build" }`. * Use {@link getDialects} to check which dialects are available at runtime. * * @example * ```typescript * const result = transpile( * "SELECT IFNULL(a, b)", * Dialect.MySQL, * Dialect.PostgreSQL, * ); * // result.sql[0] = "SELECT COALESCE(a, b)" * ``` */ export declare function transpile(sql: string, read: Dialect, write: Dialect, options?: TranspileOptions): TranspileResult; export declare interface TranspileOptions { /** Pretty-print the generated SQL */ pretty?: boolean; /** How unsupported target-dialect constructs should be handled */ unsupportedLevel?: UnsupportedLevel; /** Maximum number of unsupported diagnostics to include in raised errors */ maxUnsupported?: number; } /** * Result of a transpilation operation */ export declare interface TranspileResult { success: boolean; sql?: string[]; error?: string; /** 1-based line number where the error occurred */ errorLine?: number; /** 1-based column number where the error occurred */ errorColumn?: number; /** Start byte offset of the error range */ errorStart?: number; /** End byte offset of the error range (exclusive) */ errorEnd?: number; } /** * Trigger body */ declare type TriggerBody = { "Execute": { function: TableRef; args: Array; }; } | { "Block": string; }; /** * Trigger event (INSERT, UPDATE, DELETE, TRUNCATE) */ declare type TriggerEvent = "Insert" | { "Update": Array | null; } | "Delete" | "Truncate"; /** * Trigger FOR EACH clause */ declare type TriggerForEach = "Row" | "Statement"; /** * Trigger REFERENCING clause */ declare type TriggerReferencing = { old_table: Identifier | null; new_table: Identifier | null; old_row: Identifier | null; new_row: Identifier | null; }; /** * Trigger timing (BEFORE, AFTER, INSTEAD OF) */ declare type TriggerTiming = "Before" | "After" | "InsteadOf"; export declare function trim(expr: ExprInput): Expr; /** * TRIM function */ declare type TrimFunc = { this: Expression; characters: Expression | null; position: TrimPosition; /** * Whether SQL standard syntax was used (TRIM(BOTH chars FROM str)) vs function syntax (TRIM(str)) */ sql_standard_syntax: boolean; /** * Whether the position was explicitly specified (BOTH/LEADING/TRAILING) vs defaulted */ position_explicit: boolean; }; declare type TrimPosition = "Both" | "Leading" | "Trailing"; /** * TRUNCATE TABLE statement */ declare type Truncate = { /** * Target of TRUNCATE (TABLE vs DATABASE) */ target: TruncateTarget; /** * IF EXISTS clause */ if_exists: boolean; table: TableRef; /** * ClickHouse: ON CLUSTER clause for distributed DDL */ on_cluster?: OnCluster | null; cascade: boolean; /** * Additional tables for multi-table TRUNCATE */ extra_tables: Array; /** * RESTART IDENTITY or CONTINUE IDENTITY */ identity: TruncateIdentity | null; /** * RESTRICT option (alternative to CASCADE) */ restrict: boolean; /** * Hive PARTITION clause: PARTITION(key=value, ...) */ partition?: Expression | null; }; /** * TRUNCATE / TRUNC function */ declare type TruncateFunc = { this: Expression; decimals: Expression | null; }; /** * TRUNCATE identity option */ declare type TruncateIdentity = "Restart" | "Continue"; /** * TruncateTable */ declare type TruncateTable = { expressions: Array; is_database: Expression | null; exists: boolean; only: Expression | null; cluster: Expression | null; identity: Expression | null; option: Expression | null; partition: Expression | null; }; /** * A table entry in a TRUNCATE statement, with optional ONLY modifier and * suffix */ declare type TruncateTableEntry = { table: TableRef; /** * Whether the table has a * suffix (inherit children) */ star: boolean; }; /** * TRUNCATE target type */ declare type TruncateTarget = "Table" | "Database"; /** * TryBase64DecodeBinary */ declare type TryBase64DecodeBinary = { this: Expression; alphabet: Expression | null; }; /** * TryBase64DecodeString */ declare type TryBase64DecodeString = { this: Expression; alphabet: Expression | null; }; /** * T-SQL TRY/CATCH block. */ declare type TryCatch = { /** * Statements inside BEGIN TRY ... END TRY. */ try_body: Array; /** * Statements inside BEGIN CATCH ... END CATCH, when present. */ catch_body?: Array | null; }; /** * TryToDecfloat */ declare type TryToDecfloat = { this: Expression; format: string | null; }; /** * TsOrDsAdd */ declare type TsOrDsAdd = { this: Expression; expression: Expression; unit: string | null; return_type: Expression | null; }; /** * TsOrDsDiff */ declare type TsOrDsDiff = { this: Expression; expression: Expression; unit: string | null; }; /** * TsOrDsToDate */ declare type TsOrDsToDate = { this: Expression; format: string | null; safe: Expression | null; }; /** * TsOrDsToTime */ declare type TsOrDsToTime = { this: Expression; format: string | null; safe: Expression | null; }; /** * Tuple expression */ declare type Tuple = { expressions: Array; }; /** * Type attribute for composite types */ declare type TypeAttribute = { name: Identifier; data_type: DataType; collate: Identifier | null; }; /** * Type definition */ declare type TypeDefinition = { "Enum": Array; } | { "Composite": Array; } | { "Range": { subtype: DataType; subtype_diff: string | null; canonical: string | null; }; } | { "Base": { input: string; output: string; internallength: number | null; }; } | { "Domain": { base_type: DataType; default: Expression | null; constraints: Array; }; }; /** * Generic unary function (takes a single argument) */ declare type UnaryFunc = { this: Expression; /** * Original function name for round-trip preservation (e.g., CHAR_LENGTH vs LENGTH) */ original_name?: string | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Represent a unary operation (single operand with a prefix operator). * * Shared payload for `Not`, `Neg`, and `BitwiseNot` variants. */ declare type UnaryOp = { /** * The operand expression. */ this: Expression; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Union of all unary operator expression types */ declare type UnaryOperatorExpression = ExpressionByType<'not'> | ExpressionByType<'neg'> | ExpressionByType<'bitwise_not'>; /** * UNCACHE TABLE statement (Spark) */ declare type Uncache = { /** * The table to uncache */ table: Identifier; /** * IF EXISTS clause */ if_exists: boolean; }; /** * UNDROP TABLE/SCHEMA/DATABASE statement (Snowflake, ClickHouse) */ declare type Undrop = { /** * The object kind: "TABLE", "SCHEMA", or "DATABASE" */ kind: string; /** * The object name */ name: TableRef; /** * IF EXISTS clause */ if_exists: boolean; }; /** * Unhex */ declare type Unhex = { this: Expression; expression: Expression | null; }; /** * UnicodeString */ declare type UnicodeString = { this: Expression; escape: Expression | null; }; /** * Uniform */ declare type Uniform = { this: Expression; expression: Expression; gen: Expression | null; seed: Expression | null; }; /** * Represent a UNION set operation between two query expressions. * * When `all` is true, duplicate rows are preserved (UNION ALL). * ORDER BY, LIMIT, and OFFSET can be applied to the combined result. * Supports DuckDB's BY NAME modifier and BigQuery's CORRESPONDING modifier. */ declare type Union = { /** * The left-hand query operand. */ left: Expression; /** * The right-hand query operand. */ right: Expression; /** * Whether UNION ALL (true) or UNION (false, which deduplicates). */ all: boolean; /** * Whether DISTINCT was explicitly specified */ distinct: boolean; /** * Optional WITH clause */ with: With | null; /** * ORDER BY applied to entire UNION result */ order_by: OrderBy | null; /** * LIMIT applied to entire UNION result */ limit: Expression | null; /** * OFFSET applied to entire UNION result */ offset: Expression | null; /** * DISTRIBUTE BY clause (Hive/Spark) */ distribute_by?: DistributeBy | null; /** * SORT BY clause (Hive/Spark) */ sort_by?: SortBy | null; /** * CLUSTER BY clause (Hive/Spark) */ cluster_by?: ClusterBy | null; /** * DuckDB BY NAME modifier */ by_name: boolean; /** * BigQuery: Set operation side (LEFT, RIGHT, FULL) */ side?: string | null; /** * BigQuery: Set operation kind (INNER) */ kind?: string | null; /** * BigQuery: CORRESPONDING modifier */ corresponding: boolean; /** * BigQuery: STRICT modifier (before CORRESPONDING) */ strict: boolean; /** * BigQuery: BY (columns) after CORRESPONDING */ on_columns?: Array; }; /** Create a UNION of two SELECT queries. */ export declare function union(left: SelectBuilder, right: SelectBuilder): SetOpBuilder; /** Create a UNION ALL of two SELECT queries. */ export declare function unionAll(left: SelectBuilder, right: SelectBuilder): SetOpBuilder; /** * UniqueColumnConstraint */ declare type UniqueColumnConstraint = { this: Expression | null; index_type: Expression | null; on_conflict: Expression | null; nulls: Expression | null; options: Array; }; /** * UniqueKeyProperty */ declare type UniqueKeyProperty = { expressions: Array; }; /** * UNIX_TIMESTAMP function */ declare type UnixTimestampFunc = { this: Expression | null; format: Expression | null; }; /** * UnixToStr */ declare type UnixToStr = { this: Expression; format: string | null; }; /** * UnixToTime */ declare type UnixToTime = { this: Expression; scale: bigint | null; zone: Expression | null; hours: Expression | null; minutes: Expression | null; format: string | null; target_type: Expression | null; }; /** * UNNEST function */ declare type UnnestFunc = { this: Expression; /** * Additional arguments for multi-argument UNNEST (e.g., UNNEST(arr1, arr2)) */ expressions?: Array; with_ordinality: boolean; alias: Identifier | null; /** * BigQuery: offset alias for WITH OFFSET AS */ offset_alias?: Identifier | null; }; /** * UNPIVOT operation */ declare type Unpivot = { this: Expression; value_column: Identifier; name_column: Identifier; columns: Array; alias: Identifier | null; /** * Optional output column aliases from `UNPIVOT(...) AS alias(col1, col2, ...)` */ alias_columns?: Array; /** * Whether the value_column was parenthesized in the original SQL */ value_column_parenthesized: boolean; /** * INCLUDE NULLS (true), EXCLUDE NULLS (false), or not specified (None) */ include_nulls: boolean | null; /** * Additional value columns when parenthesized (e.g., (first_half_sales, second_half_sales)) */ extra_value_columns?: Array; }; /** * UnpivotColumns */ declare type UnpivotColumns = { this: Expression; expressions: Array; }; /** * Transpilation options */ export declare type UnsupportedLevel = 'ignore' | 'warn' | 'raise' | 'immediate'; /** * UPDATE statement */ declare type Update = { table: TableRef; hint: Hint | null; /** * Additional tables for multi-table UPDATE (MySQL syntax) */ extra_tables: Array; /** * JOINs attached to the table list (MySQL multi-table syntax) */ table_joins: Array; set: Array<[Identifier, Expression]>; from_clause: From | null; /** * JOINs after FROM clause (PostgreSQL, Snowflake, SQL Server syntax) */ from_joins: Array; where_clause: Where | null; /** * RETURNING clause (PostgreSQL, SQLite) */ returning: Array; /** * OUTPUT clause (TSQL) */ output: OutputClause | null; /** * WITH clause (CTEs) */ with: With | null; /** * Leading comments before the statement */ leading_comments: Array; /** * LIMIT clause (MySQL) */ limit: Expression | null; /** * ORDER BY clause (MySQL) */ order_by: OrderBy | null; /** * Whether FROM clause appears before SET (Snowflake syntax) */ from_before_set: boolean; }; /** Create an UpdateBuilder for the given table. */ export declare function update(tableName: string): UpdateBuilder; /** * Fluent builder for UPDATE statements. * * @example * ```typescript * const sql = update('users') * .set('name', lit('Bob')) * .where(col('id').eq(lit(1))) * .toSql(); * ``` */ export declare class UpdateBuilder { /* Excluded from this release type: _w */ constructor(tableName: string); /** Add a SET column = value assignment. */ set(column: string, value: ExprInput): this; /** Set the WHERE clause. */ where(condition: ExprInput): this; /** Set the FROM clause (PostgreSQL/Snowflake UPDATE ... FROM). */ from(tableName: string): this; /** Generate SQL string. Defaults to generic dialect. */ toSql(dialect?: string): string; /** Return the Expression AST as a plain JS object. */ build(): any; /** Free the underlying WASM handle. */ free(): void; } export declare function upper(expr: ExprInput): Expr; /** * USE statement (USE database, USE ROLE, USE WAREHOUSE, USE CATALOG, USE SCHEMA) */ declare type Use = { /** * The kind of object (DATABASE, SCHEMA, ROLE, WAREHOUSE, CATALOG, or None for default) */ kind: UseKind | null; /** * The name of the object */ this: Identifier; }; /** * Kind of USE statement */ declare type UseKind = "Database" | "Schema" | "Role" | "Warehouse" | "Catalog" | "SecondaryRoles"; /** * UserDefinedFunction */ declare type UserDefinedFunction = { this: Expression; expressions: Array; wrapped: Expression | null; }; /** * USING DATA clause for data import statements */ declare type UsingData = { this: Expression; }; /** * UsingTemplateProperty */ declare type UsingTemplateProperty = { this: Expression; }; /** * UtcTime */ declare type UtcTime = { this: Expression | null; }; /** * UtcTimestamp */ declare type UtcTimestamp = { this: Expression | null; }; /** * Uuid */ declare type Uuid = { this: Expression | null; name: string | null; is_string: Expression | null; }; /** * Validate SQL syntax and optionally semantics. * * @param sql - The SQL string to validate * @param dialect - The dialect to use for validation * @param options - Validation options * @returns Validation result with errors and warnings * * @example * ```typescript * // Basic syntax validation * const result = validate('SELECT * FROM users', 'postgresql'); * if (!result.valid) { * console.log('Errors:', result.errors); * } * * // With semantic validation * const result = validate('SELECT * FROM users', 'postgresql', { semantic: true }); * // This may also report warnings like "W001: SELECT * is discouraged" * ``` */ export declare function validate(sql: string, dialect?: ValidateDialect | string, options?: ValidationOptions): ValidationResult; /** * Dialect type for validation (matches the main Dialect enum) */ declare type ValidateDialect = 'generic' | 'postgresql' | 'mysql' | 'bigquery' | 'snowflake' | 'duckdb' | 'sqlite' | 'hive' | 'spark' | 'trino' | 'presto' | 'redshift' | 'tsql' | 'oracle' | 'clickhouse' | 'databricks'; /** * Validate SQL against a database schema. */ export declare function validateWithSchema(sql: string, schema: Schema, dialect?: string, options?: SchemaValidationOptions): ValidationResult; /** * A single validation error or warning. */ export declare interface ValidationError { /** The error/warning message */ message: string; /** Line number where the error occurred (1-based) */ line?: number; /** Column number where the error occurred (1-based) */ column?: number; /** Severity of the validation issue */ severity: ValidationSeverity; /** Error code (e.g., "E001", "W001") */ code: string; /** Start byte offset of the error range */ start?: number; /** End byte offset of the error range (exclusive) */ end?: number; } /** * Options for SQL validation. */ export declare interface ValidationOptions { /** * Enable semantic validation in addition to syntax checking. * Semantic validation checks for issues like SELECT * usage, * aggregate functions without GROUP BY, etc. * @default false */ semantic?: boolean; /** * Enable strict syntax validation for non-canonical forms that are otherwise * parsed permissively for compatibility (for example, trailing commas before * clause boundaries like `SELECT a, FROM t`). * @default false */ strictSyntax?: boolean; /** * Enable dialect-specific validation rules. * When true, additional dialect-specific rules are applied. * @default false */ dialectStrict?: boolean; } /** * Result of validating SQL. */ export declare interface ValidationResult { /** Whether the SQL is valid (no errors, warnings are allowed) */ valid: boolean; /** List of validation errors and warnings */ errors: ValidationError[]; } /** * Validation types for SQL syntax and semantic validation. */ /** * Severity level for validation issues. */ export declare type ValidationSeverity = 'error' | 'warning'; /** * Validation severity constants for convenience. */ export declare const ValidationSeverity: { Error: "error"; Warning: "warning"; }; /** * FIRST_VALUE / LAST_VALUE function */ declare type ValueFunc = { this: Expression; /** * None = not specified, Some(true) = IGNORE NULLS, Some(false) = RESPECT NULLS */ ignore_nulls?: boolean | null; /** * ORDER BY inside the function parens (e.g., DuckDB: LAST_VALUE(x ORDER BY x)) */ order_by?: Array; }; /** * VALUES table constructor: VALUES (1, 'a'), (2, 'b') */ declare type Values = { /** * The rows of values */ expressions: Array; /** * Optional alias for the table */ alias: Identifier | null; /** * Optional column aliases: AS t(c1, c2) */ column_aliases: Array; }; /** * Var - Simple variable reference (for SQL variables, keywords as values) */ declare type Var = { this: string; }; /** * Variable argument function */ declare type VarArgFunc = { expressions: Array; /** * Original function name for round-trip preservation (e.g., COALESCE vs IFNULL) */ original_name?: string | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Variadic - represents VARIADIC prefix on function arguments (PostgreSQL) */ declare type Variadic = { this: Expression; }; /** * VarMap */ declare type VarMap = { keys: Array; values: Array; }; /** * VectorSearch */ declare type VectorSearch = { this: Expression; column_to_search: Expression | null; query_table: Expression | null; query_column_to_search: Expression | null; top_k: Expression | null; distance_type: Expression | null; options: Array; }; /** * Version */ declare type Version = { this: Expression; kind: string; expression: Expression | null; }; /** * ViewAttributeProperty */ declare type ViewAttributeProperty = { this: Expression; }; /** * View column definition with optional COMMENT and OPTIONS (BigQuery) */ declare type ViewColumn = { name: Identifier; comment: string | null; /** * BigQuery: OPTIONS (key=value, ...) on column */ options?: Array; }; /** * Visitor callback function type */ declare type VisitorCallback = (node: Expression, parent: Expression | null, key: string | null, index: number | null) => T; /** * Visitor configuration with callbacks for specific node types */ declare type VisitorConfig = { [K in ExpressionType]?: VisitorCallback; } & { /** Called before visiting any node */ enter?: VisitorCallback; /** Called after visiting any node and its children */ leave?: VisitorCallback; }; /** * Context passed to visitors */ declare interface VisitorContext { /** Stop traversal completely */ stop(): void; /** Skip visiting children of current node */ skip(): void; /** Path to current node */ path: NodePath; } /** * VolatileProperty */ declare type VolatileProperty = { this: Expression | null; }; /** * Walk an AST tree, calling visitor callbacks for each node * * @example * ```typescript * walk(ast, { * column: (node) => console.log('Found column:', getExprType(node)), * enter: (node) => console.log('Entering:', getExprType(node)), * leave: (node) => console.log('Leaving:', getExprType(node)), * }); * ``` */ export declare function walk(node: Expression, visitor: VisitorConfig, parent?: Expression | null, key?: string | null, index?: number | null): void; /** * An array of (column, value) assignments for UPDATE SET / MERGE clauses. */ declare class WasmAssignmentArray { free(): void; [Symbol.dispose](): void; /** * Get the number of assignments. */ len(): number; /** * Create an empty assignment array. */ constructor(); /** * Add a column = value assignment. */ push(column: string, value: WasmExpr): void; } /** * Fluent builder for CASE expressions. */ declare class WasmCaseBuilder { free(): void; [Symbol.dispose](): void; /** * Build the CASE expression and return a WasmExpr. */ build_expr(): WasmExpr; /** * Set the ELSE result. */ else_(result: WasmExpr): void; /** * Create a new searched CASE builder (CASE WHEN ... THEN ...). */ constructor(); /** * Generate SQL string for the given dialect. */ to_sql(dialect: string): string; /** * Add a WHEN condition THEN result branch. */ when(condition: WasmExpr, result: WasmExpr): void; } /** * Fluent builder for DELETE FROM statements. */ declare class WasmDeleteBuilder { free(): void; [Symbol.dispose](): void; /** * Return the Expression AST as a JSON value. */ build(): any; /** * Create a new DELETE FROM builder for the given table. */ constructor(table_name: string); /** * Generate SQL string for the given dialect. */ to_sql(dialect: string): string; /** * Set the WHERE clause. */ where_expr(condition: WasmExpr): void; } /** * A SQL expression handle. Methods use `&self` (cloning internally) so JS * can reuse references. */ declare class WasmExpr { private constructor(); free(): void; [Symbol.dispose](): void; /** * Produce `self + other`. */ add(other: WasmExpr): WasmExpr; /** * Produce `self AS name`. */ alias(name: string): WasmExpr; /** * Produce `self AND other`. */ and(other: WasmExpr): WasmExpr; /** * Wrap with ascending sort order. */ asc(): WasmExpr; /** * Produce `self BETWEEN low AND high`. */ between(low: WasmExpr, high: WasmExpr): WasmExpr; /** * Produce `CAST(self AS type)`. */ cast(to: string): WasmExpr; /** * Wrap with descending sort order. */ desc(): WasmExpr; /** * Produce `self / other`. */ div(other: WasmExpr): WasmExpr; /** * Produce `self = other`. */ eq(other: WasmExpr): WasmExpr; /** * Produce `self > other`. */ gt(other: WasmExpr): WasmExpr; /** * Produce `self >= other`. */ gte(other: WasmExpr): WasmExpr; /** * Produce `self ILIKE pattern`. */ ilike(pattern: WasmExpr): WasmExpr; /** * Produce `self IN (values...)`. */ in_list(values: WasmExprArray): WasmExpr; /** * Produce `self IS NOT NULL`. */ is_not_null(): WasmExpr; /** * Produce `self IS NULL`. */ is_null(): WasmExpr; /** * Produce `self LIKE pattern`. */ like(pattern: WasmExpr): WasmExpr; /** * Produce `self < other`. */ lt(other: WasmExpr): WasmExpr; /** * Produce `self <= other`. */ lte(other: WasmExpr): WasmExpr; /** * Produce `self * other`. */ mul(other: WasmExpr): WasmExpr; /** * Produce `self <> other`. */ neq(other: WasmExpr): WasmExpr; /** * Produce `NOT self`. */ not(): WasmExpr; /** * Produce `self NOT IN (values...)`. */ not_in(values: WasmExprArray): WasmExpr; /** * Produce `self OR other`. */ or(other: WasmExpr): WasmExpr; /** * Produce `REGEXP_LIKE(self, pattern)`. */ rlike(pattern: WasmExpr): WasmExpr; /** * Produce `self - other`. */ sub(other: WasmExpr): WasmExpr; /** * Return the expression AST as a JSON value. */ to_json(): any; /** * Generate SQL string for the given dialect. */ to_sql(dialect: string): string; /** * Produce `self XOR other`. */ xor(other: WasmExpr): WasmExpr; } /** * An array of expressions, used to pass lists across the WASM boundary. */ declare class WasmExprArray { free(): void; [Symbol.dispose](): void; /** * Get the number of expressions. */ len(): number; /** * Create an empty expression array. */ constructor(); /** * Push an expression. */ push(expr: WasmExpr): void; /** * Push a column reference by name. */ push_col(name: string): void; /** * Push a float literal. */ push_float(value: number): void; /** * Push an integer literal. */ push_int(value: number): void; /** * Push a star (*) expression. */ push_star(): void; /** * Push a string literal. */ push_str(value: string): void; } /** * Fluent builder for INSERT INTO statements. */ declare class WasmInsertBuilder { free(): void; [Symbol.dispose](): void; /** * Return the Expression AST as a JSON value. */ build(): any; /** * Set the target column names. */ columns(cols: string[]): void; /** * Create a new INSERT INTO builder for the given table. */ constructor(table_name: string); /** * Set the source query for INSERT ... SELECT. */ query(query: WasmSelectBuilder): void; /** * Generate SQL string for the given dialect. */ to_sql(dialect: string): string; /** * Append a row of values. */ values(vals: WasmExprArray): void; } /** * Fluent builder for MERGE INTO statements. */ declare class WasmMergeBuilder { free(): void; [Symbol.dispose](): void; /** * Return the Expression AST as a JSON value. */ build(): any; /** * Create a new MERGE INTO builder for the given target table. */ constructor(target: string); /** * Generate SQL string for the given dialect. */ to_sql(dialect: string): string; /** * Set the source table and ON join condition. */ using(source: string, on: WasmExpr): void; /** * Add a WHEN MATCHED THEN DELETE clause. */ when_matched_delete(): void; /** * Add a WHEN MATCHED THEN UPDATE SET clause. */ when_matched_update(assignments: WasmAssignmentArray): void; /** * Add a WHEN NOT MATCHED THEN INSERT clause. */ when_not_matched_insert(columns: string[], values: WasmExprArray): void; } /** * Fluent builder for SELECT statements. * * Uses `Option` internally. Each method takes/puts the builder * using the `&mut self` pattern required by wasm_bindgen. */ declare class WasmSelectBuilder { free(): void; [Symbol.dispose](): void; /** * Return the Expression AST as a JSON value. */ build(): any; /** * Add a CROSS JOIN. */ cross_join(table: string): void; /** * Convert to CREATE TABLE AS SELECT. Returns the AST JSON. */ ctas(table_name: string): any; /** * Convert to CREATE TABLE AS SELECT and return generated SQL. */ ctas_sql(table_name: string, dialect: string): string; /** * Enable DISTINCT. */ distinct(): void; /** * Combine with EXCEPT. Consumes both builders. */ except_(other: WasmSelectBuilder): WasmSetOpBuilder; /** * Add a FOR UPDATE locking clause. */ for_update(): void; /** * Set the FROM clause to a table by name. */ from(table: string): void; /** * Set the FROM clause to an arbitrary expression. */ from_expr(expr: WasmExpr): void; /** * Set the GROUP BY clause. */ group_by_cols(cols: WasmExprArray): void; /** * Set the HAVING clause. */ having(condition: WasmExpr): void; /** * Add a query hint. */ hint(hint_text: string): void; /** * Combine with INTERSECT. Consumes both builders. */ intersect(other: WasmSelectBuilder): WasmSetOpBuilder; /** * Add an INNER JOIN. */ join(table: string, on: WasmExpr): void; /** * Add a LATERAL VIEW clause (Hive/Spark). */ lateral_view(func_expr: WasmExpr, table_alias: string, col_aliases: string[]): void; /** * Add a LEFT JOIN. */ left_join(table: string, on: WasmExpr): void; /** * Set the LIMIT clause. */ limit(count: number): void; /** * Create a new, empty SELECT builder. */ constructor(); /** * Set the OFFSET clause. */ offset(count: number): void; /** * Set the ORDER BY clause. */ order_by_exprs(exprs: WasmExprArray): void; /** * Set the QUALIFY clause. */ qualify(condition: WasmExpr): void; /** * Add a RIGHT JOIN. */ right_join(table: string, on: WasmExpr): void; /** * Add a column by name to the SELECT list. */ select_col(name: string): void; /** * Add a single expression to the SELECT list. */ select_expr(expr: WasmExpr): void; /** * Add multiple expressions to the SELECT list. */ select_exprs(exprs: WasmExprArray): void; /** * Add a star (*) to the SELECT list. */ select_star(): void; /** * Set the SORT BY clause (Hive/Spark). */ sort_by_exprs(exprs: WasmExprArray): void; /** * Generate SQL string for the given dialect. */ to_sql(dialect: string): string; /** * Combine with UNION (duplicate elimination). Consumes both builders. */ union(other: WasmSelectBuilder): WasmSetOpBuilder; /** * Combine with UNION ALL (keep duplicates). Consumes both builders. */ union_all(other: WasmSelectBuilder): WasmSetOpBuilder; /** * Set the WHERE clause to a condition expression. */ where_expr(condition: WasmExpr): void; /** * Set the WHERE clause by parsing a raw SQL condition string. */ where_sql(sql: string): void; /** * Add a named WINDOW clause definition. */ window(name: string, def: WasmWindowDefBuilder): void; } /** * Fluent builder for set operations (UNION, INTERSECT, EXCEPT). */ declare class WasmSetOpBuilder { private constructor(); free(): void; [Symbol.dispose](): void; /** * Return the Expression AST as a JSON value. */ build(): any; /** * Set the LIMIT clause. */ limit(count: number): void; /** * Set the OFFSET clause. */ offset(count: number): void; /** * Set the ORDER BY clause. */ order_by_exprs(exprs: WasmExprArray): void; /** * Generate SQL string for the given dialect. */ to_sql(dialect: string): string; } /** * Fluent builder for UPDATE statements. */ declare class WasmUpdateBuilder { free(): void; [Symbol.dispose](): void; /** * Return the Expression AST as a JSON value. */ build(): any; /** * Set the FROM clause (PostgreSQL/Snowflake UPDATE ... FROM). */ from(table: string): void; /** * Create a new UPDATE builder for the given table. */ constructor(table_name: string); /** * Add a SET column = value assignment. */ set(column: string, value: WasmExpr): void; /** * Generate SQL string for the given dialect. */ to_sql(dialect: string): string; /** * Set the WHERE clause. */ where_expr(condition: WasmExpr): void; } /** * Builder for named WINDOW clause definitions. */ declare class WasmWindowDefBuilder { free(): void; [Symbol.dispose](): void; /** * Create a new, empty window definition builder. */ constructor(); /** * Set the ORDER BY expressions. */ order_by(exprs: WasmExprArray): void; /** * Set the PARTITION BY expressions. */ partition_by(exprs: WasmExprArray): void; } /** * WatermarkColumnConstraint */ declare type WatermarkColumnConstraint = { this: Expression; expression: Expression; }; /** * Week */ declare type Week = { this: Expression; mode: Expression | null; }; /** * When */ declare type When = { matched: Expression | null; source: Expression | null; condition: Expression | null; then: Expression; }; /** * Wraps around one or more WHEN [NOT] MATCHED [...] clauses. */ declare type Whens = { expressions: Array; }; /** * Represent a WHERE clause containing a boolean filter predicate. */ declare type Where = { /** * The filter predicate expression. */ this: Expression; }; /** * WidthBucket */ declare type WidthBucket = { this: Expression; min_value: Expression | null; max_value: Expression | null; num_buckets: Expression | null; threshold: Expression | null; }; /** * Builder for named WINDOW clause definitions. * * Used with `SelectBuilder.window()` to define reusable window specifications. * * @example * ```typescript * const w = new WindowDefBuilder() * .partitionBy('dept') * .orderBy(col('salary').desc()); * const sql = select('id').from('t').window('w', w).toSql(); * ``` */ export declare class WindowDefBuilder { /* Excluded from this release type: _w */ constructor(); /** Set the PARTITION BY expressions. */ partitionBy(...exprs: ExprInput[]): this; /** Set the ORDER BY expressions. */ orderBy(...exprs: ExprInput[]): this; /** Free the underlying WASM handle. */ free(): void; } /** * Union of all window function expression types * Note: Some window functions use null types internally, so we use a simplified union */ declare type WindowExpression = ExpressionByType<'n_tile'> | ExpressionByType<'lead'> | ExpressionByType<'lag'> | ExpressionByType<'first_value'> | ExpressionByType<'last_value'> | ExpressionByType<'nth_value'> | ExpressionByType<'percentile_cont'> | ExpressionByType<'percentile_disc'>; /** * Window frame */ declare type WindowFrame = { kind: WindowFrameKind; start: WindowFrameBound; end: WindowFrameBound | null; exclude: WindowFrameExclude | null; /** * Original text of the frame kind keyword (preserves input case, e.g. "range") */ kind_text?: string | null; /** * Original text of the start bound side keyword (e.g. "preceding") */ start_side_text?: string | null; /** * Original text of the end bound side keyword */ end_side_text?: string | null; }; declare type WindowFrameBound = "CurrentRow" | "UnboundedPreceding" | "UnboundedFollowing" | { "Preceding": Expression; } | { "Following": Expression; } | "BarePreceding" | "BareFollowing" | { "Value": Expression; }; /** * EXCLUDE clause for window frames */ declare type WindowFrameExclude = "CurrentRow" | "Group" | "Ties" | "NoOthers"; declare type WindowFrameKind = "Rows" | "Range" | "Groups"; /** * Represent a window function call with its OVER clause. * * The inner `this` expression is typically a window-specific expression * (e.g. `RowNumber`, `Rank`, `Lead`) or an aggregate used as a window * function. The `over` field carries the PARTITION BY, ORDER BY, and * frame specification. */ declare type WindowFunction = { /** * The function expression (e.g. ROW_NUMBER(), SUM(amount)). */ this: Expression; /** * The OVER clause defining the window partitioning, ordering, and frame. */ over: Over; /** * Oracle KEEP clause: KEEP (DENSE_RANK FIRST|LAST ORDER BY ...) */ keep?: Keep | null; /** * Inferred data type from type annotation */ inferred_type?: DataType | null; }; /** * Window specification */ declare type WindowSpec = { partition_by: Array; order_by: Array; frame: WindowFrame | null; }; /** * Represent a WITH clause containing one or more Common Table Expressions (CTEs). * * When `recursive` is true, the clause is `WITH RECURSIVE`, enabling CTEs * that reference themselves. Each CTE is defined in the `ctes` vector and * can be referenced by name in subsequent CTEs and in the main query body. */ declare type With = { /** * The list of CTE definitions, in order. */ ctes: Array; /** * Whether the WITH RECURSIVE keyword was used. */ recursive: boolean; /** * Leading comments before the statement */ leading_comments: Array; /** * SEARCH/CYCLE clause for recursive CTEs (PostgreSQL) */ search?: Expression | null; }; /** * WithDataProperty */ declare type WithDataProperty = { no: Expression | null; statistics: Expression | null; }; /** * WithFill */ declare type WithFill = { from_: Expression | null; to: Expression | null; step: Expression | null; staleness: Expression | null; interpolate: Expression | null; }; /** * WITHIN GROUP clause (for ordered-set aggregate functions) */ declare type WithinGroup = { /** * The aggregate function (LISTAGG, PERCENTILE_CONT, etc.) */ this: Expression; /** * The ORDER BY clause within the group */ order_by: Array; }; /** * WithJournalTableProperty */ declare type WithJournalTableProperty = { this: Expression; }; /** * WithOperator */ declare type WithOperator = { this: Expression; op: string; }; /** * WithProcedureOptions */ declare type WithProcedureOptions = { expressions: Array; }; /** * WithSchemaBindingProperty */ declare type WithSchemaBindingProperty = { this: Expression; }; /** * WithSystemVersioningProperty */ declare type WithSystemVersioningProperty = { on: Expression | null; this: Expression | null; data_consistency: Expression | null; retention_period: Expression | null; with_: Expression | null; }; /** * WithTableHint */ declare type WithTableHint = { expressions: Array; }; /** * XMLElement */ declare type XMLElement = { this: Expression; expressions: Array; evalname: Expression | null; }; /** * XMLGet */ declare type XMLGet = { this: Expression; expression: Expression; instance: Expression | null; }; /** * XMLKeyValueOption */ declare type XMLKeyValueOption = { this: Expression; expression: Expression | null; }; /** * XML Namespace declaration */ declare type XmlNamespace = { this: Expression; alias: Identifier | null; }; /** * XMLTable */ declare type XMLTable = { this: Expression; namespaces: Expression | null; passing: Expression | null; columns: Array; by_ref: Expression | null; }; /** * Xor */ declare type Xor = { this: Expression | null; expression: Expression | null; expressions: Array; }; /** * Zipf */ declare type Zipf = { this: Expression; elementcount: Expression | null; gen: Expression | null; }; export { }