data-finder-ts 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +17 -55
  2. package/dist/chunk-BGEX377Q.js +230 -0
  3. package/dist/chunk-BGEX377Q.js.map +1 -0
  4. package/dist/chunk-BKPWV3OF.js +962 -0
  5. package/dist/chunk-BKPWV3OF.js.map +1 -0
  6. package/dist/{chunk-EYXBYV2X.js → chunk-GPHWC533.js} +2 -2
  7. package/dist/chunk-KAK75RVS.js +198 -0
  8. package/dist/chunk-KAK75RVS.js.map +1 -0
  9. package/dist/chunk-MGEL5RWM.js +628 -0
  10. package/dist/chunk-MGEL5RWM.js.map +1 -0
  11. package/dist/chunk-PF6EJZHB.js +1015 -0
  12. package/dist/chunk-PF6EJZHB.js.map +1 -0
  13. package/dist/datafinder/attribute.cjs +595 -18
  14. package/dist/datafinder/attribute.cjs.map +1 -1
  15. package/dist/datafinder/attribute.d.cts +73 -10
  16. package/dist/datafinder/attribute.d.ts +73 -10
  17. package/dist/datafinder/attribute.js +2 -2
  18. package/dist/datafinder/runner.cjs +1589 -288
  19. package/dist/datafinder/runner.cjs.map +1 -1
  20. package/dist/datafinder/runner.d.cts +41 -7
  21. package/dist/datafinder/runner.d.ts +41 -7
  22. package/dist/datafinder/runner.js +12 -6
  23. package/dist/datafinder/sql-generator.cjs +1484 -281
  24. package/dist/datafinder/sql-generator.cjs.map +1 -1
  25. package/dist/datafinder/sql-generator.d.cts +19 -14
  26. package/dist/datafinder/sql-generator.d.ts +19 -14
  27. package/dist/datafinder/sql-generator.js +9 -7
  28. package/dist/datafinder/typed-attributes.cjs +856 -93
  29. package/dist/datafinder/typed-attributes.cjs.map +1 -1
  30. package/dist/datafinder/typed-attributes.d.cts +3 -135
  31. package/dist/datafinder/typed-attributes.d.ts +3 -135
  32. package/dist/datafinder/typed-attributes.js +3 -3
  33. package/dist/dialect-CogGPm_y.d.cts +38 -0
  34. package/dist/dialect-aaG1bDi5.d.ts +38 -0
  35. package/dist/index.cjs +2080 -480
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.d.cts +119 -14
  38. package/dist/index.d.ts +119 -14
  39. package/dist/index.js +362 -12
  40. package/dist/index.js.map +1 -1
  41. package/dist/model/milestoning.cjs +529 -0
  42. package/dist/model/milestoning.cjs.map +1 -1
  43. package/dist/model/milestoning.js +2 -2
  44. package/dist/model/relational.cjs +608 -12
  45. package/dist/model/relational.cjs.map +1 -1
  46. package/dist/model/relational.d.cts +456 -47
  47. package/dist/model/relational.d.ts +456 -47
  48. package/dist/model/relational.js +61 -3
  49. package/dist/typed-attributes-CUTf_6Ru.d.ts +328 -0
  50. package/dist/typed-attributes-CdWXq_78.d.cts +328 -0
  51. package/package.json +5 -2
  52. package/dist/chunk-3SSWFES4.js +0 -448
  53. package/dist/chunk-3SSWFES4.js.map +0 -1
  54. package/dist/chunk-5K2Z3YDY.js +0 -393
  55. package/dist/chunk-5K2Z3YDY.js.map +0 -1
  56. package/dist/chunk-6QTCGJWX.js +0 -98
  57. package/dist/chunk-6QTCGJWX.js.map +0 -1
  58. package/dist/chunk-DFYZVBII.js +0 -652
  59. package/dist/chunk-DFYZVBII.js.map +0 -1
  60. package/dist/chunk-V647VNMY.js +0 -135
  61. package/dist/chunk-V647VNMY.js.map +0 -1
  62. /package/dist/{chunk-EYXBYV2X.js.map → chunk-GPHWC533.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/model/relational.ts","../src/datafinder/attribute.ts","../src/datafinder/finder-registry.ts","../src/datafinder/typed-attributes.ts","../src/model/milestoning.ts","../src/datafinder/finder.ts","../src/datafinder/sql-generator.ts","../src/datafinder/runner.ts"],"sourcesContent":["export * from './datafinder/index';\nexport * from './model/relational';\nexport * from './model/milestoning';\n","export enum ComparisonOperator {\n EQUAL = 'EQUAL',\n NOT_EQUAL = 'NOT_EQUAL',\n LESS_THAN = 'LESS_THAN',\n GREATER_THAN = 'GREATER_THAN',\n LESS_THAN_OR_EQUAL_TO = 'LESS_THAN_OR_EQUAL_TO',\n GREATER_THAN_OR_EQUAL_TO = 'GREATER_THAN_OR_EQUAL_TO',\n LIKE = 'LIKE',\n NOT_LIKE = 'NOT_LIKE',\n}\n\nexport enum LogicalOperator {\n AND = 'AND',\n OR = 'OR',\n}\n\nexport enum AggregateOperator {\n COUNT = 'COUNT',\n SUM = 'SUM',\n MIN = 'MIN',\n MAX = 'MAX',\n AVERAGE = 'AVERAGE',\n}\n\nexport enum ScalarFunction {\n ABS = 'ABS',\n CEILING = 'CEILING',\n FLOOR = 'FLOOR',\n MOD = 'MOD',\n POWER = 'POWER',\n SQRT = 'SQRT',\n ROUND = 'ROUND',\n UPPER = 'UPPER',\n LOWER = 'LOWER',\n TRIM = 'TRIM',\n LTRIM = 'LTRIM',\n RTRIM = 'RTRIM',\n LENGTH = 'LENGTH',\n REVERSE = 'REVERSE',\n LEFT = 'LEFT',\n RIGHT = 'RIGHT',\n REPEAT = 'REPEAT',\n REPLACE = 'REPLACE',\n SUBSTRING = 'SUBSTRING',\n}\n\nexport enum DatePart {\n YEAR = 'YEAR',\n MONTH = 'MONTH',\n DAY = 'DAY',\n HOUR = 'HOUR',\n MINUTE = 'MINUTE',\n SECOND = 'SECOND',\n QUARTER = 'QUARTER',\n WEEK = 'WEEK',\n DOW = 'DOW',\n}\n\nexport enum SortDirection {\n ASC = 'ASC',\n DESC = 'DESC',\n}\n\nexport abstract class RelationalOperationElement {}\n\nexport abstract class Operation extends RelationalOperationElement {\n andOp(other: RelationalOperationElement): Operation {\n return new LogicalOperation(this, LogicalOperator.AND, other);\n }\n}\n\nexport class NoOperation extends Operation {\n andOp(other: RelationalOperationElement): Operation {\n return other as Operation;\n }\n}\n\nexport abstract class ConstantOperation extends RelationalOperationElement {}\n\nexport class IntegerConstantOperation extends ConstantOperation {\n constructor(readonly value: number) { super(); }\n}\n\nexport class FloatConstantOperation extends ConstantOperation {\n constructor(readonly value: number) { super(); }\n}\n\nexport class StringConstantOperation extends ConstantOperation {\n constructor(readonly value: string) { super(); }\n}\n\nexport class DateConstantOperation extends ConstantOperation {\n constructor(readonly value: Date) { super(); }\n}\n\nexport class DateTimeConstantOperation extends ConstantOperation {\n constructor(readonly value: Date) { super(); }\n}\n\nexport class DecimalConstantOperation extends ConstantOperation {\n constructor(readonly value: number) { super(); }\n}\n\nexport class BooleanConstantOperation extends ConstantOperation {\n constructor(readonly value: boolean) { super(); }\n}\n\nexport abstract class UnaryOperation extends Operation {\n constructor(readonly element: RelationalOperationElement) { super(); }\n}\n\nexport abstract class BinaryOperation extends Operation {\n constructor(\n readonly left: RelationalOperationElement,\n readonly right: RelationalOperationElement,\n ) { super(); }\n}\n\nexport class IsNullOperation extends UnaryOperation {}\n\nexport class IsNotNullOperation extends UnaryOperation {}\n\nexport class ComparisonOperation extends BinaryOperation {\n constructor(\n left: RelationalOperationElement,\n readonly operator: ComparisonOperator,\n right: RelationalOperationElement,\n ) { super(left, right); }\n}\n\nexport class LogicalOperation extends BinaryOperation {\n constructor(\n left: RelationalOperationElement,\n readonly operator: LogicalOperator,\n right: RelationalOperationElement,\n ) { super(left, right); }\n}\n\nexport class WindowSpecification {\n constructor(\n readonly partitionBy: RelationalOperationElement[] = [],\n readonly orderBy: SortOperation[] = [],\n ) {}\n}\n\nexport class AggregateOperation extends UnaryOperation {\n constructor(\n element: RelationalOperationElement,\n readonly operator: AggregateOperator,\n readonly displayName?: string,\n readonly window?: WindowSpecification,\n ) { super(element); }\n\n over(partitionBy?: RelationalOperationElement[], orderBy?: SortOperation[]): AggregateOperation {\n return new AggregateOperation(this.element, this.operator, this.displayName,\n new WindowSpecification(partitionBy ?? [], orderBy ?? []));\n }\n}\n\nexport enum WindowFunction {\n ROW_NUMBER = 'ROW_NUMBER',\n RANK = 'RANK',\n DENSE_RANK = 'DENSE_RANK',\n NTILE = 'NTILE',\n LAG = 'LAG',\n LEAD = 'LEAD',\n FIRST_VALUE = 'FIRST_VALUE',\n LAST_VALUE = 'LAST_VALUE',\n CUME_DIST = 'CUME_DIST',\n PERCENT_RANK = 'PERCENT_RANK',\n}\n\nexport class WindowFunctionOperation extends UnaryOperation {\n constructor(\n element: RelationalOperationElement | null,\n readonly func: WindowFunction,\n readonly displayName?: string,\n readonly secondArg?: number,\n readonly extraArgs: (string | number)[] = [],\n readonly window?: WindowSpecification,\n ) { super(element as RelationalOperationElement); }\n\n over(partitionBy?: RelationalOperationElement[], orderBy?: SortOperation[]): WindowFunctionOperation {\n return new WindowFunctionOperation(this.element, this.func, this.displayName, this.secondArg,\n [...this.extraArgs], new WindowSpecification(partitionBy ?? [], orderBy ?? []));\n }\n}\n\nexport class ScalarFunctionOperation extends UnaryOperation {\n constructor(\n element: RelationalOperationElement,\n readonly func: ScalarFunction,\n readonly displayName?: string,\n readonly secondArg?: number,\n readonly extraArgs: (string | number)[] = [],\n ) { super(element); }\n}\n\nexport class DateExtractOperation extends UnaryOperation {\n constructor(\n element: RelationalOperationElement,\n readonly part: DatePart,\n readonly displayName?: string,\n ) { super(element); }\n}\n\nexport class DateArithmeticOperation extends UnaryOperation {\n constructor(\n element: RelationalOperationElement,\n readonly n: number,\n readonly unit: DatePart,\n readonly isAdd: boolean = true,\n readonly displayName?: string,\n ) { super(element); }\n}\n\nexport class DateDiffOperation extends UnaryOperation {\n constructor(\n element: RelationalOperationElement,\n readonly other: Date,\n readonly unit: DatePart,\n readonly displayName?: string,\n ) { super(element); }\n}\n\nexport class Column extends RelationalOperationElement {\n table?: Table;\n\n constructor(\n readonly name: string,\n readonly type: string,\n readonly owner?: string,\n readonly primaryKey: boolean = false,\n ) { super(); }\n}\n\nexport class ForeignKey {\n constructor(readonly column: Column, readonly references: Column) {}\n}\n\nexport abstract class DataStore {\n readonly schemas: Schema[] = [];\n\n constructor(readonly name: string) {}\n\n abstract namespace(schemaName: string): string;\n}\n\nexport class Database extends DataStore {\n constructor(name: string, readonly location?: string) { super(name); }\n\n namespace(schemaName: string): string { return schemaName; }\n}\n\nexport class DataCatalog extends DataStore {\n constructor(name: string) { super(name); }\n\n namespace(schemaName: string): string { return `${this.name}.${schemaName}`; }\n}\n\nexport class Schema {\n readonly tables: Table[] = [];\n\n constructor(readonly name: string, readonly datastore?: DataStore) {\n datastore?.schemas.push(this);\n }\n}\n\nexport class Table {\n private readonly _columnsByName: Map<string, Column> = new Map();\n readonly foreignKeys: ForeignKey[] = [];\n\n constructor(readonly name: string, columns: Column[], readonly schema?: Schema) {\n for (const col of columns) {\n if (this._columnsByName.has(col.name)) {\n throw new Error(`Duplicate column name '${col.name}' in table '${name}'`);\n }\n this._columnsByName.set(col.name, col);\n col.table = this;\n }\n schema?.tables.push(this);\n }\n\n get columns(): Column[] {\n return Array.from(this._columnsByName.values());\n }\n\n get qualifiedName(): string {\n if (!this.schema) return this.name;\n if (!this.schema.datastore) return `${this.schema.name}.${this.name}`;\n return `${this.schema.datastore.namespace(this.schema.name)}.${this.name}`;\n }\n}\n\nexport class JoinOperation {\n filter?: RelationalOperationElement;\n\n constructor(\n readonly name: string,\n readonly target: Table,\n readonly left: Column,\n readonly right: Column,\n filter?: RelationalOperationElement,\n ) {\n this.filter = filter;\n }\n}\n\nexport class JoinTreeNodeOperation {\n constructor(\n readonly join: JoinOperation,\n readonly parent?: JoinTreeNodeOperation,\n ) {}\n}\n\nexport class ColumnWithJoin extends RelationalOperationElement {\n constructor(\n readonly column: Column,\n readonly parent?: JoinTreeNodeOperation,\n ) { super(); }\n}\n\nexport class SortOperation {\n constructor(\n readonly column: ColumnWithJoin,\n readonly direction: SortDirection,\n ) {}\n}\n\nexport class CountAllOperation extends RelationalOperationElement {\n constructor(readonly table: string) { super(); }\n}\n","import {\n Column,\n AggregateOperation,\n AggregateOperator,\n ColumnWithJoin,\n SortOperation,\n SortDirection,\n IsNullOperation,\n IsNotNullOperation,\n JoinTreeNodeOperation,\n WindowFunction,\n WindowFunctionOperation,\n WindowSpecification,\n} from '../model/relational';\n\nexport abstract class Attribute {\n private readonly _displayName: string;\n private readonly _column: Column;\n private readonly _owner: string;\n private readonly _parent?: JoinTreeNodeOperation;\n\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n ) {\n this._displayName = displayName;\n this._column = new Column(columnName, columnDbType, owner);\n this._owner = owner;\n this._parent = parent;\n }\n\n column(): Column { return this._column; }\n owner(): string { return this._owner; }\n parent(): JoinTreeNodeOperation | undefined { return this._parent; }\n displayName(): string { return this._displayName; }\n\n cwj(): ColumnWithJoin {\n return new ColumnWithJoin(this._column, this._parent);\n }\n\n count(): AggregateOperation {\n return new AggregateOperation(\n new ColumnWithJoin(this._column, this._parent),\n AggregateOperator.COUNT,\n this._displayName + ' Count',\n );\n }\n\n ascending(): SortOperation {\n return new SortOperation(new ColumnWithJoin(this._column, this._parent), SortDirection.ASC);\n }\n\n descending(): SortOperation {\n return new SortOperation(new ColumnWithJoin(this._column, this._parent), SortDirection.DESC);\n }\n\n isNull(): IsNullOperation {\n return new IsNullOperation(new ColumnWithJoin(this._column, this._parent));\n }\n\n isNotNull(): IsNotNullOperation {\n return new IsNotNullOperation(new ColumnWithJoin(this._column, this._parent));\n }\n\n private _windowSpec(\n partitionBy?: ColumnWithJoin | ColumnWithJoin[],\n orderBy?: SortOperation | SortOperation[],\n ): WindowSpecification {\n const pb = partitionBy === undefined ? [] : Array.isArray(partitionBy) ? partitionBy : [partitionBy];\n const ob = orderBy === undefined ? [] : Array.isArray(orderBy) ? orderBy : [orderBy];\n return new WindowSpecification(pb, ob);\n }\n\n rank(opts: {\n method?: 'min' | 'dense' | 'first';\n pct?: boolean;\n partitionBy?: ColumnWithJoin | ColumnWithJoin[];\n orderBy?: SortOperation | SortOperation[];\n } = {}): WindowFunctionOperation {\n const { method = 'min', pct = false, partitionBy, orderBy } = opts;\n let func: WindowFunction;\n let name: string;\n if (pct) {\n if (method === 'max' as string) { func = WindowFunction.CUME_DIST; name = 'Cume Dist'; }\n else { func = WindowFunction.PERCENT_RANK; name = 'Percent Rank'; }\n } else if (method === 'first') { func = WindowFunction.ROW_NUMBER; name = 'Row Number'; }\n else if (method === 'dense') { func = WindowFunction.DENSE_RANK; name = 'Dense Rank'; }\n else { func = WindowFunction.RANK; name = 'Rank'; }\n return new WindowFunctionOperation(null, func, name, undefined, [], this._windowSpec(partitionBy, orderBy));\n }\n\n qcut(buckets: number, opts: {\n partitionBy?: ColumnWithJoin | ColumnWithJoin[];\n orderBy?: SortOperation | SortOperation[];\n } = {}): WindowFunctionOperation {\n return new WindowFunctionOperation(null, WindowFunction.NTILE, 'Quantile', buckets, [],\n this._windowSpec(opts.partitionBy, opts.orderBy));\n }\n\n shift(periods = 1, opts: {\n fillValue?: string | number;\n partitionBy?: ColumnWithJoin | ColumnWithJoin[];\n orderBy?: SortOperation | SortOperation[];\n } = {}): WindowFunctionOperation {\n const extraArgs: (string | number)[] = opts.fillValue !== undefined ? [opts.fillValue] : [];\n const func = periods >= 0 ? WindowFunction.LAG : WindowFunction.LEAD;\n const label = periods >= 0 ? 'Lag' : 'Lead';\n return new WindowFunctionOperation(\n new ColumnWithJoin(this._column, this._parent),\n func,\n label + ' ' + this._displayName,\n Math.abs(periods),\n extraArgs,\n this._windowSpec(opts.partitionBy, opts.orderBy),\n );\n }\n\n first(opts: {\n partitionBy?: ColumnWithJoin | ColumnWithJoin[];\n orderBy?: SortOperation | SortOperation[];\n } = {}): WindowFunctionOperation {\n return new WindowFunctionOperation(\n new ColumnWithJoin(this._column, this._parent),\n WindowFunction.FIRST_VALUE,\n 'First ' + this._displayName,\n undefined, [],\n this._windowSpec(opts.partitionBy, opts.orderBy),\n );\n }\n\n last(opts: {\n partitionBy?: ColumnWithJoin | ColumnWithJoin[];\n orderBy?: SortOperation | SortOperation[];\n } = {}): WindowFunctionOperation {\n return new WindowFunctionOperation(\n new ColumnWithJoin(this._column, this._parent),\n WindowFunction.LAST_VALUE,\n 'Last ' + this._displayName,\n undefined, [],\n this._windowSpec(opts.partitionBy, opts.orderBy),\n );\n }\n}\n","const _registry = new Map<string, new (...args: any[]) => unknown>();\n\nexport function registerRelatedFinderClass(name: string, cls: new (...args: any[]) => unknown): void {\n _registry.set(name, cls);\n}\n\nexport function getRelatedFinderClass(name: string): (new (...args: any[]) => unknown) | undefined {\n return _registry.get(name);\n}\n","import { Attribute } from './attribute';\nimport {\n ComparisonOperation,\n ComparisonOperator,\n Operation,\n StringConstantOperation,\n FloatConstantOperation,\n IntegerConstantOperation,\n DateConstantOperation,\n DateTimeConstantOperation,\n BooleanConstantOperation,\n DecimalConstantOperation,\n AggregateOperation,\n AggregateOperator,\n ScalarFunction,\n ScalarFunctionOperation,\n DatePart,\n DateExtractOperation,\n DateArithmeticOperation,\n DateDiffOperation,\n JoinTreeNodeOperation,\n} from '../model/relational';\n\nexport class StringAttribute extends Attribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n ) { super(displayName, columnName, columnDbType, owner, parent); }\n\n upper(): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.UPPER, 'Upper ' + this.displayName());\n }\n lower(): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.LOWER, 'Lower ' + this.displayName());\n }\n strip(): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.TRIM, 'Strip ' + this.displayName());\n }\n lstrip(): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.LTRIM, 'LStrip ' + this.displayName());\n }\n rstrip(): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.RTRIM, 'RStrip ' + this.displayName());\n }\n length(): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.LENGTH, 'Length ' + this.displayName());\n }\n reverse(): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.REVERSE, 'Reverse ' + this.displayName());\n }\n left(n: number): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.LEFT, 'Left ' + this.displayName(), n);\n }\n right(n: number): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.RIGHT, 'Right ' + this.displayName(), n);\n }\n repeat(n: number): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.REPEAT, 'Repeat ' + this.displayName(), n);\n }\n replace(fromStr: string, toStr: string): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.REPLACE, 'Replace ' + this.displayName(), undefined, [fromStr, toStr]);\n }\n substring(start: number, length?: number): ScalarFunctionOperation {\n // Python convention: 0-based start; SQL SUBSTRING is 1-based, so add 1\n const args: (number)[] = length !== undefined ? [start + 1, length] : [start + 1];\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.SUBSTRING, 'Substring ' + this.displayName(), undefined, args);\n }\n\n eq(value: string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new StringConstantOperation(value));\n }\n ne(value: string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_EQUAL, new StringConstantOperation(value));\n }\n contains(value: string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LIKE, new StringConstantOperation(`%${value}%`));\n }\n startsWith(prefix: string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LIKE, new StringConstantOperation(`${prefix}%`));\n }\n endsWith(suffix: string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LIKE, new StringConstantOperation(`%${suffix}`));\n }\n notContains(value: string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_LIKE, new StringConstantOperation(`%${value}%`));\n }\n}\n\nexport abstract class NumericAttribute extends Attribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n ) { super(displayName, columnName, columnDbType, owner, parent); }\n\n sum(): AggregateOperation {\n return new AggregateOperation(this.cwj(), AggregateOperator.SUM, this.displayName() + ' Sum');\n }\n min(): AggregateOperation {\n return new AggregateOperation(this.cwj(), AggregateOperator.MIN, this.displayName() + ' Min');\n }\n max(): AggregateOperation {\n return new AggregateOperation(this.cwj(), AggregateOperator.MAX, this.displayName() + ' Max');\n }\n average(): AggregateOperation {\n return new AggregateOperation(this.cwj(), AggregateOperator.AVERAGE, this.displayName() + ' Average');\n }\n abs(): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.ABS, 'Abs ' + this.displayName());\n }\n ceil(): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.CEILING, 'Ceil ' + this.displayName());\n }\n floor(): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.FLOOR, 'Floor ' + this.displayName());\n }\n sqrt(): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.SQRT, 'Sqrt ' + this.displayName());\n }\n mod(n: number): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.MOD, 'Mod ' + this.displayName(), n);\n }\n power(n: number): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.POWER, 'Power ' + this.displayName(), n);\n }\n round(d?: number): ScalarFunctionOperation {\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.ROUND, 'Round ' + this.displayName(), d);\n }\n}\n\nexport class DoubleAttribute extends NumericAttribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n ) { super(displayName, columnName, columnDbType, owner, parent); }\n\n eq(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new FloatConstantOperation(value));\n }\n ne(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_EQUAL, new FloatConstantOperation(value));\n }\n gt(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN, new FloatConstantOperation(value));\n }\n lt(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN, new FloatConstantOperation(value));\n }\n gte(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN_OR_EQUAL_TO, new FloatConstantOperation(value));\n }\n lte(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN_OR_EQUAL_TO, new FloatConstantOperation(value));\n }\n}\n\nexport const FloatAttribute = DoubleAttribute;\nexport type FloatAttribute = DoubleAttribute;\n\nexport class DecimalAttribute extends NumericAttribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n ) { super(displayName, columnName, columnDbType, owner, parent); }\n\n eq(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new DecimalConstantOperation(value));\n }\n ne(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_EQUAL, new DecimalConstantOperation(value));\n }\n gt(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN, new DecimalConstantOperation(value));\n }\n lt(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN, new DecimalConstantOperation(value));\n }\n gte(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN_OR_EQUAL_TO, new DecimalConstantOperation(value));\n }\n lte(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN_OR_EQUAL_TO, new DecimalConstantOperation(value));\n }\n}\n\nexport class IntegerAttribute extends NumericAttribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n ) { super(displayName, columnName, columnDbType, owner, parent); }\n\n eq(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new IntegerConstantOperation(value));\n }\n ne(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_EQUAL, new IntegerConstantOperation(value));\n }\n gt(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN, new IntegerConstantOperation(value));\n }\n lt(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN, new IntegerConstantOperation(value));\n }\n gte(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN_OR_EQUAL_TO, new IntegerConstantOperation(value));\n }\n lte(value: number): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN_OR_EQUAL_TO, new IntegerConstantOperation(value));\n }\n}\n\nexport class BooleanAttribute extends Attribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n ) { super(displayName, columnName, columnDbType, owner, parent); }\n\n eq(value: boolean): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new BooleanConstantOperation(value));\n }\n isTrue(): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new BooleanConstantOperation(true));\n }\n isFalse(): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new BooleanConstantOperation(false));\n }\n}\n\nfunction parseDate(value: Date | string): Date {\n if (value instanceof Date) return value;\n const d = new Date(value);\n if (isNaN(d.getTime())) throw new Error(`Cannot parse date: ${value}`);\n return d;\n}\n\nexport class DateAttribute extends Attribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n ) { super(displayName, columnName, columnDbType, owner, parent); }\n\n eq(value: Date | string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new DateConstantOperation(parseDate(value)));\n }\n ne(value: Date | string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_EQUAL, new DateConstantOperation(parseDate(value)));\n }\n gt(value: Date | string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN, new DateConstantOperation(parseDate(value)));\n }\n lt(value: Date | string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN, new DateConstantOperation(parseDate(value)));\n }\n gte(value: Date | string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN_OR_EQUAL_TO, new DateConstantOperation(parseDate(value)));\n }\n lte(value: Date | string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN_OR_EQUAL_TO, new DateConstantOperation(parseDate(value)));\n }\n\n year(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.YEAR, 'Year ' + this.displayName()); }\n month(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.MONTH, 'Month ' + this.displayName()); }\n day(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.DAY, 'Day ' + this.displayName()); }\n quarter(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.QUARTER, 'Quarter ' + this.displayName()); }\n week(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.WEEK, 'Week ' + this.displayName()); }\n dayOfWeek(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.DOW, 'Day Of Week ' + this.displayName()); }\n\n addDays(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.DAY, true, 'Add Days ' + this.displayName()); }\n addMonths(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.MONTH, true, 'Add Months ' + this.displayName()); }\n addYears(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.YEAR, true, 'Add Years ' + this.displayName()); }\n subtractDays(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.DAY, false, 'Subtract Days ' + this.displayName()); }\n subtractMonths(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.MONTH, false, 'Subtract Months ' + this.displayName()); }\n subtractYears(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.YEAR, false, 'Subtract Years ' + this.displayName()); }\n\n diffDays(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.DAY, 'Diff Days ' + this.displayName()); }\n diffMonths(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.MONTH, 'Diff Months ' + this.displayName()); }\n diffYears(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.YEAR, 'Diff Years ' + this.displayName()); }\n}\n\nexport class DateTimeAttribute extends Attribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n ) { super(displayName, columnName, columnDbType, owner, parent); }\n\n eq(value: Date | string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new DateTimeConstantOperation(parseDate(value)));\n }\n ne(value: Date | string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_EQUAL, new DateTimeConstantOperation(parseDate(value)));\n }\n gt(value: Date | string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN, new DateTimeConstantOperation(parseDate(value)));\n }\n lt(value: Date | string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN, new DateTimeConstantOperation(parseDate(value)));\n }\n gte(value: Date | string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN_OR_EQUAL_TO, new DateTimeConstantOperation(parseDate(value)));\n }\n lte(value: Date | string): Operation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN_OR_EQUAL_TO, new DateTimeConstantOperation(parseDate(value)));\n }\n\n year(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.YEAR, 'Year ' + this.displayName()); }\n month(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.MONTH, 'Month ' + this.displayName()); }\n day(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.DAY, 'Day ' + this.displayName()); }\n hour(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.HOUR, 'Hour ' + this.displayName()); }\n minute(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.MINUTE, 'Minute ' + this.displayName()); }\n second(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.SECOND, 'Second ' + this.displayName()); }\n quarter(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.QUARTER, 'Quarter ' + this.displayName()); }\n week(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.WEEK, 'Week ' + this.displayName()); }\n dayOfWeek(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.DOW, 'Day Of Week ' + this.displayName()); }\n\n addDays(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.DAY, true, 'Add Days ' + this.displayName()); }\n addMonths(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.MONTH, true, 'Add Months ' + this.displayName()); }\n addYears(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.YEAR, true, 'Add Years ' + this.displayName()); }\n addHours(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.HOUR, true, 'Add Hours ' + this.displayName()); }\n addMinutes(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.MINUTE, true, 'Add Minutes ' + this.displayName()); }\n addSeconds(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.SECOND, true, 'Add Seconds ' + this.displayName()); }\n subtractDays(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.DAY, false, 'Subtract Days ' + this.displayName()); }\n subtractMonths(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.MONTH, false, 'Subtract Months ' + this.displayName()); }\n subtractYears(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.YEAR, false, 'Subtract Years ' + this.displayName()); }\n subtractHours(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.HOUR, false, 'Subtract Hours ' + this.displayName()); }\n subtractMinutes(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.MINUTE, false, 'Subtract Minutes ' + this.displayName()); }\n subtractSeconds(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.SECOND, false, 'Subtract Seconds ' + this.displayName()); }\n\n diffDays(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.DAY, 'Diff Days ' + this.displayName()); }\n diffMonths(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.MONTH, 'Diff Months ' + this.displayName()); }\n diffYears(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.YEAR, 'Diff Years ' + this.displayName()); }\n diffHours(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.HOUR, 'Diff Hours ' + this.displayName()); }\n diffMinutes(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.MINUTE, 'Diff Minutes ' + this.displayName()); }\n diffSeconds(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.SECOND, 'Diff Seconds ' + this.displayName()); }\n}\n","import { Column, Table, Schema } from './relational';\n\nexport abstract class MilestoningColumns {\n abstract columns(): Column[];\n}\n\nexport class ProcessingTemporalColumns extends MilestoningColumns {\n constructor(\n readonly startAtColumn: Column,\n readonly endAtColumn: Column,\n readonly infiniteDatetime?: string,\n ) { super(); }\n\n columns(): Column[] { return [this.startAtColumn, this.endAtColumn]; }\n}\n\nexport class SingleBusinessDateColumn extends MilestoningColumns {\n constructor(readonly businessDateColumn: Column) { super(); }\n\n columns(): Column[] { return [this.businessDateColumn]; }\n}\n\nexport class BusinessDateAndProcessingTemporalColumns extends MilestoningColumns {\n constructor(\n readonly businessDateColumn: Column,\n readonly startAtColumn: Column,\n readonly endAtColumn: Column,\n readonly infiniteDatetime?: string,\n ) { super(); }\n\n columns(): Column[] {\n return [this.businessDateColumn, this.startAtColumn, this.endAtColumn];\n }\n}\n\nexport class BiTemporalColumns extends MilestoningColumns {\n constructor(\n readonly businessDateFromColumn: Column,\n readonly businessDateToColumn: Column,\n readonly startAtColumn: Column,\n readonly endAtColumn: Column,\n readonly infiniteDatetime?: string,\n ) { super(); }\n\n columns(): Column[] {\n return [\n this.businessDateFromColumn,\n this.businessDateToColumn,\n this.startAtColumn,\n this.endAtColumn,\n ];\n }\n}\n\nexport class MilestonedTable extends Table {\n constructor(\n name: string,\n columns: Column[],\n readonly milestoningColumns: MilestoningColumns,\n schema?: Schema,\n ) {\n super(name, columns, schema);\n for (const col of milestoningColumns.columns()) {\n col.table = this;\n }\n }\n}\n","import { RelationalOperationElement, LogicalOperation, LogicalOperator, JoinTreeNodeOperation } from '../model/relational';\n\nexport class ExistsOperation extends RelationalOperationElement {\n constructor(readonly node: JoinTreeNodeOperation) { super(); }\n\n andOp(other: RelationalOperationElement): LogicalOperation {\n return new LogicalOperation(this, LogicalOperator.AND, other);\n }\n}\n\nexport class NotExistsOperation extends RelationalOperationElement {\n constructor(readonly node: JoinTreeNodeOperation) { super(); }\n\n andOp(other: RelationalOperationElement): LogicalOperation {\n return new LogicalOperation(this, LogicalOperator.AND, other);\n }\n}\n\nexport class RelatedFinder {\n constructor(private readonly _node: JoinTreeNodeOperation) {}\n\n exists(): ExistsOperation {\n return new ExistsOperation(this._node);\n }\n\n notExists(): NotExistsOperation {\n return new NotExistsOperation(this._node);\n }\n}\n","import { Attribute } from './attribute';\nimport {\n RelationalOperationElement,\n Operation,\n NoOperation,\n ConstantOperation,\n StringConstantOperation,\n IntegerConstantOperation,\n FloatConstantOperation,\n DateConstantOperation,\n DateTimeConstantOperation,\n BooleanConstantOperation,\n DecimalConstantOperation,\n LogicalOperation,\n LogicalOperator,\n ComparisonOperation,\n ComparisonOperator,\n IsNullOperation,\n IsNotNullOperation,\n AggregateOperation,\n AggregateOperator,\n ScalarFunctionOperation,\n ScalarFunction,\n DateExtractOperation,\n DateArithmeticOperation,\n DateDiffOperation,\n WindowFunction,\n WindowFunctionOperation,\n WindowSpecification,\n Column,\n ColumnWithJoin,\n Table,\n JoinOperation,\n JoinTreeNodeOperation,\n SortOperation,\n SortDirection,\n CountAllOperation,\n UnaryOperation,\n} from '../model/relational';\nimport {\n MilestonedTable,\n BiTemporalColumns,\n BusinessDateAndProcessingTemporalColumns,\n ProcessingTemporalColumns,\n SingleBusinessDateColumn,\n} from '../model/milestoning';\nimport { DateAttribute, DateTimeAttribute } from './typed-attributes';\nimport { ExistsOperation, NotExistsOperation } from './finder';\n\nclass Alias {\n constructor(readonly element: RelationalOperationElement, readonly name: string) {}\n}\n\nclass TableAlias {\n constructor(readonly table: string, readonly alias: string) {}\n}\n\nclass TableAliasColumn extends RelationalOperationElement {\n constructor(readonly column: Column, readonly tableAlias: TableAlias) { super(); }\n}\n\nclass Join {\n constructor(\n readonly source: TableAliasColumn,\n readonly target: TableAliasColumn,\n readonly filterOp?: RelationalOperationElement,\n ) {}\n}\n\nclass SelectOperation {\n constructor(\n readonly display: (Attribute | RelationalOperationElement)[],\n readonly filter: RelationalOperationElement,\n readonly orderBy: SortOperation[] = [],\n readonly groupBy: Attribute[] = [],\n readonly limit?: number,\n readonly table?: Table,\n ) {}\n}\n\nfunction sqlFormatDatetime(value: Date): string {\n const pad = (n: number, w = 2) => String(n).padStart(w, '0');\n return `'${value.getUTCFullYear()}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())} ${pad(value.getUTCHours())}:${pad(value.getUTCMinutes())}:${pad(value.getUTCSeconds())}'`;\n}\n\nfunction sqlFormatDate(value: Date): string {\n const pad = (n: number) => String(n).padStart(2, '0');\n return `'${value.getUTCFullYear()}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())}'`;\n}\n\nconst LOGICAL_OPERATOR_STR: Record<LogicalOperator, string> = {\n [LogicalOperator.AND]: ' AND ',\n [LogicalOperator.OR]: ' OR ',\n};\n\nconst COMPARISON_OPERATOR_STR: Record<ComparisonOperator, string> = {\n [ComparisonOperator.EQUAL]: ' = ',\n [ComparisonOperator.NOT_EQUAL]: ' <> ',\n [ComparisonOperator.LESS_THAN]: ' < ',\n [ComparisonOperator.GREATER_THAN]: ' > ',\n [ComparisonOperator.LESS_THAN_OR_EQUAL_TO]: ' <= ',\n [ComparisonOperator.GREATER_THAN_OR_EQUAL_TO]: ' >= ',\n [ComparisonOperator.LIKE]: ' LIKE ',\n [ComparisonOperator.NOT_LIKE]: ' NOT LIKE ',\n};\n\nconst AGGREGATE_SQL_NAMES: Partial<Record<AggregateOperator, string>> = {\n [AggregateOperator.AVERAGE]: 'AVG',\n};\n\nconst WINDOW_SQL_NAMES: Record<WindowFunction, string> = {\n [WindowFunction.ROW_NUMBER]: 'ROW_NUMBER',\n [WindowFunction.RANK]: 'RANK',\n [WindowFunction.DENSE_RANK]: 'DENSE_RANK',\n [WindowFunction.NTILE]: 'NTILE',\n [WindowFunction.LAG]: 'LAG',\n [WindowFunction.LEAD]: 'LEAD',\n [WindowFunction.FIRST_VALUE]: 'FIRST_VALUE',\n [WindowFunction.LAST_VALUE]: 'LAST_VALUE',\n [WindowFunction.CUME_DIST]: 'CUME_DIST',\n [WindowFunction.PERCENT_RANK]: 'PERCENT_RANK',\n};\n\nconst SCALAR_SQL_NAMES: Record<ScalarFunction, string> = {\n [ScalarFunction.ABS]: 'ABS',\n [ScalarFunction.CEILING]: 'CEILING',\n [ScalarFunction.FLOOR]: 'FLOOR',\n [ScalarFunction.MOD]: 'MOD',\n [ScalarFunction.POWER]: 'POWER',\n [ScalarFunction.SQRT]: 'SQRT',\n [ScalarFunction.ROUND]: 'ROUND',\n [ScalarFunction.UPPER]: 'UPPER',\n [ScalarFunction.LOWER]: 'LOWER',\n [ScalarFunction.TRIM]: 'TRIM',\n [ScalarFunction.LTRIM]: 'LTRIM',\n [ScalarFunction.RTRIM]: 'RTRIM',\n [ScalarFunction.LENGTH]: 'LENGTH',\n [ScalarFunction.REVERSE]: 'REVERSE',\n [ScalarFunction.LEFT]: 'LEFT',\n [ScalarFunction.RIGHT]: 'RIGHT',\n [ScalarFunction.REPEAT]: 'REPEAT',\n [ScalarFunction.REPLACE]: 'REPLACE',\n [ScalarFunction.SUBSTRING]: 'SUBSTRING',\n};\n\nfunction constantValueString(op: ConstantOperation): string {\n if (op instanceof StringConstantOperation) return \"'\" + op.value + \"'\";\n if (op instanceof DateConstantOperation) return sqlFormatDate(op.value);\n if (op instanceof DateTimeConstantOperation) return sqlFormatDatetime(op.value);\n if (op instanceof IntegerConstantOperation) return String(op.value);\n if (op instanceof FloatConstantOperation) return String(op.value);\n if (op instanceof BooleanConstantOperation) return op.value ? 'TRUE' : 'FALSE';\n if (op instanceof DecimalConstantOperation) return String(op.value);\n throw new Error('Unknown constant operation');\n}\n\nfunction windowSpecToString(window: WindowSpecification): string {\n const parts: string[] = [];\n if (window.partitionBy.length > 0) {\n parts.push('PARTITION BY ' + window.partitionBy.map(p => sqlOperationToString(p)).join(', '));\n }\n if (window.orderBy.length > 0) {\n parts.push('ORDER BY ' + window.orderBy.map(s =>\n sqlOperationToString(s.column) + (s.direction === SortDirection.ASC ? ' ASC' : ' DESC'),\n ).join(', '));\n }\n return 'OVER (' + parts.join(' ') + ')';\n}\n\nfunction sqlOperationToString(operation: RelationalOperationElement): string {\n if (operation instanceof TableAliasColumn) {\n return operation.tableAlias.alias + '.' + operation.column.name;\n }\n if (operation instanceof WindowFunctionOperation) {\n const fn = WINDOW_SQL_NAMES[operation.func];\n const parts: string[] = [];\n if (operation.element !== null && operation.element !== undefined) {\n parts.push(sqlOperationToString(operation.element));\n }\n if (operation.secondArg !== undefined) parts.push(String(operation.secondArg));\n for (const arg of operation.extraArgs) {\n parts.push(typeof arg === 'string' ? \"'\" + arg + \"'\" : String(arg));\n }\n const sql = fn + '(' + parts.join(', ') + ')';\n return sql + (operation.window !== undefined ? ' ' + windowSpecToString(operation.window) : ' OVER ()');\n }\n if (operation instanceof AggregateOperation) {\n const fn = AGGREGATE_SQL_NAMES[operation.operator] ?? operation.operator;\n let sql = fn + '(' + sqlOperationToString(operation.element) + ')';\n if (operation.window !== undefined) {\n sql += ' ' + windowSpecToString(operation.window);\n }\n return sql;\n }\n if (operation instanceof ScalarFunctionOperation) {\n const fn = SCALAR_SQL_NAMES[operation.func];\n const parts: string[] = [sqlOperationToString(operation.element)];\n if (operation.secondArg !== undefined) parts.push(String(operation.secondArg));\n for (const arg of operation.extraArgs) {\n parts.push(typeof arg === 'string' ? \"'\" + arg + \"'\" : String(arg));\n }\n return fn + '(' + parts.join(', ') + ')';\n }\n if (operation instanceof DateExtractOperation) {\n return 'EXTRACT(' + operation.part + ' FROM ' + sqlOperationToString(operation.element) + ')';\n }\n if (operation instanceof DateArithmeticOperation) {\n const op = operation.isAdd ? '+' : '-';\n return sqlOperationToString(operation.element) + ' ' + op + ' INTERVAL ' + operation.n + ' ' + operation.unit;\n }\n if (operation instanceof DateDiffOperation) {\n const otherSql = sqlFormatDatetime(operation.other);\n return \"DATE_DIFF('\" + operation.unit.toLowerCase() + \"', \" + sqlOperationToString(operation.element) + ', ' + otherSql + ')';\n }\n if (operation instanceof CountAllOperation) return 'COUNT(*)';\n if (operation instanceof Alias) {\n return sqlOperationToString(operation.element) + ' AS \"' + operation.name + '\"';\n }\n throw new TypeError('Unknown operation in sqlOperationToString: ' + operation.constructor.name);\n}\n\nfunction findColumn(operation: RelationalOperationElement): ColumnWithJoin {\n if (operation instanceof UnaryOperation) return findColumn(operation.element);\n if (operation instanceof ColumnWithJoin) return operation;\n throw new TypeError('Cannot find ColumnWithJoin in: ' + operation.constructor.name);\n}\n\nfunction openEndClause(\n endAttr: DateTimeAttribute | DateAttribute,\n value: Date,\n infiniteDatetime?: string,\n): Operation {\n const gtOp = endAttr instanceof DateTimeAttribute ? endAttr.gt(value) : endAttr.gt(value);\n if (infiniteDatetime === undefined) {\n const colRef = new ColumnWithJoin(endAttr.column(), endAttr.parent());\n return new LogicalOperation(gtOp, LogicalOperator.OR, new IsNullOperation(colRef));\n }\n return gtOp;\n}\n\nfunction buildMilestoningFilterOperation(\n businessDate: Date | null,\n processingDatetime: Date | null,\n table: MilestonedTable,\n joinNode?: JoinTreeNodeOperation,\n): Operation | null {\n const mc = table.milestoningColumns;\n const ops: Operation[] = [];\n\n if (mc instanceof BiTemporalColumns) {\n if (businessDate !== null) {\n const dateFrom = new DateAttribute('business_date_from', mc.businessDateFromColumn.name, mc.businessDateFromColumn.type, mc.businessDateFromColumn.table!.qualifiedName, joinNode);\n const dateTo = new DateAttribute('business_date_to', mc.businessDateToColumn.name, mc.businessDateToColumn.type, mc.businessDateToColumn.table!.qualifiedName, joinNode);\n ops.push(new LogicalOperation(dateFrom.lte(businessDate), LogicalOperator.AND, openEndClause(dateTo, businessDate, mc.infiniteDatetime)));\n }\n if (processingDatetime !== null) {\n const startAt = new DateTimeAttribute('start_at', mc.startAtColumn.name, mc.startAtColumn.type, mc.startAtColumn.table!.qualifiedName, joinNode);\n const endAt = new DateTimeAttribute('end_at', mc.endAtColumn.name, mc.endAtColumn.type, mc.endAtColumn.table!.qualifiedName, joinNode);\n ops.push(new LogicalOperation(startAt.lte(processingDatetime), LogicalOperator.AND, openEndClause(endAt, processingDatetime, mc.infiniteDatetime)));\n }\n } else if (mc instanceof BusinessDateAndProcessingTemporalColumns) {\n if (businessDate !== null) {\n const businessAtt = new DateAttribute('business_date', mc.businessDateColumn.name, mc.businessDateColumn.type, mc.businessDateColumn.table!.qualifiedName, joinNode);\n ops.push(businessAtt.eq(businessDate));\n }\n if (processingDatetime !== null) {\n const startAt = new DateTimeAttribute('start_at', mc.startAtColumn.name, mc.startAtColumn.type, mc.startAtColumn.table!.qualifiedName, joinNode);\n const endAt = new DateTimeAttribute('end_at', mc.endAtColumn.name, mc.endAtColumn.type, mc.endAtColumn.table!.qualifiedName, joinNode);\n ops.push(new LogicalOperation(startAt.lte(processingDatetime), LogicalOperator.AND, openEndClause(endAt, processingDatetime, mc.infiniteDatetime)));\n }\n } else if (mc instanceof ProcessingTemporalColumns && processingDatetime !== null) {\n const startAt = new DateTimeAttribute('start_at', mc.startAtColumn.name, mc.startAtColumn.type, mc.startAtColumn.table!.qualifiedName, joinNode);\n const endAt = new DateTimeAttribute('end_at', mc.endAtColumn.name, mc.endAtColumn.type, mc.endAtColumn.table!.qualifiedName, joinNode);\n ops.push(new LogicalOperation(startAt.lte(processingDatetime), LogicalOperator.AND, openEndClause(endAt, processingDatetime, mc.infiniteDatetime)));\n } else if (mc instanceof SingleBusinessDateColumn && businessDate !== null) {\n const businessAtt = new DateAttribute('business_date', mc.businessDateColumn.name, mc.businessDateColumn.type, mc.businessDateColumn.table!.qualifiedName, joinNode);\n ops.push(businessAtt.eq(businessDate));\n }\n\n if (ops.length === 0) return null;\n if (ops.length === 1) return ops[0];\n return new LogicalOperation(ops[0], LogicalOperator.AND, ops[1]);\n}\n\nfunction buildQueryOperation(\n businessDate: Date | null,\n processingDatetime: Date | null,\n columns: (Attribute | RelationalOperationElement)[],\n table: Table,\n op: RelationalOperationElement,\n orderBy: SortOperation[] = [],\n groupBy: Attribute[] = [],\n limit?: number,\n): SelectOperation {\n let filter = op;\n\n if (table instanceof MilestonedTable) {\n const milestonedOp = buildMilestoningFilterOperation(businessDate, processingDatetime, table);\n if (milestonedOp !== null) {\n filter = filter instanceof NoOperation\n ? milestonedOp\n : new LogicalOperation(filter, LogicalOperator.AND, milestonedOp);\n }\n }\n\n const requiredJoins: JoinTreeNodeOperation[] = [];\n const requiredJoinIds = new Set<JoinTreeNodeOperation>();\n\n for (const col of columns) {\n if (col instanceof CountAllOperation) continue;\n let node: JoinTreeNodeOperation | undefined;\n if (col instanceof Attribute) {\n node = col.parent();\n } else {\n node = findColumn(col as RelationalOperationElement).parent;\n }\n if (node !== undefined && !requiredJoinIds.has(node)) {\n requiredJoinIds.add(node);\n requiredJoins.push(node);\n }\n }\n\n for (const node of requiredJoins) {\n if (node.join.target instanceof MilestonedTable) {\n const milestonedOp = buildMilestoningFilterOperation(businessDate, processingDatetime, node.join.target, node);\n if (milestonedOp !== null) {\n node.join.filter = milestonedOp;\n }\n }\n }\n\n return new SelectOperation(columns, filter, orderBy, groupBy, limit, table);\n}\n\nclass SQLQueryGenerator {\n private _select: Alias[] = [];\n private _from: Set<TableAlias> = new Set();\n private _join: Join[] = [];\n private _groupByParts: string[] = [];\n private _orderByParts: string[] = [];\n private _where = '';\n private _limit?: number;\n private _tableAliasIncr = 0;\n private _tableAliasesByTable = new Map<unknown, TableAlias>();\n private _addedJoinIds = new Set<JoinTreeNodeOperation>();\n private _rootTable?: Table;\n\n generate(select: SelectOperation): void {\n this._rootTable = select.table;\n if (this._rootTable !== undefined) {\n this._from.add(this._tableAliasForTable(this._rootTable.qualifiedName, this._rootTable.qualifiedName));\n }\n this.processSelect(select.display);\n this._where = this.buildFilter(select.filter);\n const groupByJoins = new Map<JoinTreeNodeOperation, JoinTreeNodeOperation>();\n for (const expr of select.groupBy) {\n this._collectRequiredJoins(expr, groupByJoins);\n }\n for (const node of groupByJoins.values()) {\n this._addJoin(node);\n }\n this._groupByParts = select.groupBy.map(a => this._attrToColString(a));\n this._orderByParts = select.orderBy.map(s =>\n this.buildFilter(s.column) + (s.direction === SortDirection.ASC ? ' ASC' : ' DESC'),\n );\n this._limit = select.limit;\n }\n\n private _attrToColString(attr: Attribute): string {\n const node = attr.parent();\n const ta = this._tableAliasForTable(attr.owner(), node ?? attr.owner());\n return ta.alias + '.' + attr.column().name;\n }\n\n private _collectRequiredJoins(op: RelationalOperationElement | null | undefined, out: Map<JoinTreeNodeOperation, JoinTreeNodeOperation>): void {\n if (op === null || op === undefined) return;\n if (op instanceof Attribute) {\n const p = op.parent();\n if (p !== undefined) out.set(p, p);\n } else if (op instanceof ColumnWithJoin) {\n if (op.parent !== undefined) out.set(op.parent, op.parent);\n } else if (op instanceof AggregateOperation) {\n this._collectRequiredJoins(op.element, out);\n if (op.window) this._collectRequiredJoins(op.window as unknown as RelationalOperationElement, out);\n } else if (op instanceof WindowFunctionOperation) {\n if (op.element) this._collectRequiredJoins(op.element, out);\n if (op.window) this._collectRequiredJoinsFromWindowSpec(op.window, out);\n } else if (op instanceof ScalarFunctionOperation || op instanceof DateExtractOperation ||\n op instanceof DateArithmeticOperation || op instanceof DateDiffOperation) {\n this._collectRequiredJoins((op as UnaryOperation).element, out);\n } else if (op instanceof SortOperation) {\n this._collectRequiredJoins(op.column, out);\n } else if (op instanceof LogicalOperation || op instanceof ComparisonOperation) {\n this._collectRequiredJoins((op as any).left, out);\n this._collectRequiredJoins((op as any).right, out);\n }\n }\n\n private _collectRequiredJoinsFromWindowSpec(window: WindowSpecification, out: Map<JoinTreeNodeOperation, JoinTreeNodeOperation>): void {\n for (const p of window.partitionBy) {\n this._collectRequiredJoins(p, out);\n }\n for (const s of window.orderBy) {\n this._collectRequiredJoins(s.column, out);\n }\n }\n\n private _rewriteWindowSpec(window: WindowSpecification): WindowSpecification {\n const partitionBy = window.partitionBy.map(p => this._rewriteOperation(p));\n const orderBy = window.orderBy.map(s => new SortOperation(this._rewriteOperation(s.column) as ColumnWithJoin, s.direction));\n return new WindowSpecification(partitionBy, orderBy);\n }\n\n private _rewriteOperation(op: RelationalOperationElement): RelationalOperationElement {\n if (op instanceof Attribute) {\n const ta = this._tableAliasForTable(op.owner(), op.parent() ?? op.owner());\n return new TableAliasColumn(op.column(), ta);\n }\n if (op instanceof ColumnWithJoin) {\n const ta = op.parent !== undefined\n ? this._tableAliasForTable(op.column.owner!, op.parent)\n : this._tableAliasForTable(op.column.owner!, op.column.owner!);\n return new TableAliasColumn(op.column, ta);\n }\n if (op instanceof Column) {\n const ta = this._tableAliasForTable(op.owner!, op.owner!);\n return new TableAliasColumn(op, ta);\n }\n if (op instanceof AggregateOperation) {\n return new AggregateOperation(\n this._rewriteOperation(op.element), op.operator, op.displayName,\n op.window ? this._rewriteWindowSpec(op.window) : undefined,\n );\n }\n if (op instanceof WindowFunctionOperation) {\n const el = op.element ? this._rewriteOperation(op.element) : null;\n return new WindowFunctionOperation(el, op.func, op.displayName, op.secondArg, [...op.extraArgs],\n op.window ? this._rewriteWindowSpec(op.window) : undefined);\n }\n if (op instanceof ScalarFunctionOperation) {\n return new ScalarFunctionOperation(this._rewriteOperation(op.element), op.func, op.displayName, op.secondArg, op.extraArgs);\n }\n if (op instanceof DateExtractOperation) {\n return new DateExtractOperation(this._rewriteOperation(op.element), op.part, op.displayName);\n }\n if (op instanceof DateArithmeticOperation) {\n return new DateArithmeticOperation(this._rewriteOperation(op.element), op.n, op.unit, op.isAdd, op.displayName);\n }\n if (op instanceof DateDiffOperation) {\n return new DateDiffOperation(this._rewriteOperation(op.element), (op as DateDiffOperation).other, (op as DateDiffOperation).unit, op.displayName);\n }\n return op;\n }\n\n private processSelect(cols: (Attribute | RelationalOperationElement)[]): void {\n const requiredJoins = new Map<JoinTreeNodeOperation, JoinTreeNodeOperation>();\n\n for (const col of cols) {\n this._collectRequiredJoins(col, requiredJoins);\n }\n for (const node of requiredJoins.values()) {\n this._addJoin(node);\n }\n\n for (const col of cols) {\n if (col instanceof Attribute) {\n const node = col.parent();\n let ta: TableAlias;\n if (node !== undefined) {\n ta = this._tableAliasForTable(col.owner(), node);\n } else {\n ta = this._tableAliasForTable(col.owner(), col.owner());\n this._from.add(ta);\n }\n this._select.push(new Alias(new TableAliasColumn(col.column(), ta), col.displayName()));\n } else if (col instanceof WindowFunctionOperation) {\n const rewritten = this._rewriteOperation(col) as WindowFunctionOperation;\n let alias: string;\n if (col.displayName) {\n alias = col.displayName;\n } else if ([WindowFunction.ROW_NUMBER, WindowFunction.RANK, WindowFunction.DENSE_RANK].includes(col.func)) {\n alias = col.func.replace(/_/g, ' ').replace(/\\b\\w/g, c => c.toUpperCase());\n } else if (col.element) {\n alias = col.func + ' ' + findColumn(col).column.name;\n } else {\n alias = col.func;\n }\n this._select.push(new Alias(rewritten, alias));\n } else if (col instanceof AggregateOperation) {\n const colNested = findColumn(col);\n const node = colNested.parent;\n let ta: TableAlias;\n if (node !== undefined) {\n ta = this._tableAliasForTable(colNested.column.owner!, node);\n } else {\n ta = this._tableAliasForTable(colNested.column.owner!, colNested.column.owner!);\n this._from.add(ta);\n }\n const alias = col.displayName ?? col.operator + ' ' + colNested.column.name;\n const rewrittenAgg = new AggregateOperation(\n new TableAliasColumn(colNested.column, ta), col.operator, undefined,\n col.window ? this._rewriteWindowSpec(col.window) : undefined,\n );\n this._select.push(new Alias(rewrittenAgg, alias));\n } else if (col instanceof ScalarFunctionOperation) {\n const colNested = findColumn(col);\n const node = colNested.parent;\n let ta: TableAlias;\n if (node !== undefined) {\n ta = this._tableAliasForTable(colNested.column.owner!, node);\n } else {\n ta = this._tableAliasForTable(colNested.column.owner!, colNested.column.owner!);\n this._from.add(ta);\n }\n const alias = col.displayName ?? col.func + ' ' + colNested.column.name;\n this._select.push(new Alias(\n new ScalarFunctionOperation(new TableAliasColumn(colNested.column, ta), col.func, undefined, col.secondArg, col.extraArgs),\n alias,\n ));\n } else if (col instanceof DateExtractOperation || col instanceof DateArithmeticOperation || col instanceof DateDiffOperation) {\n const colNested = findColumn(col as RelationalOperationElement);\n const node = colNested.parent;\n let ta: TableAlias;\n if (node !== undefined) {\n ta = this._tableAliasForTable(colNested.column.owner!, node);\n } else {\n ta = this._tableAliasForTable(colNested.column.owner!, colNested.column.owner!);\n this._from.add(ta);\n }\n const alias = (col as DateExtractOperation).displayName ?? colNested.column.name;\n let aliasedOp: RelationalOperationElement;\n if (col instanceof DateExtractOperation) {\n aliasedOp = new DateExtractOperation(new TableAliasColumn(colNested.column, ta), col.part);\n } else if (col instanceof DateArithmeticOperation) {\n aliasedOp = new DateArithmeticOperation(new TableAliasColumn(colNested.column, ta), col.n, col.unit, col.isAdd);\n } else {\n aliasedOp = new DateDiffOperation(new TableAliasColumn(colNested.column, ta), (col as DateDiffOperation).other, (col as DateDiffOperation).unit);\n }\n this._select.push(new Alias(aliasedOp, alias));\n } else if (col instanceof CountAllOperation) {\n const ta = this._tableAliasForTable(col.table, col.table);\n this._from.add(ta);\n this._select.push(new Alias(col, 'Count'));\n }\n }\n }\n\n private _addJoin(node: JoinTreeNodeOperation): void {\n if (this._addedJoinIds.has(node)) return;\n if (node.parent !== undefined) this._addJoin(node.parent);\n this._addedJoinIds.add(node);\n\n const join = node.join;\n const left = join.left;\n const srcTa = this._tableAliasForTable(left.owner!, node.parent ?? left.owner!);\n if (node.parent === undefined) this._from.add(srcTa);\n const sc = new TableAliasColumn(left, srcTa);\n const right = join.right;\n const tc = new TableAliasColumn(right, this._tableAliasForTable(right.owner!, node));\n this._join.push(new Join(sc, tc, join.filter));\n }\n\n buildFilter(op: RelationalOperationElement): string {\n if (op instanceof NoOperation) return '';\n if (op instanceof ExistsOperation) {\n const col = op.node.join.right;\n return this.buildFilter(new ColumnWithJoin(col, op.node)) + ' IS NOT NULL';\n }\n if (op instanceof NotExistsOperation) {\n const col = op.node.join.right;\n return this.buildFilter(new ColumnWithJoin(col, op.node)) + ' IS NULL';\n }\n if (op instanceof IsNotNullOperation) return this.buildFilter(op.element) + ' IS NOT NULL';\n if (op instanceof IsNullOperation) return this.buildFilter(op.element) + ' IS NULL';\n if (op instanceof LogicalOperation) {\n let left = this.buildFilter(op.left);\n let right = this.buildFilter(op.right);\n if (op.left instanceof LogicalOperation) left = '(' + left + ')';\n if (op.right instanceof LogicalOperation) right = '(' + right + ')';\n return left + LOGICAL_OPERATOR_STR[op.operator] + right;\n }\n if (op instanceof ComparisonOperation) {\n return this.buildFilter(op.left) + COMPARISON_OPERATOR_STR[op.operator] + this.buildFilter(op.right);\n }\n if (op instanceof ConstantOperation) return constantValueString(op);\n if (op instanceof ColumnWithJoin) {\n const node = op.parent;\n let ta: TableAlias;\n if (node !== undefined) {\n ta = this._tableAliasForTable(op.column.owner!, node);\n this._addJoin(node);\n } else {\n ta = this._tableAliasForTable(op.column.owner!, op.column.owner!);\n }\n return ta.alias + '.' + op.column.name;\n }\n if (op instanceof Column) {\n const ta = this._tableAliasForTable(op.owner!, op.owner!);\n return ta.alias + '.' + op.name;\n }\n throw new Error('Unknown operation in buildFilter: ' + op.constructor.name);\n }\n\n private _tableAliasForTable(table: string, key: unknown): TableAlias {\n if (this._tableAliasesByTable.has(key)) {\n return this._tableAliasesByTable.get(key)!;\n }\n const ta = new TableAlias(table, 't' + this._tableAliasIncr++);\n this._tableAliasesByTable.set(key, ta);\n return ta;\n }\n\n buildQueryString(): string {\n const joins = this._join.map(j =>\n ' LEFT OUTER JOIN ' + j.target.tableAlias.table + ' AS ' + j.target.tableAlias.alias +\n ' ON ' + j.source.tableAlias.alias + '.' + j.source.column.name +\n ' = ' + j.target.tableAlias.alias + '.' + j.target.column.name +\n (j.filterOp ? ' AND ' + this.buildFilter(j.filterOp) : ''),\n );\n\n return 'SELECT ' + this._select.map(ca => sqlOperationToString(ca)).join(',') +\n ' FROM ' + Array.from(this._from).map(ta => ta.table + ' AS ' + ta.alias).join(',') +\n joins.join('') +\n this._buildWhere() +\n this._buildGroupBy() +\n this._buildOrderBy() +\n this._buildLimit();\n }\n\n private _buildWhere(): string {\n return this._where.length > 0 ? ' WHERE ' + this._where : '';\n }\n private _buildGroupBy(): string {\n return this._groupByParts.length > 0 ? ' GROUP BY ' + this._groupByParts.join(', ') : '';\n }\n private _buildOrderBy(): string {\n return this._orderByParts.length > 0 ? ' ORDER BY ' + this._orderByParts.join(', ') : '';\n }\n private _buildLimit(): string {\n return this._limit !== undefined ? ' LIMIT ' + this._limit : '';\n }\n}\n\nexport function selectSqlToString(selectOperation: SelectOperation): string {\n const qg = new SQLQueryGenerator();\n qg.generate(selectOperation);\n return qg.buildQueryString();\n}\n\nexport function toSql(\n businessDate: Date | null,\n processingDatetime: Date | null,\n columns: (Attribute | RelationalOperationElement)[],\n table: Table,\n op: RelationalOperationElement,\n orderBy: SortOperation[] = [],\n groupBy: Attribute[] = [],\n limit?: number,\n): string {\n const selectOp = buildQueryOperation(businessDate, processingDatetime, columns, table, op, orderBy, groupBy, limit);\n return selectSqlToString(selectOp);\n}\n\nexport { buildQueryOperation, SelectOperation };\n","import { Attribute } from './attribute';\nimport { toSql } from './sql-generator';\nimport {\n Table,\n Operation,\n SortOperation,\n NoOperation,\n RelationalOperationElement,\n} from '../model/relational';\n\nexport type Row = unknown[];\n\n/** Minimum interface satisfied by both Table (SQL) and GraphQLQuery (GraphQL). */\nexport interface QueryTarget {\n readonly name: string;\n}\n\nexport interface QueryRunner {\n select(\n businessDate: Date | null,\n processingDatetime: Date | null,\n columns: (Attribute | RelationalOperationElement)[],\n table: QueryTarget,\n op: RelationalOperationElement,\n orderBy?: SortOperation[],\n groupBy?: Attribute[],\n limit?: number,\n ): Promise<Row[]>;\n}\n\nlet _runner: QueryRunner | null = null;\n\nexport function registerRunner(runner: QueryRunner): void { _runner = runner; }\nexport function clearRunner(): void { _runner = null; }\nexport function getRunner(): QueryRunner {\n if (!_runner) throw new Error('No query runner registered. Call registerRunner() first.');\n return _runner;\n}\n\nexport class FinderResult {\n private _orderBy: SortOperation[] = [];\n private _groupBy: Attribute[] = [];\n private _limit?: number;\n\n constructor(\n private readonly _businessDate: Date | null,\n private readonly _processingDatetime: Date | null,\n private readonly _columns: (Attribute | RelationalOperationElement)[],\n private readonly _table: QueryTarget,\n private readonly _op: RelationalOperationElement,\n ) {}\n\n orderByOp(...sorts: SortOperation[]): this {\n this._orderBy = sorts;\n return this;\n }\n\n groupByOp(...attrs: Attribute[]): this {\n this._groupBy = attrs;\n return this;\n }\n\n limit(n: number): this {\n this._limit = n;\n return this;\n }\n\n toSql(): string {\n return toSql(\n this._businessDate,\n this._processingDatetime,\n this._columns,\n this._table as Table,\n this._op,\n this._orderBy,\n this._groupBy,\n this._limit,\n );\n }\n\n async toRows(): Promise<Row[]> {\n return getRunner().select(\n this._businessDate,\n this._processingDatetime,\n this._columns,\n this._table,\n this._op,\n this._orderBy,\n this._groupBy,\n this._limit,\n );\n }\n}\n\nfunction convertDate(value: Date | string | null): Date | null {\n if (value === null) return null;\n if (value instanceof Date) return value;\n // Date-only strings (YYYY-MM-DD) must be parsed as UTC to avoid timezone-shift bugs.\n // new Date('2023-01-15') already parses as UTC midnight, so this is consistent.\n const normalized = /^\\d{4}-\\d{2}-\\d{2}$/.test(value) ? value + 'T00:00:00Z' : value;\n const d = new Date(normalized);\n if (isNaN(d.getTime())) throw new Error(`Cannot parse date: ${value}`);\n return d;\n}\n\nexport function convertInputsAndSelect(\n businessDate: Date | string | null,\n processingDatetime: Date | string | null,\n columns: (Attribute | RelationalOperationElement)[],\n table: QueryTarget,\n op: RelationalOperationElement = new NoOperation(),\n): FinderResult {\n return new FinderResult(\n convertDate(businessDate),\n convertDate(processingDatetime),\n columns,\n table,\n op,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAK,qBAAL,kBAAKA,wBAAL;AACL,EAAAA,oBAAA,WAAQ;AACR,EAAAA,oBAAA,eAAY;AACZ,EAAAA,oBAAA,eAAY;AACZ,EAAAA,oBAAA,kBAAe;AACf,EAAAA,oBAAA,2BAAw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AA,EAEA,QAAgB;AACd,WAAO;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,IACP;AAAA,EACF;AAAA,EAEA,MAAM,SAAyB;AAC7B,WAAO,UAAU,EAAE;AAAA,MACjB,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,IACP;AAAA,EACF;AACF;AAEA,SAAS,YAAY,OAA0C;AAC7D,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,iBAAiB,KAAM,QAAO;AAGlC,QAAM,aAAa,sBAAsB,KAAK,KAAK,IAAI,QAAQ,eAAe;AAC9E,QAAM,IAAI,IAAI,KAAK,UAAU;AAC7B,MAAI,MAAM,EAAE,QAAQ,CAAC,EAAG,OAAM,IAAI,MAAM,sBAAsB,KAAK,EAAE;AACrE,SAAO;AACT;AAEO,SAAS,uBACd,cACA,oBACA,SACA,OACA,KAAiC,IAAI,YAAY,GACnC;AACd,SAAO,IAAI;AAAA,IACT,YAAY,YAAY;AAAA,IACxB,YAAY,kBAAkB;AAAA,IAC9B;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["ComparisonOperator","LogicalOperator","AggregateOperator","ScalarFunction","DatePart","SortDirection","WindowFunction"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/model/relational.ts","../src/datafinder/attribute.ts","../src/datafinder/finder-registry.ts","../src/datafinder/scalar-functions.ts","../src/datafinder/typed-attributes.ts","../src/datafinder/expressions.ts","../src/datafinder/conditional.ts","../src/model/milestoning.ts","../src/datafinder/dialect.ts","../src/datafinder/sql-generator.ts","../src/datafinder/naming.ts","../src/datafinder/embedded.ts","../src/datafinder/finder.ts","../src/datafinder/runner.ts","../src/datafinder/databricks-runner.ts"],"sourcesContent":["export * from './datafinder/index';\nexport * from './model/relational';\nexport * from './model/milestoning';\n","export enum ComparisonOperator {\n EQUAL = 'EQUAL',\n NOT_EQUAL = 'NOT_EQUAL',\n LESS_THAN = 'LESS_THAN',\n GREATER_THAN = 'GREATER_THAN',\n LESS_THAN_OR_EQUAL_TO = 'LESS_THAN_OR_EQUAL_TO',\n GREATER_THAN_OR_EQUAL_TO = 'GREATER_THAN_OR_EQUAL_TO',\n LIKE = 'LIKE',\n NOT_LIKE = 'NOT_LIKE',\n}\n\n/** The character that makes the next one literal in a LIKE pattern built from a value (`contains`, `startsWith`, ...). */\nexport const LIKE_ESCAPE = '!';\n\n/**\n * `value` as part of a LIKE pattern that matches it literally: `%`, `_` and the escape character itself\n * would otherwise be wildcards.\n */\nexport function escapeLike(value: string): string {\n return value.replaceAll(LIKE_ESCAPE, LIKE_ESCAPE + LIKE_ESCAPE).replaceAll('%', LIKE_ESCAPE + '%').replaceAll('_', LIKE_ESCAPE + '_');\n}\n\nexport enum LogicalOperator {\n AND = 'AND',\n OR = 'OR',\n}\n\nexport enum AggregateOperator {\n COUNT = 'COUNT',\n SUM = 'SUM',\n MIN = 'MIN',\n MAX = 'MAX',\n AVERAGE = 'AVERAGE',\n STRING_AGG = 'STRING_AGG',\n COUNT_DISTINCT = 'COUNT_DISTINCT',\n STDDEV_SAMP = 'STDDEV_SAMP',\n STDDEV_POP = 'STDDEV_POP',\n VAR_SAMP = 'VAR_SAMP',\n VAR_POP = 'VAR_POP',\n BOOL_AND = 'BOOL_AND',\n BOOL_OR = 'BOOL_OR',\n}\n\nexport enum ScalarFunction {\n ABS = 'ABS',\n CEILING = 'CEILING',\n FLOOR = 'FLOOR',\n MOD = 'MOD',\n POWER = 'POWER',\n SQRT = 'SQRT',\n ROUND = 'ROUND',\n UPPER = 'UPPER',\n LOWER = 'LOWER',\n TRIM = 'TRIM',\n LTRIM = 'LTRIM',\n RTRIM = 'RTRIM',\n LENGTH = 'LENGTH',\n REVERSE = 'REVERSE',\n LEFT = 'LEFT',\n RIGHT = 'RIGHT',\n REPEAT = 'REPEAT',\n REPLACE = 'REPLACE',\n SUBSTRING = 'SUBSTRING',\n COALESCE = 'COALESCE',\n}\n\nexport enum DatePart {\n YEAR = 'YEAR',\n MONTH = 'MONTH',\n DAY = 'DAY',\n HOUR = 'HOUR',\n MINUTE = 'MINUTE',\n SECOND = 'SECOND',\n QUARTER = 'QUARTER',\n WEEK = 'WEEK',\n DOW = 'DOW',\n}\n\nexport enum SortDirection {\n ASC = 'ASC',\n DESC = 'DESC',\n}\n\nexport abstract class RelationalOperationElement {}\n\n/**\n * Something that can be a column of the result, so can be given a name there:\n * `f.price().sum().alias('Total')`. The name is held by an `Alias` that wraps the column.\n */\nexport interface Aliasable {\n alias(name: string): Alias;\n}\n\n/** Something the result can be ordered by: `f.id().count().ascending()`. */\nexport interface Sortable {\n /** Sort by this expression, smallest first. */\n ascending(): SortOperation;\n /** Sort by this expression, largest first. */\n descending(): SortOperation;\n}\n\nexport abstract class Operation extends RelationalOperationElement implements Aliasable {\n /** Name this column in the result: `f.price().sum().alias('Total')`, `f.age().gt(30).alias('Adult')`. */\n alias(name: string): Alias { return new Alias(this, name); }\n\n and(other: RelationalOperationElement): Operation {\n return new LogicalOperation(this, LogicalOperator.AND, other);\n }\n\n /** Combine with `other` using OR. A chain reads left to right: `a.or(b).and(c)` is `(a OR b) AND c`. */\n or(other: RelationalOperationElement): Operation {\n return new LogicalOperation(this, LogicalOperator.OR, other);\n }\n}\n\nexport class NoOperation extends Operation {\n and(other: RelationalOperationElement): Operation {\n return other as Operation;\n }\n\n /** No filter matches every row, so OR-ing anything with it still matches every row. */\n or(_other: RelationalOperationElement): Operation {\n return this;\n }\n}\n\nexport abstract class ConstantOperation extends RelationalOperationElement implements Aliasable, Sortable {\n /** Name this column in the result. */\n alias(name: string): Alias { return new Alias(this, name); }\n\n /** Sort by this expression, smallest first. */\n ascending(): SortOperation { return new SortOperation(this, SortDirection.ASC); }\n\n /** Sort by this expression, largest first. */\n descending(): SortOperation { return new SortOperation(this, SortDirection.DESC); }\n}\n\n/** A constant that is a number, so it can be an operand of arithmetic: `constant(100).minus(f.price())`. */\nexport abstract class NumericConstantOperation extends ConstantOperation {\n abstract readonly value: number;\n\n arithmeticOperand(): RelationalOperationElement { return this; }\n}\n\nexport class IntegerConstantOperation extends NumericConstantOperation {\n constructor(readonly value: number) { super(); }\n}\n\nexport class FloatConstantOperation extends NumericConstantOperation {\n constructor(readonly value: number) { super(); }\n}\n\nexport class StringConstantOperation extends ConstantOperation {\n constructor(readonly value: string) { super(); }\n}\n\n/** Matches a zone-less calendar date such as `2024-06-01`. */\nexport const DATE_ONLY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/**\n * A calendar date, held as UTC midnight. JavaScript has no date-only type, so this marks a `Date`\n * that was given as a date rather than a timestamp, and is rendered as a date literal (`'2024-06-01'`)\n * instead of a timestamp literal (`'2024-06-01 00:00:00'`).\n */\nexport class DateOnly extends Date {}\n\nexport class DateConstantOperation extends ConstantOperation {\n constructor(readonly value: Date) { super(); }\n}\n\nexport class DateTimeConstantOperation extends ConstantOperation {\n constructor(readonly value: Date) { super(); }\n}\n\nexport class DecimalConstantOperation extends NumericConstantOperation {\n constructor(readonly value: number) { super(); }\n}\n\nexport class BooleanConstantOperation extends ConstantOperation {\n constructor(readonly value: boolean) { super(); }\n}\n\nexport abstract class UnaryOperation extends Operation {\n constructor(readonly element: RelationalOperationElement) { super(); }\n}\n\nexport abstract class BinaryOperation extends Operation {\n constructor(\n readonly left: RelationalOperationElement,\n readonly right: RelationalOperationElement,\n ) { super(); }\n}\n\nexport class IsNullOperation extends UnaryOperation {}\n\nexport class IsNotNullOperation extends UnaryOperation {}\n\n/** The element is one of `values` (`element IN (...)`). */\nexport class InOperation extends UnaryOperation {\n constructor(element: RelationalOperationElement, readonly values: ConstantOperation[]) { super(element); }\n}\n\n/** The element is none of `values` (`element NOT IN (...)`). */\nexport class NotInOperation extends UnaryOperation {\n constructor(element: RelationalOperationElement, readonly values: ConstantOperation[]) { super(element); }\n}\n\nexport class ComparisonOperation extends BinaryOperation {\n constructor(\n left: RelationalOperationElement,\n readonly operator: ComparisonOperator,\n right: RelationalOperationElement,\n ) { super(left, right); }\n}\n\nexport class LogicalOperation extends BinaryOperation {\n constructor(\n left: RelationalOperationElement,\n readonly operator: LogicalOperator,\n right: RelationalOperationElement,\n ) { super(left, right); }\n}\n\nexport class WindowSpecification {\n constructor(\n readonly partitionBy: RelationalOperationElement[] = [],\n readonly orderBy: SortOperation[] = [],\n ) {}\n}\n\nexport class AggregateOperation extends UnaryOperation implements Sortable {\n /** Sort by this expression, smallest first. */\n ascending(): SortOperation { return new SortOperation(this, SortDirection.ASC); }\n\n /** Sort by this expression, largest first. */\n descending(): SortOperation { return new SortOperation(this, SortDirection.DESC); }\n\n constructor(\n element: RelationalOperationElement,\n readonly operator: AggregateOperator,\n readonly displayName?: string,\n readonly window?: WindowSpecification,\n /** For STRING_AGG: what goes between the values. */\n readonly separator?: string,\n /** For STRING_AGG: the order the values are joined in. */\n readonly orderBy: SortOperation[] = [],\n ) { super(element); }\n\n arithmeticOperand(): RelationalOperationElement { return this; }\n comparisonOperand(): RelationalOperationElement { return this; }\n\n over(partitionBy?: RelationalOperationElement[], orderBy?: SortOperation[]): AggregateOperation {\n return new AggregateOperation(this.element, this.operator, this.displayName,\n new WindowSpecification(partitionBy ?? [], orderBy ?? []), this.separator, this.orderBy);\n }\n}\n\nexport enum WindowFunction {\n ROW_NUMBER = 'ROW_NUMBER',\n RANK = 'RANK',\n DENSE_RANK = 'DENSE_RANK',\n NTILE = 'NTILE',\n LAG = 'LAG',\n LEAD = 'LEAD',\n FIRST_VALUE = 'FIRST_VALUE',\n LAST_VALUE = 'LAST_VALUE',\n CUME_DIST = 'CUME_DIST',\n PERCENT_RANK = 'PERCENT_RANK',\n}\n\nexport class WindowFunctionOperation extends UnaryOperation implements Sortable {\n /** Sort by this expression, smallest first. */\n ascending(): SortOperation { return new SortOperation(this, SortDirection.ASC); }\n\n /** Sort by this expression, largest first. */\n descending(): SortOperation { return new SortOperation(this, SortDirection.DESC); }\n\n constructor(\n element: RelationalOperationElement | null,\n readonly func: WindowFunction,\n readonly displayName?: string,\n readonly secondArg?: number,\n readonly extraArgs: (string | number)[] = [],\n readonly window?: WindowSpecification,\n ) { super(element as RelationalOperationElement); }\n\n over(partitionBy?: RelationalOperationElement[], orderBy?: SortOperation[]): WindowFunctionOperation {\n return new WindowFunctionOperation(this.element, this.func, this.displayName, this.secondArg,\n [...this.extraArgs], new WindowSpecification(partitionBy ?? [], orderBy ?? []));\n }\n}\n\nexport class ScalarFunctionOperation extends UnaryOperation implements Sortable {\n /** Sort by this expression, smallest first. */\n ascending(): SortOperation { return new SortOperation(this, SortDirection.ASC); }\n\n /** Sort by this expression, largest first. */\n descending(): SortOperation { return new SortOperation(this, SortDirection.DESC); }\n\n constructor(\n element: RelationalOperationElement,\n readonly func: ScalarFunction,\n readonly displayName?: string,\n readonly secondArg?: number,\n readonly extraArgs: (string | number | boolean)[] = [],\n ) { super(element); }\n\n /** This expression as an operand of a comparison. */\n comparisonOperand(): RelationalOperationElement { return this; }\n\n arithmeticOperand(): RelationalOperationElement { return this; }\n\n /** Only a function that gives a number can be used in arithmetic. */\n assertNumeric(): void {\n if (!NUMERIC_FUNCTIONS.has(this.func)) {\n throw new TypeError(`${this.func} does not give a number, so it cannot be used in arithmetic`);\n }\n }\n}\n\n/** The functions that give a number, which arithmetic and `Numeric` functions apply to. */\nexport const NUMERIC_FUNCTIONS: ReadonlySet<ScalarFunction> = new Set([\n ScalarFunction.ABS, ScalarFunction.CEILING, ScalarFunction.FLOOR, ScalarFunction.MOD,\n ScalarFunction.POWER, ScalarFunction.SQRT, ScalarFunction.ROUND, ScalarFunction.LENGTH,\n]);\n\nexport class DateExtractOperation extends UnaryOperation implements Sortable {\n /** Sort by this expression, smallest first. */\n ascending(): SortOperation { return new SortOperation(this, SortDirection.ASC); }\n\n /** Sort by this expression, largest first. */\n descending(): SortOperation { return new SortOperation(this, SortDirection.DESC); }\n\n constructor(\n element: RelationalOperationElement,\n readonly part: DatePart,\n readonly displayName?: string,\n ) { super(element); }\n}\n\n/** The first day of the week, month, quarter or year that the date falls in, as a date. */\nexport class DateTruncOperation extends UnaryOperation implements Sortable {\n constructor(\n element: RelationalOperationElement,\n readonly part: DatePart,\n readonly displayName?: string,\n ) { super(element); }\n\n /** Sort by this expression, earliest first. */\n ascending(): SortOperation { return new SortOperation(this, SortDirection.ASC); }\n\n /** Sort by this expression, latest first. */\n descending(): SortOperation { return new SortOperation(this, SortDirection.DESC); }\n\n comparisonOperand(): RelationalOperationElement { return this; }\n}\n\nexport class DateArithmeticOperation extends UnaryOperation implements Sortable {\n /** Sort by this expression, smallest first. */\n ascending(): SortOperation { return new SortOperation(this, SortDirection.ASC); }\n\n /** Sort by this expression, largest first. */\n descending(): SortOperation { return new SortOperation(this, SortDirection.DESC); }\n\n constructor(\n element: RelationalOperationElement,\n readonly n: number,\n readonly unit: DatePart,\n readonly isAdd: boolean = true,\n readonly displayName?: string,\n ) { super(element); }\n}\n\nexport class DateDiffOperation extends UnaryOperation implements Sortable {\n /** Sort by this expression, smallest first. */\n ascending(): SortOperation { return new SortOperation(this, SortDirection.ASC); }\n\n /** Sort by this expression, largest first. */\n descending(): SortOperation { return new SortOperation(this, SortDirection.DESC); }\n\n constructor(\n element: RelationalOperationElement,\n readonly other: Date,\n readonly unit: DatePart,\n readonly displayName?: string,\n ) { super(element); }\n}\n\nexport class Column extends RelationalOperationElement {\n table?: Table;\n /** Whether the column may hold NULL. As in Legend, a primary key is never null. */\n readonly nullable: boolean;\n\n constructor(\n readonly name: string,\n readonly type: string,\n readonly owner?: string,\n readonly primaryKey: boolean = false,\n nullable: boolean = true,\n ) {\n super();\n this.nullable = nullable && !primaryKey;\n }\n}\n\nexport class ForeignKey {\n constructor(readonly column: Column, readonly references: Column) {}\n}\n\nexport abstract class DataStore {\n readonly schemas: Schema[] = [];\n\n constructor(readonly name: string) {}\n\n abstract namespace(schemaName: string): string;\n}\n\nexport class Database extends DataStore {\n constructor(name: string, readonly location?: string) { super(name); }\n\n namespace(schemaName: string): string { return schemaName; }\n}\n\nexport class DataCatalog extends DataStore {\n constructor(name: string) { super(name); }\n\n namespace(schemaName: string): string { return `${this.name}.${schemaName}`; }\n}\n\nexport class Schema {\n readonly tables: Table[] = [];\n\n constructor(readonly name: string, readonly datastore?: DataStore) {\n datastore?.schemas.push(this);\n }\n}\n\nexport class Table {\n private readonly _columnsByName: Map<string, Column> = new Map();\n readonly foreignKeys: ForeignKey[] = [];\n\n constructor(readonly name: string, columns: Column[], readonly schema?: Schema) {\n for (const col of columns) {\n if (this._columnsByName.has(col.name)) {\n throw new Error(`Duplicate column name '${col.name}' in table '${name}'`);\n }\n this._columnsByName.set(col.name, col);\n col.table = this;\n }\n schema?.tables.push(this);\n }\n\n get columns(): Column[] {\n return Array.from(this._columnsByName.values());\n }\n\n get qualifiedName(): string {\n if (!this.schema) return this.name;\n if (!this.schema.datastore) return `${this.schema.name}.${this.name}`;\n return `${this.schema.datastore.namespace(this.schema.name)}.${this.name}`;\n }\n}\n\nexport class JoinOperation {\n filter?: RelationalOperationElement;\n /** Property-equality filters on the join target (property id -> value), set by a related finder given a filter. */\n filterKwargs: Record<string, unknown> = {};\n /** Maps property ids to [column, type, table] for `filterKwargs`. */\n filterColumnMap: Record<string, [string, string, string]> = {};\n\n constructor(\n readonly name: string,\n readonly target: Table,\n readonly left: Column,\n readonly right: Column,\n filter?: RelationalOperationElement,\n ) {\n this.filter = filter;\n }\n}\n\nexport class JoinTreeNodeOperation {\n constructor(\n readonly join: JoinOperation,\n readonly parent?: JoinTreeNodeOperation,\n /**\n * True when the property this step follows is to-many, so a value read through it repeats the row. As in\n * Pure, that is the multiplicity of the property, not something the join itself says.\n */\n readonly many: boolean = false,\n /** True when the property this step follows can be missing (its lower bound is 0). */\n readonly optional: boolean = false,\n ) {}\n}\n\nexport class ColumnWithJoin extends RelationalOperationElement {\n /**\n * `embedded` is an alternate reference to a flat (denormalized) column on the owning table that\n * holds the same value without the join; the SQL generator uses it when the join can be elided.\n */\n constructor(\n readonly column: Column,\n readonly parent?: JoinTreeNodeOperation,\n readonly embedded?: ColumnWithJoin,\n private readonly _optional: boolean = false,\n ) { super(); }\n\n /** Whether the value can be missing: its property is optional, or a navigation on the way to it is. */\n get optional(): boolean {\n for (let node = this.parent; node !== undefined; node = node.parent) {\n if (node.optional) return true;\n }\n return this._optional;\n }\n}\n\nexport class SortOperation {\n constructor(\n /** What the rows are ordered by: a column, or an expression such as an aggregate. */\n readonly column: RelationalOperationElement,\n readonly direction: SortDirection,\n ) {}\n}\n\nexport class CountAllOperation extends RelationalOperationElement implements Aliasable, Sortable {\n /** Name this column in the result. */\n alias(name: string): Alias { return new Alias(this, name); }\n\n /** Sort by this expression, smallest first. */\n ascending(): SortOperation { return new SortOperation(this, SortDirection.ASC); }\n\n /** Sort by this expression, largest first. */\n descending(): SortOperation { return new SortOperation(this, SortDirection.DESC); }\n\n constructor(readonly table: string) { super(); }\n\n comparisonOperand(): RelationalOperationElement { return this; }\n}\n\n/**\n * A column of the result under another name, wrapping the column it names. Only things that can be a\n * column of the result have `alias()` (an `Attribute`, an aggregate, a function, a constant, ...), so a\n * filter cannot be aliased; aliasing an alias replaces its name.\n */\nexport class Alias extends RelationalOperationElement implements Aliasable, Sortable {\n constructor(readonly element: RelationalOperationElement, readonly name: string) { super(); }\n\n alias(name: string): Alias { return new Alias(this.element, name); }\n\n /** Sorts by the column the alias names. */\n ascending(): SortOperation { return new SortOperation(this.element, SortDirection.ASC); }\n\n /** Sorts by the column the alias names. */\n descending(): SortOperation { return new SortOperation(this.element, SortDirection.DESC); }\n}\n\n/** `CASE WHEN condition THEN then ELSE fallback END`; without a `fallback` the value is NULL. */\nexport class CaseOperation extends Operation {\n constructor(\n readonly condition: RelationalOperationElement,\n readonly then: RelationalOperationElement,\n readonly fallback?: RelationalOperationElement,\n readonly displayName?: string,\n ) { super(); }\n}\n\n/** Returned by `RelatedFinder.exists()`. A backend translates it to a join-presence check. */\nexport class ExistsOperation extends RelationalOperationElement implements Aliasable {\n /** Name this column in the result. */\n alias(name: string): Alias { return new Alias(this, name); }\n\n constructor(readonly node: JoinTreeNodeOperation) { super(); }\n\n and(other: RelationalOperationElement): LogicalOperation {\n return new LogicalOperation(this, LogicalOperator.AND, other);\n }\n\n or(other: RelationalOperationElement): LogicalOperation {\n return new LogicalOperation(this, LogicalOperator.OR, other);\n }\n}\n\n/** Returned by `RelatedFinder.notExists()`. A backend translates it to a join-absence check. */\nexport class NotExistsOperation extends RelationalOperationElement implements Aliasable {\n /** Name this column in the result. */\n alias(name: string): Alias { return new Alias(this, name); }\n\n constructor(readonly node: JoinTreeNodeOperation) { super(); }\n\n and(other: RelationalOperationElement): LogicalOperation {\n return new LogicalOperation(this, LogicalOperator.AND, other);\n }\n\n or(other: RelationalOperationElement): LogicalOperation {\n return new LogicalOperation(this, LogicalOperator.OR, other);\n }\n}\n\nexport class SelectOperation {\n constructor(\n readonly display: RelationalOperationElement[],\n readonly filter: RelationalOperationElement,\n readonly orderBy: SortOperation[] = [],\n readonly groupBy: RelationalOperationElement[] = [],\n readonly limit?: number,\n readonly table?: Table,\n /**\n * Extra ON conditions for this query's joins (milestoning and property filters), keyed by join node.\n * Held here rather than on the shared JoinOperation, so queries that use the same node can't affect each other.\n */\n readonly joinFilters: ReadonlyMap<JoinTreeNodeOperation, Operation> = new Map(),\n /** Whether each distinct row is returned once (`SELECT DISTINCT`). */\n readonly distinct: boolean = false,\n /** How many rows to skip before the first one returned. */\n readonly offset?: number,\n /** Keeps the groups that satisfy it (`HAVING`). */\n readonly having?: Operation,\n ) {}\n}\n\n/** Whether `op` holds an aggregate, a window function or a count. */\nexport function containsAggregateOrWindow(op: unknown): boolean {\n if (op instanceof AggregateOperation || op instanceof WindowFunctionOperation || op instanceof CountAllOperation) return true;\n if (op instanceof BinaryOperation) return containsAggregateOrWindow(op.left) || containsAggregateOrWindow(op.right);\n if (op instanceof UnaryOperation || op instanceof Alias) return containsAggregateOrWindow(op.element);\n return false;\n}\n\n/** Whether `op` collapses rows: an aggregate or a count. Window functions keep every row. */\nexport function containsAggregate(op: unknown): boolean {\n if (op instanceof AggregateOperation || op instanceof CountAllOperation) return true;\n if (op instanceof BinaryOperation) return containsAggregate(op.left) || containsAggregate(op.right);\n if (op instanceof UnaryOperation || op instanceof Alias) return containsAggregate(op.element);\n return false;\n}\n\n/** A plain value as the constant it compares with. */\nexport function valueOperand(value: unknown): ConstantOperation {\n if (typeof value === 'boolean') return new BooleanConstantOperation(value);\n if (typeof value === 'number' && Number.isFinite(value)) {\n return Number.isInteger(value) ? new IntegerConstantOperation(value) : new FloatConstantOperation(value);\n }\n if (typeof value === 'string') return new StringConstantOperation(value);\n if (value instanceof DateOnly) return new DateConstantOperation(value); // before Date: DateOnly is a Date\n if (value instanceof Date) return new DateTimeConstantOperation(value);\n throw new TypeError(`A value to compare with is a boolean, a finite number, a string or a date, not ${value === null ? 'null' : typeof value}`);\n}\n\n/** The thing to compare or calculate with: an expression as it is, an attribute as its column, a value as a constant. */\nexport function operandOf(other: unknown): RelationalOperationElement {\n if (other instanceof RelationalOperationElement) return other;\n if (typeof (other as { cwj?: unknown } | null)?.cwj === 'function') return (other as { cwj(): ColumnWithJoin }).cwj();\n return valueOperand(other);\n}\n\n/**\n * Comparisons for an expression, as for a column: `f.name().toUpperCase().eq('ACME')`, `f.name().length().gt(10)`.\n * The other side is a value or another expression. Each gives a filter. Mixed into the expressions that have it.\n */\nexport abstract class Comparable {\n abstract comparisonOperand(): RelationalOperationElement;\n\n private _compared(operator: ComparisonOperator, other: unknown): ComparisonOperation {\n return new ComparisonOperation(this.comparisonOperand(), operator, operandOf(other));\n }\n\n /** Filter to rows where this expression equals `other`. */\n eq(other: unknown): ComparisonOperation { return this._compared(ComparisonOperator.EQUAL, other); }\n /** Filter to rows where this expression does not equal `other`. */\n ne(other: unknown): ComparisonOperation { return this._compared(ComparisonOperator.NOT_EQUAL, other); }\n /** Filter to rows where this expression is less than `other`. */\n lt(other: unknown): ComparisonOperation { return this._compared(ComparisonOperator.LESS_THAN, other); }\n /** Filter to rows where this expression is at most `other`. */\n lte(other: unknown): ComparisonOperation { return this._compared(ComparisonOperator.LESS_THAN_OR_EQUAL_TO, other); }\n /** Filter to rows where this expression is greater than `other`. */\n gt(other: unknown): ComparisonOperation { return this._compared(ComparisonOperator.GREATER_THAN, other); }\n /** Filter to rows where this expression is at least `other`. */\n gte(other: unknown): ComparisonOperation { return this._compared(ComparisonOperator.GREATER_THAN_OR_EQUAL_TO, other); }\n}\n\n/** Whether a standard deviation or variance is the sample one (`ddof` 1) or the population one (0). */\nexport function sample(ddof: number): boolean {\n if (ddof !== 0 && ddof !== 1) throw new RangeError(`ddof is 0 (population) or 1 (sample), not ${ddof}`);\n return ddof === 1;\n}\n\n/**\n * Pattern tests on an expression that holds text, as on a column: `f.name().toUpperCase().startsWith('AC')`,\n * `f.name().join(',').contains('John')`. Mixed into the expressions that have it.\n */\nexport abstract class StringPredicates {\n abstract comparisonOperand(): RelationalOperationElement;\n\n private _like(pattern: string): ComparisonOperation {\n return new ComparisonOperation(this.comparisonOperand(), ComparisonOperator.LIKE, new StringConstantOperation(pattern));\n }\n\n /** Filter to rows where this text contains `value`. */\n contains(value: string): ComparisonOperation { return this._like(`%${escapeLike(value)}%`); }\n /** Filter to rows where this text starts with `prefix`. */\n startsWith(prefix: string): ComparisonOperation { return this._like(`${escapeLike(prefix)}%`); }\n /** Filter to rows where this text ends with `suffix`. */\n endsWith(suffix: string): ComparisonOperation { return this._like(`%${escapeLike(suffix)}`); }\n}\n\n/**\n * Aggregates of an expression, as a column has them: `f.price().times(f.quantity()).sum()`, `constant(1).sum()`,\n * `when(f.price().gt(10)).then(5.0).otherwise(1.0).sum()`. Mixed into the expressions that have it.\n */\nexport abstract class Aggregates {\n private _aggregate(operator: AggregateOperator, label: string): AggregateOperation {\n return new AggregateOperation(this as unknown as RelationalOperationElement, operator, label + ' Expression');\n }\n\n /** Sum of the values in the group. */\n sum(): AggregateOperation { return this._aggregate(AggregateOperator.SUM, 'Sum'); }\n /** Smallest value in the group. */\n min(): AggregateOperation { return this._aggregate(AggregateOperator.MIN, 'Min'); }\n /** Largest value in the group. */\n max(): AggregateOperation { return this._aggregate(AggregateOperator.MAX, 'Max'); }\n /** Arithmetic mean of the values in the group. */\n average(): AggregateOperation { return this._aggregate(AggregateOperator.AVERAGE, 'Average'); }\n /** Number of non-null values in the group. */\n count(): AggregateOperation { return this._aggregate(AggregateOperator.COUNT, 'Count'); }\n /** Standard deviation of the values in the group: the sample one by default, `ddof = 0` for the population one. */\n std(ddof = 1): AggregateOperation {\n return this._aggregate(sample(ddof) ? AggregateOperator.STDDEV_SAMP : AggregateOperator.STDDEV_POP, 'Std');\n }\n /** Variance of the values in the group: the sample one by default, `ddof = 0` for the population one. */\n var(ddof = 1): AggregateOperation {\n return this._aggregate(sample(ddof) ? AggregateOperator.VAR_SAMP : AggregateOperator.VAR_POP, 'Var');\n }\n}\n\n/**\n * Aggregates of a condition: `f.quantity().gt(20).all()` is true for a group where every row holds, `.any()` where at\n * least one does. Mixed into the conditions.\n */\nexport abstract class BooleanAggregates {\n /** True for a group where every row satisfies the condition. */\n all(): AggregateOperation {\n return new AggregateOperation(this as unknown as RelationalOperationElement, AggregateOperator.BOOL_AND, 'All Expression');\n }\n /** True for a group where at least one row satisfies the condition. */\n any(): AggregateOperation {\n return new AggregateOperation(this as unknown as RelationalOperationElement, AggregateOperator.BOOL_OR, 'Any Expression');\n }\n}\n\n/**\n * Mix the methods of the base classes into `derived`, the TypeScript handbook's way to inherit from more than\n * one class: the type side comes from an `interface Derived extends Base {}` beside the class.\n */\nexport function applyMixins(derived: { prototype: object }, bases: { prototype: object }[]): void {\n for (const base of bases) {\n for (const name of Object.getOwnPropertyNames(base.prototype)) {\n if (name === 'constructor' || Object.prototype.hasOwnProperty.call(derived.prototype, name)) continue;\n Object.defineProperty(derived.prototype, name, Object.getOwnPropertyDescriptor(base.prototype, name)!);\n }\n }\n}\n\nexport enum ArithmeticOperator {\n ADD = '+',\n SUBTRACT = '-',\n MULTIPLY = '*',\n DIVIDE = '/',\n}\n\n/** A number or a numeric expression: what arithmetic takes on the other side. */\nexport type ArithmeticOperand = number | { arithmeticOperand(): RelationalOperationElement };\n\n/**\n * `plus`, `minus`, `times` and `dividedBy` for an expression that holds a number: `f.price().times(f.quantity())`,\n * `f.price().plus(1.5)`, `constant(100).minus(f.price())`. The other operand is a number or another numeric\n * expression. Mixed into the expressions that have it.\n */\nexport abstract class Arithmetic {\n abstract arithmeticOperand(): RelationalOperationElement;\n\n /** Raises if this expression is not a number. */\n assertNumeric(): void {}\n\n private _arithmetic(operator: ArithmeticOperator, other: ArithmeticOperand): ArithmeticOperation {\n this.assertNumeric();\n let operand: RelationalOperationElement;\n if (typeof other === 'number') {\n if (!Number.isFinite(other)) throw new TypeError('Arithmetic is between numbers and numeric columns, not a non-finite number');\n operand = valueOperand(other);\n } else if (other !== null && typeof other === 'object' && typeof other.arithmeticOperand === 'function') {\n (other as unknown as Arithmetic).assertNumeric?.();\n operand = other.arithmeticOperand();\n } else {\n throw new TypeError(`Arithmetic is between numbers and numeric columns, not ${other === null ? 'null' : typeof other}`);\n }\n return new ArithmeticOperation(this.arithmeticOperand(), operator, operand);\n }\n\n /** `this + other`. */\n plus(other: ArithmeticOperand): ArithmeticOperation { return this._arithmetic(ArithmeticOperator.ADD, other); }\n /** `this - other`. */\n minus(other: ArithmeticOperand): ArithmeticOperation { return this._arithmetic(ArithmeticOperator.SUBTRACT, other); }\n /** `this * other`. */\n times(other: ArithmeticOperand): ArithmeticOperation { return this._arithmetic(ArithmeticOperator.MULTIPLY, other); }\n /** `this / other`. */\n dividedBy(other: ArithmeticOperand): ArithmeticOperation { return this._arithmetic(ArithmeticOperator.DIVIDE, other); }\n}\n\n/** `left operator right` on numbers, e.g. `price * quantity`. */\nexport class ArithmeticOperation extends BinaryOperation implements Sortable {\n constructor(\n left: RelationalOperationElement,\n readonly operator: ArithmeticOperator,\n right: RelationalOperationElement,\n readonly displayName?: string,\n ) { super(left, right); }\n\n /** Sort by this expression, smallest first. */\n ascending(): SortOperation { return new SortOperation(this, SortDirection.ASC); }\n\n /** Sort by this expression, largest first. */\n descending(): SortOperation { return new SortOperation(this, SortDirection.DESC); }\n\n arithmeticOperand(): RelationalOperationElement { return this; }\n comparisonOperand(): RelationalOperationElement { return this; }\n}\n\n/** Text joined end to end. A NULL in any part makes the whole NULL, as with SQL's `||`. */\nexport class ConcatOperation extends Operation implements Sortable {\n constructor(\n readonly parts: RelationalOperationElement[],\n readonly displayName?: string,\n ) { super(); }\n\n /** Join more text on the end: `f.first().concat(' ', f.last())`. A concatenation joins into one. */\n concat(...more: ConcatPart[]): ConcatOperation { return concat(this, ...more); }\n\n /** Sort by this expression, smallest first. */\n ascending(): SortOperation { return new SortOperation(this, SortDirection.ASC); }\n\n /** Sort by this expression, largest first. */\n descending(): SortOperation { return new SortOperation(this, SortDirection.DESC); }\n\n comparisonOperand(): RelationalOperationElement { return this; }\n}\n\n/** What can be joined as text: a string, a text column, a function that gives text, or another concatenation. */\nexport type ConcatPart = string | { functionInput(): RelationalOperationElement } | ConcatOperation;\n\n/**\n * Join text: `concat(f.name(), ' (', f.category(), ')')`. A string is a constant; a concatenation among the\n * parts is flattened into one.\n */\nexport function concat(...parts: ConcatPart[]): ConcatOperation {\n const partsOf = (part: ConcatPart): RelationalOperationElement[] => {\n if (part instanceof ConcatOperation) return part.parts;\n if (typeof part === 'string') return [new StringConstantOperation(part)];\n if (part instanceof RelationalOperationElement) return [part];\n if (part !== null && typeof part === 'object' && typeof part.functionInput === 'function') return [part.functionInput()];\n throw new TypeError(`Text is joined with text, not ${part === null ? 'null' : typeof part}`);\n };\n return new ConcatOperation(parts.flatMap(partsOf));\n}\n\nexport interface ConcatOperation extends Comparable, StringPredicates {}\napplyMixins(ConcatOperation, [Comparable, StringPredicates]);\n\nexport interface DateTruncOperation extends Comparable {}\napplyMixins(DateTruncOperation, [Comparable]);\n\nexport interface ArithmeticOperation extends Arithmetic, Comparable {}\napplyMixins(ArithmeticOperation, [Arithmetic, Comparable]);\n\nexport interface ScalarFunctionOperation extends Comparable, Arithmetic, StringPredicates {}\napplyMixins(ScalarFunctionOperation, [Comparable, Arithmetic, StringPredicates]);\n\nexport interface AggregateOperation extends Arithmetic, Comparable, StringPredicates {}\napplyMixins(AggregateOperation, [Arithmetic, Comparable, StringPredicates]);\n\nexport interface CountAllOperation extends Comparable {}\napplyMixins(CountAllOperation, [Comparable]);\n\nexport interface NumericConstantOperation extends Arithmetic {}\napplyMixins(NumericConstantOperation, [Arithmetic]);\n\nexport interface ConstantOperation extends Aggregates {}\napplyMixins(ConstantOperation, [Aggregates]);\n\nexport interface ArithmeticOperation extends Aggregates {}\napplyMixins(ArithmeticOperation, [Aggregates]);\n\nexport interface ScalarFunctionOperation extends Aggregates {}\napplyMixins(ScalarFunctionOperation, [Aggregates]);\n\nexport interface CaseOperation extends Aggregates {}\napplyMixins(CaseOperation, [Aggregates]);\n\nexport interface IsNullOperation extends BooleanAggregates {}\napplyMixins(IsNullOperation, [BooleanAggregates]);\n\nexport interface IsNotNullOperation extends BooleanAggregates {}\napplyMixins(IsNotNullOperation, [BooleanAggregates]);\n\nexport interface InOperation extends BooleanAggregates {}\napplyMixins(InOperation, [BooleanAggregates]);\n\nexport interface NotInOperation extends BooleanAggregates {}\napplyMixins(NotInOperation, [BooleanAggregates]);\n\nexport interface ComparisonOperation extends BooleanAggregates {}\napplyMixins(ComparisonOperation, [BooleanAggregates]);\n\nexport interface LogicalOperation extends BooleanAggregates {}\napplyMixins(LogicalOperation, [BooleanAggregates]);\n","import {\n Column,\n AggregateOperation,\n AggregateOperator,\n ColumnWithJoin,\n SortOperation,\n SortDirection,\n IsNullOperation,\n IsNotNullOperation,\n InOperation,\n NotInOperation,\n ConstantOperation,\n JoinTreeNodeOperation,\n Alias,\n RelationalOperationElement,\n Aliasable,\n ScalarFunction,\n ScalarFunctionOperation,\n WindowFunction,\n WindowFunctionOperation,\n WindowSpecification,\n} from '../model/relational';\n\n/** A value an attribute can be compared with in `isIn` / `isNotIn`. */\nexport type AttributeValue = string | number | boolean | Date;\n\nexport abstract class Attribute implements Aliasable {\n private readonly _displayName: string;\n private readonly _column: Column;\n private readonly _owner: string;\n private readonly _parent?: JoinTreeNodeOperation;\n private readonly _embedded?: Attribute;\n private readonly _optional: boolean;\n\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n embedded?: Attribute,\n nullable: boolean = true,\n optional: boolean = false,\n ) {\n this._optional = optional;\n this._displayName = displayName;\n this._column = new Column(columnName, columnDbType, owner, false, nullable);\n this._owner = owner;\n this._parent = parent;\n this._embedded = embedded;\n }\n\n column(): Column { return this._column; }\n owner(): string { return this._owner; }\n parent(): JoinTreeNodeOperation | undefined { return this._parent; }\n displayName(): string { return this._displayName; }\n\n /** Alternate attribute on a flat column of the owning table, used in place of this one when its join is elided. */\n embedded(): Attribute | undefined { return this._embedded; }\n\n /** @internal The expression a function of this attribute applies to: its column. */\n functionInput(): RelationalOperationElement {\n return this.cwj();\n }\n\n /** @internal What a function of this attribute is labelled after: its display name. */\n functionLabel(): string {\n return this._displayName;\n }\n\n /** @internal This attribute as an operand of arithmetic: its column. */\n arithmeticOperand(): RelationalOperationElement {\n return this.cwj();\n }\n\n cwj(): ColumnWithJoin {\n return new ColumnWithJoin(this._column, this._parent, this._embedded?.cwj(), this._optional);\n }\n\n /** Count the number of non-null values. Use in a projection with `groupBy` to aggregate per group. */\n count(): AggregateOperation {\n return new AggregateOperation(\n this.cwj(),\n AggregateOperator.COUNT,\n this._displayName + ' Count',\n );\n }\n\n /** Name this column in the result: `f.price().sum().alias('Total')`. */\n alias(name: string): Alias {\n return new Alias(this, name);\n }\n\n /** The number of different non-NULL values in the group: `COUNT(DISTINCT column)`. Use with `groupBy` to count per group. */\n countDistinct(): AggregateOperation {\n return new AggregateOperation(this.cwj(), AggregateOperator.COUNT_DISTINCT, this._displayName + ' Count Distinct');\n }\n\n /** The value, or `defaultValue` when it is NULL: `name().orElse('N/A')`. Like `COALESCE` in SQL. */\n orElse(defaultValue: string | number | boolean): ScalarFunctionOperation {\n if (!['string', 'number', 'boolean'].includes(typeof defaultValue)) {\n throw new TypeError(`An orElse default is a string, number or boolean, not ${defaultValue === null ? 'null' : typeof defaultValue}`);\n }\n return new ScalarFunctionOperation(this.cwj(), ScalarFunction.COALESCE, 'Or Else ' + this._displayName, undefined, [defaultValue]);\n }\n\n /** Sort this attribute in ascending order. Pass to `orderBy` or a window function's `orderBy`. */\n ascending(): SortOperation {\n return new SortOperation(this.cwj(), SortDirection.ASC);\n }\n\n /** Sort this attribute in descending order. Pass to `orderBy` or a window function's `orderBy`. */\n descending(): SortOperation {\n return new SortOperation(this.cwj(), SortDirection.DESC);\n }\n\n /** Filter to rows where this attribute has no value. */\n isNull(): IsNullOperation {\n return new IsNullOperation(this.cwj());\n }\n\n /** Filter to rows where this attribute has a value. */\n isNotNull(): IsNotNullOperation {\n return new IsNotNullOperation(this.cwj());\n }\n\n /** Wrap a value as a constant of this attribute's type. Overridden by the typed attributes. */\n protected toConstant(_value: AttributeValue): ConstantOperation {\n throw new TypeError(`${this.constructor.name} does not support isIn / isNotIn`);\n }\n\n private _constants(values: readonly AttributeValue[]): ConstantOperation[] {\n const constants = values.map(v => this.toConstant(v));\n if (constants.length === 0) throw new Error('isIn / isNotIn need at least one value');\n return constants;\n }\n\n /** Filter to rows where this attribute equals any of `values`. */\n isIn(values: readonly AttributeValue[]): InOperation {\n return new InOperation(this.cwj(), this._constants(values));\n }\n\n /** Filter to rows where this attribute equals none of `values`. Rows with no value are excluded, as in SQL. */\n isNotIn(values: readonly AttributeValue[]): NotInOperation {\n return new NotInOperation(this.cwj(), this._constants(values));\n }\n\n private _windowSpec(\n partitionBy?: Attribute | ColumnWithJoin | (Attribute | ColumnWithJoin)[],\n orderBy?: SortOperation | SortOperation[],\n ): WindowSpecification {\n const pbArr = partitionBy === undefined ? [] : Array.isArray(partitionBy) ? partitionBy : [partitionBy];\n const pb = pbArr.map(x => x instanceof Attribute ? x.cwj() : x);\n const ob = orderBy === undefined ? [] : Array.isArray(orderBy) ? orderBy : [orderBy];\n return new WindowSpecification(pb, ob);\n }\n\n /**\n * Assign a rank to each row within the ordered window, following pandas `Series.rank` conventions.\n *\n * `method` controls tie-breaking (default `'min'`):\n * - `'min'` — tied rows share the lowest rank; the next rank skips.\n * - `'dense'` — like `'min'` but ranks are contiguous (no gaps).\n * - `'first'` — each row gets a unique sequential integer (no ties).\n * - `'max'` — only meaningful with `pct: true` (see below).\n *\n * When `pct: true` the result is a relative rank between 0 and 1:\n * - `method: 'min'` (default) → fraction of values strictly below this row (PERCENT_RANK).\n * - `method: 'max'` → fraction of values at or below this row (cumulative distribution).\n *\n * `partitionBy` restarts the ranking within each group of distinct values.\n */\n rank(opts: {\n method?: 'min' | 'dense' | 'first' | 'max';\n pct?: boolean;\n partitionBy?: Attribute | ColumnWithJoin | (Attribute | ColumnWithJoin)[];\n orderBy?: SortOperation | SortOperation[];\n } = {}): WindowFunctionOperation {\n const { method = 'min', pct = false, partitionBy, orderBy } = opts;\n let func: WindowFunction;\n let name: string;\n if (pct) {\n if (method === 'max') { func = WindowFunction.CUME_DIST; name = 'Cume Dist'; }\n else { func = WindowFunction.PERCENT_RANK; name = 'Percent Rank'; }\n } else if (method === 'first') { func = WindowFunction.ROW_NUMBER; name = 'Row Number'; }\n else if (method === 'dense') { func = WindowFunction.DENSE_RANK; name = 'Dense Rank'; }\n else { func = WindowFunction.RANK; name = 'Rank'; }\n return new WindowFunctionOperation(null, func, name, undefined, [], this._windowSpec(partitionBy, orderBy));\n }\n\n /**\n * Split rows into `buckets` equal-sized quantile bins ordered by `orderBy`.\n * Each row receives a bucket number from 1 (lowest) to `buckets` (highest).\n * Named after `pandas.qcut`.\n */\n qcut(buckets: number, opts: {\n partitionBy?: Attribute | ColumnWithJoin | (Attribute | ColumnWithJoin)[];\n orderBy?: SortOperation | SortOperation[];\n } = {}): WindowFunctionOperation {\n return new WindowFunctionOperation(null, WindowFunction.NTILE, 'Quantile', buckets, [],\n this._windowSpec(opts.partitionBy, opts.orderBy));\n }\n\n /**\n * Return the value of this attribute from `periods` rows earlier (positive) or later (negative)\n * within the ordered window, following `pandas.Series.shift`.\n * Rows with no neighbour at the given offset return `null` (or `fillValue` if provided).\n */\n shift(periods = 1, opts: {\n fillValue?: string | number;\n partitionBy?: Attribute | ColumnWithJoin | (Attribute | ColumnWithJoin)[];\n orderBy?: SortOperation | SortOperation[];\n } = {}): WindowFunctionOperation {\n const extraArgs: (string | number)[] = opts.fillValue !== undefined ? [opts.fillValue] : [];\n const func = periods >= 0 ? WindowFunction.LAG : WindowFunction.LEAD;\n const label = periods >= 0 ? 'Lag' : 'Lead';\n return new WindowFunctionOperation(\n this.cwj(),\n func,\n label + ' ' + this._displayName,\n Math.abs(periods),\n extraArgs,\n this._windowSpec(opts.partitionBy, opts.orderBy),\n );\n }\n\n /**\n * Return the first value of this attribute in the window frame.\n * Use `partitionBy` to restart the frame for each group.\n */\n first(opts: {\n partitionBy?: Attribute | ColumnWithJoin | (Attribute | ColumnWithJoin)[];\n orderBy?: SortOperation | SortOperation[];\n } = {}): WindowFunctionOperation {\n return new WindowFunctionOperation(\n this.cwj(),\n WindowFunction.FIRST_VALUE,\n 'First ' + this._displayName,\n undefined, [],\n this._windowSpec(opts.partitionBy, opts.orderBy),\n );\n }\n\n /**\n * Return the last value of this attribute in the window frame.\n * Use `partitionBy` to restart the frame for each group.\n */\n last(opts: {\n partitionBy?: Attribute | ColumnWithJoin | (Attribute | ColumnWithJoin)[];\n orderBy?: SortOperation | SortOperation[];\n } = {}): WindowFunctionOperation {\n return new WindowFunctionOperation(\n this.cwj(),\n WindowFunction.LAST_VALUE,\n 'Last ' + this._displayName,\n undefined, [],\n this._windowSpec(opts.partitionBy, opts.orderBy),\n );\n }\n}\n","const _registry = new Map<string, new (...args: any[]) => unknown>();\n\nexport function registerRelatedFinderClass(name: string, cls: new (...args: any[]) => unknown): void {\n _registry.set(name, cls);\n}\n\nexport function getRelatedFinderClass(name: string): (new (...args: any[]) => unknown) | undefined {\n return _registry.get(name);\n}\n","/**\n * Scalar functions as methods, shared by attributes and by the results of other functions, so they chain:\n * `f.name().toUpperCase().length()`.\n *\n * TypeScript has no multiple inheritance, so each group of functions is a class whose methods are mixed into\n * every host with `applyMixins` (the handbook's pattern), the type side being an `interface Host extends Group {}`\n * beside the host. A host provides `functionInput()` and `functionLabel()`: an attribute reads its column and is\n * labelled by its display name; a function result is itself the input and is labelled by its own name.\n */\nimport {\n ConcatOperation,\n ConcatPart,\n RelationalOperationElement,\n concat,\n ScalarFunction,\n ScalarFunctionOperation,\n applyMixins,\n} from '../model/relational';\n\n/** A function result that gives text, which has the string functions too: `f.name().toUpperCase().length()`. */\nexport class StringFunctionOperation extends ScalarFunctionOperation {\n functionInput(): RelationalOperationElement { return this; }\n functionLabel(): string { return labelOf(this); }\n}\n\n/** A function result that gives a number, which has the numeric functions too. */\nexport class NumericFunctionOperation extends ScalarFunctionOperation {\n functionInput(): RelationalOperationElement { return this; }\n functionLabel(): string { return labelOf(this); }\n}\n\nfunction labelOf(operation: ScalarFunctionOperation): string {\n return operation.displayName ?? operation.func.charAt(0) + operation.func.slice(1).toLowerCase();\n}\n\nfunction stringFunction(\n element: RelationalOperationElement, func: ScalarFunction, label: string,\n secondArg?: number, extraArgs: (string | number)[] = [],\n): StringFunctionOperation {\n return new StringFunctionOperation(element, func, label, secondArg, extraArgs);\n}\n\nfunction numberFunction(\n element: RelationalOperationElement, func: ScalarFunction, label: string, secondArg?: number,\n): NumericFunctionOperation {\n return new NumericFunctionOperation(element, func, label, secondArg);\n}\n\n/** Functions of text. */\nexport abstract class StringFunctions {\n /** @internal The expression the function applies to. */\n abstract functionInput(): RelationalOperationElement;\n /** @internal What a function of this is labelled after. */\n abstract functionLabel(): string;\n\n /** Join text on the end: `f.first().concat(' ', f.last())`. A NULL part makes the whole NULL. */\n concat(...more: ConcatPart[]): ConcatOperation {\n return concat(this as unknown as ConcatPart, ...more);\n }\n\n /** Convert every character to uppercase. */\n toUpperCase(): StringFunctionOperation {\n return stringFunction(this.functionInput(), ScalarFunction.UPPER, 'Upper ' + this.functionLabel());\n }\n /** Convert every character to lowercase. */\n toLowerCase(): StringFunctionOperation {\n return stringFunction(this.functionInput(), ScalarFunction.LOWER, 'Lower ' + this.functionLabel());\n }\n /** Remove leading and trailing whitespace. */\n trim(): StringFunctionOperation {\n return stringFunction(this.functionInput(), ScalarFunction.TRIM, 'Trim ' + this.functionLabel());\n }\n /** Remove leading whitespace. */\n trimStart(): StringFunctionOperation {\n return stringFunction(this.functionInput(), ScalarFunction.LTRIM, 'Trim Start ' + this.functionLabel());\n }\n /** Remove trailing whitespace. */\n trimEnd(): StringFunctionOperation {\n return stringFunction(this.functionInput(), ScalarFunction.RTRIM, 'Trim End ' + this.functionLabel());\n }\n /** Return the number of characters in the string. */\n length(): NumericFunctionOperation {\n return numberFunction(this.functionInput(), ScalarFunction.LENGTH, 'Length ' + this.functionLabel());\n }\n /** Return the string with characters in reverse order. */\n reverse(): StringFunctionOperation {\n return stringFunction(this.functionInput(), ScalarFunction.REVERSE, 'Reverse ' + this.functionLabel());\n }\n /** Return the first `n` characters. */\n left(n: number): StringFunctionOperation {\n return stringFunction(this.functionInput(), ScalarFunction.LEFT, 'Left ' + this.functionLabel(), n);\n }\n /** Return the last `n` characters. */\n right(n: number): StringFunctionOperation {\n return stringFunction(this.functionInput(), ScalarFunction.RIGHT, 'Right ' + this.functionLabel(), n);\n }\n /** Return the string repeated `n` times. */\n repeat(n: number): StringFunctionOperation {\n return stringFunction(this.functionInput(), ScalarFunction.REPEAT, 'Repeat ' + this.functionLabel(), n);\n }\n /** Replace all occurrences of `fromStr` with `toStr`. */\n replace(fromStr: string, toStr: string): StringFunctionOperation {\n return stringFunction(this.functionInput(), ScalarFunction.REPLACE, 'Replace ' + this.functionLabel(), undefined, [fromStr, toStr]);\n }\n /**\n * Extract a portion of the string.\n * `start` is zero-based (following Python convention); `length` is optional.\n */\n substring(start: number, length?: number): StringFunctionOperation {\n // Python convention: 0-based start; SQL SUBSTRING is 1-based, so add 1\n const args = length !== undefined ? [start + 1, length] : [start + 1];\n return stringFunction(this.functionInput(), ScalarFunction.SUBSTRING, 'Substring ' + this.functionLabel(), undefined, args);\n }\n}\n\n/** Functions of a number. */\nexport abstract class NumericFunctions {\n /** @internal The expression the function applies to. */\n abstract functionInput(): RelationalOperationElement;\n /** @internal What a function of this is labelled after. */\n abstract functionLabel(): string;\n\n /** Absolute value (distance from zero, always non-negative). */\n abs(): NumericFunctionOperation {\n return numberFunction(this.functionInput(), ScalarFunction.ABS, 'Abs ' + this.functionLabel());\n }\n /** Round up to the nearest integer. */\n ceil(): NumericFunctionOperation {\n return numberFunction(this.functionInput(), ScalarFunction.CEILING, 'Ceil ' + this.functionLabel());\n }\n /** Round down to the nearest integer. */\n floor(): NumericFunctionOperation {\n return numberFunction(this.functionInput(), ScalarFunction.FLOOR, 'Floor ' + this.functionLabel());\n }\n /** Square root. */\n sqrt(): NumericFunctionOperation {\n return numberFunction(this.functionInput(), ScalarFunction.SQRT, 'Sqrt ' + this.functionLabel());\n }\n /** Remainder after dividing by `n`. */\n mod(n: number): NumericFunctionOperation {\n return numberFunction(this.functionInput(), ScalarFunction.MOD, 'Mod ' + this.functionLabel(), n);\n }\n /** Raise to the power of `n`. */\n power(n: number): NumericFunctionOperation {\n return numberFunction(this.functionInput(), ScalarFunction.POWER, 'Power ' + this.functionLabel(), n);\n }\n /** Round to `d` decimal places, or to the nearest integer when `d` is omitted. */\n round(d?: number): NumericFunctionOperation {\n return numberFunction(this.functionInput(), ScalarFunction.ROUND, 'Round ' + this.functionLabel(), d);\n }\n}\n\nexport interface StringFunctionOperation extends StringFunctions {}\napplyMixins(StringFunctionOperation, [StringFunctions]);\n\nexport interface NumericFunctionOperation extends NumericFunctions {}\napplyMixins(NumericFunctionOperation, [NumericFunctions]);\n","import { Attribute, AttributeValue } from './attribute';\nimport { NumericFunctions, StringFunctions } from './scalar-functions';\nimport {\n ComparisonOperation,\n ComparisonOperator,\n StringConstantOperation,\n FloatConstantOperation,\n IntegerConstantOperation,\n DateConstantOperation,\n DateTimeConstantOperation,\n ConstantOperation,\n DateOnly,\n escapeLike,\n applyMixins,\n Arithmetic,\n DATE_ONLY_PATTERN,\n BooleanConstantOperation,\n DecimalConstantOperation,\n AggregateOperation,\n AggregateOperator,\n SortOperation,\n ScalarFunction,\n ScalarFunctionOperation,\n DatePart,\n DateExtractOperation,\n DateTruncOperation,\n DateArithmeticOperation,\n DateDiffOperation,\n JoinTreeNodeOperation,\n ColumnWithJoin,\n sample,\n} from '../model/relational';\n\n/** The smallest and largest value of a group, for a column that can be ordered but not summed. */\nabstract class MinMax {\n abstract cwj(): ColumnWithJoin;\n abstract displayName(): string;\n\n /** Smallest value in the group. */\n min(): AggregateOperation {\n return new AggregateOperation(this.cwj(), AggregateOperator.MIN, 'Min ' + this.displayName());\n }\n /** Largest value in the group. */\n max(): AggregateOperation {\n return new AggregateOperation(this.cwj(), AggregateOperator.MAX, 'Max ' + this.displayName());\n }\n}\n\nexport class StringAttribute extends Attribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n embedded?: Attribute,\n nullable: boolean = true,\n optional: boolean = false,\n ) { super(displayName, columnName, columnDbType, owner, parent, embedded, nullable, optional); }\n\n protected toConstant(value: AttributeValue): ConstantOperation {\n return new StringConstantOperation(String(value));\n }\n\n /**\n * Join the values of a group into one text with `separator` between them. `orderBy` is the order they are\n * joined in (`[f.name().ascending()]`); without it the order is not defined. Missing values are skipped.\n */\n join(separator: string = '', orderBy: SortOperation[] = []): AggregateOperation {\n return new AggregateOperation(this.cwj(), AggregateOperator.STRING_AGG, 'Join ' + this.displayName(), undefined, separator, orderBy);\n }\n\n /** Filter to rows where this attribute equals `value`. */\n eq(value: string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new StringConstantOperation(value));\n }\n /** Filter to rows where this attribute does not equal `value`. */\n ne(value: string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_EQUAL, new StringConstantOperation(value));\n }\n /** Filter to rows where this attribute contains `value` as a substring. */\n contains(value: string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LIKE, new StringConstantOperation(`%${escapeLike(value)}%`));\n }\n /** Filter to rows where this attribute begins with `prefix`. */\n startsWith(prefix: string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LIKE, new StringConstantOperation(`${escapeLike(prefix)}%`));\n }\n /** Filter to rows where this attribute ends with `suffix`. */\n endsWith(suffix: string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LIKE, new StringConstantOperation(`%${escapeLike(suffix)}`));\n }\n /** Filter to rows where this attribute does not contain `value` as a substring. */\n notContains(value: string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_LIKE, new StringConstantOperation(`%${escapeLike(value)}%`));\n }\n}\n\nexport interface StringAttribute extends MinMax, StringFunctions {}\napplyMixins(StringAttribute, [MinMax, StringFunctions]);\n\nexport abstract class NumericAttribute extends Attribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n embedded?: Attribute,\n nullable: boolean = true,\n optional: boolean = false,\n ) { super(displayName, columnName, columnDbType, owner, parent, embedded, nullable, optional); }\n\n /** Sum of all values in the group. */\n sum(): AggregateOperation {\n return new AggregateOperation(this.cwj(), AggregateOperator.SUM, 'Sum ' + this.displayName());\n }\n /** Arithmetic mean of all values in the group. */\n average(): AggregateOperation {\n return new AggregateOperation(this.cwj(), AggregateOperator.AVERAGE, 'Average ' + this.displayName());\n }\n /** Standard deviation of the values in the group: the sample one by default, `ddof = 0` for the population one, as `Series.std`. */\n std(ddof = 1): AggregateOperation {\n const operator = sample(ddof) ? AggregateOperator.STDDEV_SAMP : AggregateOperator.STDDEV_POP;\n return new AggregateOperation(this.cwj(), operator, 'Std ' + this.displayName());\n }\n /** Variance of the values in the group: the sample one by default, `ddof = 0` for the population one, as `Series.var`. */\n var(ddof = 1): AggregateOperation {\n const operator = sample(ddof) ? AggregateOperator.VAR_SAMP : AggregateOperator.VAR_POP;\n return new AggregateOperation(this.cwj(), operator, 'Var ' + this.displayName());\n }\n}\n\nexport interface NumericAttribute extends MinMax, NumericFunctions, Arithmetic {}\napplyMixins(NumericAttribute, [MinMax, NumericFunctions, Arithmetic]);\n\nexport class DoubleAttribute extends NumericAttribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n embedded?: Attribute,\n nullable: boolean = true,\n optional: boolean = false,\n ) { super(displayName, columnName, columnDbType, owner, parent, embedded, nullable, optional); }\n\n protected toConstant(value: AttributeValue): ConstantOperation {\n return new FloatConstantOperation(Number(value));\n }\n\n /** Filter to rows where this attribute equals `value`. */\n eq(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new FloatConstantOperation(value));\n }\n /** Filter to rows where this attribute does not equal `value`. */\n ne(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_EQUAL, new FloatConstantOperation(value));\n }\n /** Filter to rows where this attribute is greater than `value`. */\n gt(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN, new FloatConstantOperation(value));\n }\n /** Filter to rows where this attribute is less than `value`. */\n lt(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN, new FloatConstantOperation(value));\n }\n /** Filter to rows where this attribute is greater than or equal to `value`. */\n gte(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN_OR_EQUAL_TO, new FloatConstantOperation(value));\n }\n /** Filter to rows where this attribute is less than or equal to `value`. */\n lte(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN_OR_EQUAL_TO, new FloatConstantOperation(value));\n }\n}\n\nexport const FloatAttribute = DoubleAttribute;\nexport type FloatAttribute = DoubleAttribute;\n\nexport class DecimalAttribute extends NumericAttribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n embedded?: Attribute,\n nullable: boolean = true,\n optional: boolean = false,\n ) { super(displayName, columnName, columnDbType, owner, parent, embedded, nullable, optional); }\n\n protected toConstant(value: AttributeValue): ConstantOperation {\n return new DecimalConstantOperation(Number(value));\n }\n\n /** Filter to rows where this attribute equals `value`. */\n eq(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new DecimalConstantOperation(value));\n }\n /** Filter to rows where this attribute does not equal `value`. */\n ne(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_EQUAL, new DecimalConstantOperation(value));\n }\n /** Filter to rows where this attribute is greater than `value`. */\n gt(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN, new DecimalConstantOperation(value));\n }\n /** Filter to rows where this attribute is less than `value`. */\n lt(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN, new DecimalConstantOperation(value));\n }\n /** Filter to rows where this attribute is greater than or equal to `value`. */\n gte(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN_OR_EQUAL_TO, new DecimalConstantOperation(value));\n }\n /** Filter to rows where this attribute is less than or equal to `value`. */\n lte(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN_OR_EQUAL_TO, new DecimalConstantOperation(value));\n }\n}\n\nexport class IntegerAttribute extends NumericAttribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n embedded?: Attribute,\n nullable: boolean = true,\n optional: boolean = false,\n ) { super(displayName, columnName, columnDbType, owner, parent, embedded, nullable, optional); }\n\n protected toConstant(value: AttributeValue): ConstantOperation {\n return new IntegerConstantOperation(Number(value));\n }\n\n /** Filter to rows where this attribute equals `value`. */\n eq(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new IntegerConstantOperation(value));\n }\n /** Filter to rows where this attribute does not equal `value`. */\n ne(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_EQUAL, new IntegerConstantOperation(value));\n }\n /** Filter to rows where this attribute is greater than `value`. */\n gt(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN, new IntegerConstantOperation(value));\n }\n /** Filter to rows where this attribute is less than `value`. */\n lt(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN, new IntegerConstantOperation(value));\n }\n /** Filter to rows where this attribute is greater than or equal to `value`. */\n gte(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN_OR_EQUAL_TO, new IntegerConstantOperation(value));\n }\n /** Filter to rows where this attribute is less than or equal to `value`. */\n lte(value: number): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN_OR_EQUAL_TO, new IntegerConstantOperation(value));\n }\n}\n\nexport class BooleanAttribute extends Attribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n embedded?: Attribute,\n nullable: boolean = true,\n optional: boolean = false,\n ) { super(displayName, columnName, columnDbType, owner, parent, embedded, nullable, optional); }\n\n protected toConstant(value: AttributeValue): ConstantOperation {\n return new BooleanConstantOperation(Boolean(value));\n }\n\n /** Filter to rows where this attribute equals `value`. */\n eq(value: boolean): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new BooleanConstantOperation(value));\n }\n /** Filter to rows where this attribute is true. */\n isTrue(): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new BooleanConstantOperation(true));\n }\n /** Filter to rows where this attribute is false. */\n isFalse(): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new BooleanConstantOperation(false));\n }\n}\n\nfunction parseDate(value: Date | string): Date {\n if (value instanceof Date) return value;\n const d = new Date(value);\n if (isNaN(d.getTime())) throw new Error(`Cannot parse date: ${value}`);\n return d;\n}\n\n/**\n * A timestamp comparison value: a `DateOnly` (or a `YYYY-MM-DD` string) is a date literal,\n * any other `Date` or string a timestamp literal.\n */\nfunction temporalConstant(value: Date | string): DateConstantOperation | DateTimeConstantOperation {\n if (typeof value === 'string' && DATE_ONLY_PATTERN.test(value)) return new DateConstantOperation(new DateOnly(value));\n const date = parseDate(value);\n return date instanceof DateOnly ? new DateConstantOperation(date) : new DateTimeConstantOperation(date);\n}\n\nexport class DateAttribute extends Attribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n embedded?: Attribute,\n nullable: boolean = true,\n optional: boolean = false,\n ) { super(displayName, columnName, columnDbType, owner, parent, embedded, nullable, optional); }\n\n protected toConstant(value: AttributeValue): ConstantOperation {\n return new DateConstantOperation(parseDate(value as Date | string));\n }\n\n /** Filter to rows where this date equals `value`. */\n eq(value: Date | string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, new DateConstantOperation(parseDate(value)));\n }\n /** Filter to rows where this date does not equal `value`. */\n ne(value: Date | string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_EQUAL, new DateConstantOperation(parseDate(value)));\n }\n /** Filter to rows where this date is after `value`. */\n gt(value: Date | string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN, new DateConstantOperation(parseDate(value)));\n }\n /** Filter to rows where this date is before `value`. */\n lt(value: Date | string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN, new DateConstantOperation(parseDate(value)));\n }\n /** Filter to rows where this date is on or after `value`. */\n gte(value: Date | string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN_OR_EQUAL_TO, new DateConstantOperation(parseDate(value)));\n }\n /** Filter to rows where this date is on or before `value`. */\n lte(value: Date | string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN_OR_EQUAL_TO, new DateConstantOperation(parseDate(value)));\n }\n\n /** Extract the four-digit calendar year. */\n year(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.YEAR, 'Year ' + this.displayName()); }\n /** Extract the month number (1–12). */\n month(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.MONTH, 'Month ' + this.displayName()); }\n /** Extract the day of the month (1–31). */\n day(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.DAY, 'Day ' + this.displayName()); }\n /** Extract the quarter (1–4). */\n quarter(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.QUARTER, 'Quarter ' + this.displayName()); }\n /** Extract the ISO week number (1–53). */\n week(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.WEEK, 'Week ' + this.displayName()); }\n /** Extract the day of the week (0 = Sunday through 6 = Saturday). */\n dayOfWeek(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.DOW, 'Day Of Week ' + this.displayName()); }\n /** The date of the first day of the week the date falls in (a Monday). */\n firstDayOfWeek(): DateTruncOperation { return new DateTruncOperation(this.cwj(), DatePart.WEEK, 'First Day Of Week ' + this.displayName()); }\n /** The date of the first day of the month the date falls in. */\n firstDayOfMonth(): DateTruncOperation { return new DateTruncOperation(this.cwj(), DatePart.MONTH, 'First Day Of Month ' + this.displayName()); }\n /** The date of the first day of the quarter the date falls in. */\n firstDayOfQuarter(): DateTruncOperation { return new DateTruncOperation(this.cwj(), DatePart.QUARTER, 'First Day Of Quarter ' + this.displayName()); }\n /** The date of the first day of the year the date falls in. */\n firstDayOfYear(): DateTruncOperation { return new DateTruncOperation(this.cwj(), DatePart.YEAR, 'First Day Of Year ' + this.displayName()); }\n\n /** Add `n` days to this date. */\n addDays(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.DAY, true, 'Add Days ' + this.displayName()); }\n /** Add `n` months to this date. */\n addMonths(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.MONTH, true, 'Add Months ' + this.displayName()); }\n /** Add `n` years to this date. */\n addYears(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.YEAR, true, 'Add Years ' + this.displayName()); }\n /** Subtract `n` days from this date. */\n subtractDays(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.DAY, false, 'Subtract Days ' + this.displayName()); }\n /** Subtract `n` months from this date. */\n subtractMonths(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.MONTH, false, 'Subtract Months ' + this.displayName()); }\n /** Subtract `n` years from this date. */\n subtractYears(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.YEAR, false, 'Subtract Years ' + this.displayName()); }\n\n /** Number of whole days between this date and `other`. */\n diffDays(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.DAY, 'Diff Days ' + this.displayName()); }\n /** Number of whole months between this date and `other`. */\n diffMonths(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.MONTH, 'Diff Months ' + this.displayName()); }\n /** Number of whole years between this date and `other`. */\n diffYears(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.YEAR, 'Diff Years ' + this.displayName()); }\n}\n\nexport class DateTimeAttribute extends Attribute {\n constructor(\n displayName: string,\n columnName: string,\n columnDbType: string,\n owner: string,\n parent?: JoinTreeNodeOperation,\n embedded?: Attribute,\n nullable: boolean = true,\n optional: boolean = false,\n ) { super(displayName, columnName, columnDbType, owner, parent, embedded, nullable, optional); }\n\n protected toConstant(value: AttributeValue): ConstantOperation {\n return temporalConstant(value as Date | string);\n }\n\n /** Filter to rows where this timestamp equals `value`. */\n eq(value: Date | string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.EQUAL, temporalConstant(value));\n }\n /** Filter to rows where this timestamp does not equal `value`. */\n ne(value: Date | string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.NOT_EQUAL, temporalConstant(value));\n }\n /** Filter to rows where this timestamp is after `value`. */\n gt(value: Date | string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN, temporalConstant(value));\n }\n /** Filter to rows where this timestamp is before `value`. */\n lt(value: Date | string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN, temporalConstant(value));\n }\n /** Filter to rows where this timestamp is on or after `value`. */\n gte(value: Date | string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.GREATER_THAN_OR_EQUAL_TO, temporalConstant(value));\n }\n /** Filter to rows where this timestamp is on or before `value`. */\n lte(value: Date | string): ComparisonOperation {\n return new ComparisonOperation(this.cwj(), ComparisonOperator.LESS_THAN_OR_EQUAL_TO, temporalConstant(value));\n }\n\n /** Extract the four-digit calendar year. */\n year(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.YEAR, 'Year ' + this.displayName()); }\n /** Extract the month number (1–12). */\n month(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.MONTH, 'Month ' + this.displayName()); }\n /** Extract the day of the month (1–31). */\n day(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.DAY, 'Day ' + this.displayName()); }\n /** Extract the hour (0–23). */\n hour(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.HOUR, 'Hour ' + this.displayName()); }\n /** Extract the minute (0–59). */\n minute(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.MINUTE, 'Minute ' + this.displayName()); }\n /** Extract the second (0–59). */\n second(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.SECOND, 'Second ' + this.displayName()); }\n /** Extract the quarter (1–4). */\n quarter(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.QUARTER, 'Quarter ' + this.displayName()); }\n /** Extract the ISO week number (1–53). */\n week(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.WEEK, 'Week ' + this.displayName()); }\n /** Extract the day of the week (0 = Sunday through 6 = Saturday). */\n dayOfWeek(): DateExtractOperation { return new DateExtractOperation(this.cwj(), DatePart.DOW, 'Day Of Week ' + this.displayName()); }\n /** The date of the first day of the week the date falls in (a Monday). */\n firstDayOfWeek(): DateTruncOperation { return new DateTruncOperation(this.cwj(), DatePart.WEEK, 'First Day Of Week ' + this.displayName()); }\n /** The date of the first day of the month the date falls in. */\n firstDayOfMonth(): DateTruncOperation { return new DateTruncOperation(this.cwj(), DatePart.MONTH, 'First Day Of Month ' + this.displayName()); }\n /** The date of the first day of the quarter the date falls in. */\n firstDayOfQuarter(): DateTruncOperation { return new DateTruncOperation(this.cwj(), DatePart.QUARTER, 'First Day Of Quarter ' + this.displayName()); }\n /** The date of the first day of the year the date falls in. */\n firstDayOfYear(): DateTruncOperation { return new DateTruncOperation(this.cwj(), DatePart.YEAR, 'First Day Of Year ' + this.displayName()); }\n\n /** Add `n` days to this timestamp. */\n addDays(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.DAY, true, 'Add Days ' + this.displayName()); }\n /** Add `n` months to this timestamp. */\n addMonths(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.MONTH, true, 'Add Months ' + this.displayName()); }\n /** Add `n` years to this timestamp. */\n addYears(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.YEAR, true, 'Add Years ' + this.displayName()); }\n /** Add `n` hours to this timestamp. */\n addHours(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.HOUR, true, 'Add Hours ' + this.displayName()); }\n /** Add `n` minutes to this timestamp. */\n addMinutes(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.MINUTE, true, 'Add Minutes ' + this.displayName()); }\n /** Add `n` seconds to this timestamp. */\n addSeconds(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.SECOND, true, 'Add Seconds ' + this.displayName()); }\n /** Subtract `n` days from this timestamp. */\n subtractDays(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.DAY, false, 'Subtract Days ' + this.displayName()); }\n /** Subtract `n` months from this timestamp. */\n subtractMonths(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.MONTH, false, 'Subtract Months ' + this.displayName()); }\n /** Subtract `n` years from this timestamp. */\n subtractYears(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.YEAR, false, 'Subtract Years ' + this.displayName()); }\n /** Subtract `n` hours from this timestamp. */\n subtractHours(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.HOUR, false, 'Subtract Hours ' + this.displayName()); }\n /** Subtract `n` minutes from this timestamp. */\n subtractMinutes(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.MINUTE, false, 'Subtract Minutes ' + this.displayName()); }\n /** Subtract `n` seconds from this timestamp. */\n subtractSeconds(n: number): DateArithmeticOperation { return new DateArithmeticOperation(this.cwj(), n, DatePart.SECOND, false, 'Subtract Seconds ' + this.displayName()); }\n\n /** Number of whole days between this timestamp and `other`. */\n diffDays(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.DAY, 'Diff Days ' + this.displayName()); }\n /** Number of whole months between this timestamp and `other`. */\n diffMonths(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.MONTH, 'Diff Months ' + this.displayName()); }\n /** Number of whole years between this timestamp and `other`. */\n diffYears(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.YEAR, 'Diff Years ' + this.displayName()); }\n /** Number of whole hours between this timestamp and `other`. */\n diffHours(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.HOUR, 'Diff Hours ' + this.displayName()); }\n /** Number of whole minutes between this timestamp and `other`. */\n diffMinutes(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.MINUTE, 'Diff Minutes ' + this.displayName()); }\n /** Number of whole seconds between this timestamp and `other`. */\n diffSeconds(other: Date): DateDiffOperation { return new DateDiffOperation(this.cwj(), other, DatePart.SECOND, 'Diff Seconds ' + this.displayName()); }\n}\n\nexport interface DateAttribute extends MinMax {}\napplyMixins(DateAttribute, [MinMax]);\n\nexport interface DateTimeAttribute extends MinMax {}\napplyMixins(DateTimeAttribute, [MinMax]);\n","/** Expressions that are not a column of a finder: values to select next to the columns. */\nimport {\n BooleanConstantOperation,\n CountAllOperation,\n ConstantOperation,\n DateConstantOperation,\n DateOnly,\n DateTimeConstantOperation,\n FloatConstantOperation,\n IntegerConstantOperation,\n NumericConstantOperation,\n StringConstantOperation,\n} from '../model/relational';\n\n/**\n * A fixed value as a column: `f.findAll(null, null, [f.name(), constant('EU').alias('Region')])`.\n * A number is a `NumericConstantOperation`, which takes part in arithmetic: `constant(100).minus(f.price())`.\n * A `DateOnly` is a date and any other `Date` a timestamp. It is named \"Constant\" unless `alias` gives it a name.\n */\nexport function constant(value: number): NumericConstantOperation;\nexport function constant(value: boolean | string | Date): ConstantOperation;\nexport function constant(value: boolean | number | string | Date): ConstantOperation;\nexport function constant(value: boolean | number | string | Date): ConstantOperation {\n if (typeof value === 'boolean') return new BooleanConstantOperation(value);\n if (typeof value === 'number' && Number.isFinite(value)) {\n return Number.isInteger(value) ? new IntegerConstantOperation(value) : new FloatConstantOperation(value);\n }\n if (typeof value === 'string') return new StringConstantOperation(value);\n if (value instanceof DateOnly) return new DateConstantOperation(value); // before Date: DateOnly is a Date\n if (value instanceof Date) return new DateTimeConstantOperation(value);\n throw new TypeError(`A constant column holds a boolean, a finite number, a string or a date, not ${value === null ? 'null' : typeof value}`);\n}\n\n/**\n * The number of rows in the group, `COUNT(*)`: `f.findAll(null, null, [f.category(), countAll()]).groupBy(f.category())`.\n * Unlike `count()` of a column it also counts rows where that column is missing.\n */\nexport function countAll(): CountAllOperation {\n return new CountAllOperation('');\n}\n","/**\n * A value that depends on a condition, written as in polars:\n * `when(f.age().gt(30)).then('senior').otherwise('junior')`.\n */\nimport { Attribute } from './attribute';\nimport { constant } from './expressions';\nimport {\n CaseOperation,\n ComparisonOperation,\n ExistsOperation,\n InOperation,\n IsNotNullOperation,\n IsNullOperation,\n LogicalOperation,\n NotExistsOperation,\n NotInOperation,\n Operation,\n RelationalOperationElement,\n} from '../model/relational';\n\nconst CONDITIONS = [\n ComparisonOperation, LogicalOperation, IsNullOperation, IsNotNullOperation,\n InOperation, NotInOperation, ExistsOperation, NotExistsOperation,\n];\n\n/** What a branch can be: a column or expression as it is, a plain value as a constant. */\nexport type Branch = Attribute | RelationalOperationElement | boolean | number | string | Date;\n\n/**\n * Something that is true or false for a row, which a `when` can test: a comparison, a null check, a membership\n * test, `exists`, or `and` / `or` of those. Checked when `when` is called.\n */\nexport type Condition = Operation | ExistsOperation | NotExistsOperation;\n\ntype Case = [Condition, RelationalOperationElement];\n\nfunction value(branch: Branch): RelationalOperationElement {\n if (branch instanceof Attribute) return branch.cwj();\n if (branch instanceof RelationalOperationElement) return branch;\n try {\n return constant(branch);\n } catch {\n throw new TypeError(`A branch is a column, an expression or a value, not ${branch === null ? 'null' : typeof branch}`);\n }\n}\n\nfunction checked(condition: unknown): Condition {\n if (!CONDITIONS.some(c => condition instanceof c)) {\n throw new TypeError('The condition is a comparison, a null check, a membership test, exists, or and/or of those');\n }\n return condition as Condition;\n}\n\n/** The cases in order as a conditional: each later case is what the one before falls back to. */\nfunction chain(cases: Case[], fallback?: RelationalOperationElement): CaseOperation {\n const [[condition, then], ...rest] = cases;\n return new CaseOperation(condition, then, rest.length > 0 ? chain(rest, fallback) : fallback);\n}\n\n/**\n * `when(condition).then(value)`: a column on its own (missing where the condition does not hold), or continued\n * with another `when` or closed with `otherwise`.\n */\nexport class Then extends CaseOperation {\n constructor(private readonly cases: Case[]) {\n const first = chain(cases);\n super(first.condition, first.then, first.fallback);\n }\n\n /** Another case, tried when the ones before it do not hold. */\n when(condition: Condition): When {\n return new When(checked(condition), this.cases);\n }\n\n /** The value when none of the cases hold. */\n otherwise(branch: Branch): CaseOperation {\n return chain(this.cases, value(branch));\n }\n}\n\nexport class When {\n constructor(private readonly condition: Condition, private readonly earlier: Case[] = []) {}\n\n /** The value where the condition holds. A value is a column, an expression or a plain value. */\n then(branch: Branch): Then {\n return new Then([...this.earlier, [this.condition, value(branch)]]);\n }\n}\n\n/**\n * Start a conditional: `when(f.category().eq('Technology')).then('tech').otherwise('other')`.\n *\n * Further cases follow with `.when(...).then(...)`; with no `otherwise` the value is missing (NULL). A condition\n * that is NULL for a row (a comparison with a missing value) is not true, so that row takes the next case.\n */\nexport function when(condition: Condition): When {\n return new When(checked(condition));\n}\n","import { Column, Table, Schema } from './relational';\n\nexport abstract class MilestoningColumns {\n abstract columns(): Column[];\n}\n\nexport class ProcessingTemporalColumns extends MilestoningColumns {\n constructor(\n readonly startAtColumn: Column,\n readonly endAtColumn: Column,\n readonly infiniteDatetime?: string,\n ) { super(); }\n\n columns(): Column[] { return [this.startAtColumn, this.endAtColumn]; }\n}\n\nexport class SingleBusinessDateColumn extends MilestoningColumns {\n constructor(readonly businessDateColumn: Column) { super(); }\n\n columns(): Column[] { return [this.businessDateColumn]; }\n}\n\nexport class BusinessDateAndProcessingTemporalColumns extends MilestoningColumns {\n constructor(\n readonly businessDateColumn: Column,\n readonly startAtColumn: Column,\n readonly endAtColumn: Column,\n readonly infiniteDatetime?: string,\n ) { super(); }\n\n columns(): Column[] {\n return [this.businessDateColumn, this.startAtColumn, this.endAtColumn];\n }\n}\n\nexport class BiTemporalColumns extends MilestoningColumns {\n constructor(\n readonly businessDateFromColumn: Column,\n readonly businessDateToColumn: Column,\n readonly startAtColumn: Column,\n readonly endAtColumn: Column,\n readonly infiniteDatetime?: string,\n ) { super(); }\n\n columns(): Column[] {\n return [\n this.businessDateFromColumn,\n this.businessDateToColumn,\n this.startAtColumn,\n this.endAtColumn,\n ];\n }\n}\n\nexport class MilestonedTable extends Table {\n constructor(\n name: string,\n columns: Column[],\n readonly milestoningColumns: MilestoningColumns,\n schema?: Schema,\n ) {\n super(name, columns, schema);\n for (const col of milestoningColumns.columns()) {\n col.table = this;\n }\n }\n}\n","/**\n * The SQL a query is written in. The generator writes Postgres by default; a dialect says where another database\n * differs, so the same query can be sent to DuckDB or Databricks.\n *\n * Only what differs is here. Everything the databases share (joins, CASE, window functions, COUNT(DISTINCT), LIKE ...\n * ESCAPE, `||`, typed date literals, `INTERVAL '7' DAY`, ...) is written once by the generator.\n */\nimport { DatePart, SortDirection } from '../model/relational';\n\nexport type DialectName = 'postgres' | 'duckdb' | 'databricks';\n\nexport interface SqlDialect {\n readonly name: DialectName;\n\n /** A name as an identifier, used for the names of the result's columns. */\n quoteIdentifier(name: string): string;\n\n /** A string as a literal that can never end early, whatever it holds. */\n stringLiteral(value: string): string;\n\n /**\n * ` ASC` or ` DESC`, with the null placement spelled out where the database's default differs from Postgres\n * (nulls last when ascending, first when descending), so a sort gives the same order everywhere.\n */\n orderDirection(direction: SortDirection): string;\n\n /** The type a float constant is cast to, so it comes back as a double and not a decimal. */\n readonly doubleType: string;\n\n /** The day of the week of a date or timestamp, 0 = Sunday through 6 = Saturday. */\n dayOfWeek(expression: string): string;\n\n /** Whole `unit`s from `from` to `to`; both are SQL expressions. */\n dateDiff(unit: DatePart, from: string, to: string): string;\n\n /** The values of a group joined with `separator` (an SQL literal), in the order given (each with its direction). */\n stringAgg(expression: string, separator: string, orderBy: string[]): string;\n}\n\nconst doubleQuoted = (name: string): string => '\"' + name.replaceAll('\"', '\"\"') + '\"';\nconst quoted = (value: string): string => \"'\" + value.replaceAll(\"'\", \"''\") + \"'\";\n\nconst SECONDS_PER: Partial<Record<DatePart, number>> = { [DatePart.HOUR]: 3600, [DatePart.MINUTE]: 60, [DatePart.SECOND]: 1 };\n\nexport const POSTGRES: SqlDialect = {\n name: 'postgres',\n quoteIdentifier: doubleQuoted,\n stringLiteral: quoted,\n orderDirection: direction => (direction === SortDirection.ASC ? ' ASC' : ' DESC'),\n doubleType: 'DOUBLE PRECISION',\n dayOfWeek: expression => `EXTRACT(DOW FROM ${expression})`,\n dateDiff(unit, from, to) {\n const start = `CAST(${from} AS TIMESTAMP)`;\n const end = `CAST(${to} AS TIMESTAMP)`;\n switch (unit) {\n case DatePart.DAY: return `(CAST(${to} AS DATE) - CAST(${from} AS DATE))`;\n case DatePart.MONTH:\n return `CAST(EXTRACT(YEAR FROM AGE(${end}, ${start})) * 12 + EXTRACT(MONTH FROM AGE(${end}, ${start})) AS BIGINT)`;\n case DatePart.YEAR: return `CAST(EXTRACT(YEAR FROM AGE(${end}, ${start})) AS BIGINT)`;\n default: {\n const seconds = SECONDS_PER[unit];\n if (seconds === undefined) throw new Error(`Cannot take the difference in ${unit}`);\n return `CAST(FLOOR(EXTRACT(EPOCH FROM (${end} - ${start})) / ${seconds}) AS BIGINT)`;\n }\n }\n },\n stringAgg: (expression, separator, orderBy) =>\n `STRING_AGG(${expression}, ${separator}${orderBy.length > 0 ? ' ORDER BY ' + orderBy.join(', ') : ''})`,\n};\n\nexport const DUCKDB: SqlDialect = {\n ...POSTGRES,\n name: 'duckdb',\n // DuckDB sorts nulls last whichever way the sort goes\n orderDirection: direction => (direction === SortDirection.ASC ? ' ASC' : ' DESC NULLS FIRST'),\n doubleType: 'DOUBLE',\n dateDiff: (unit, from, to) => `DATE_DIFF('${unit.toLowerCase()}', ${from}, ${to})`,\n};\n\nexport const DATABRICKS: SqlDialect = {\n name: 'databricks',\n // a double-quoted token is a string in Databricks; identifiers take backticks\n quoteIdentifier: name => '`' + name.replaceAll('`', '``') + '`',\n // a backslash starts an escape in a Databricks string literal, and a doubled quote is not one: Spark reads\n // 'it''s' as the two literals 'it' and 's' and joins them, losing the quote. A quote is escaped with a backslash.\n stringLiteral: value => \"'\" + value.replaceAll('\\\\', '\\\\\\\\').replaceAll(\"'\", \"\\\\'\") + \"'\",\n // Databricks sorts nulls first when ascending, last when descending\n orderDirection: direction => (direction === SortDirection.ASC ? ' ASC NULLS LAST' : ' DESC NULLS FIRST'),\n doubleType: 'DOUBLE',\n // DAYOFWEEK is 1 = Sunday through 7 = Saturday\n dayOfWeek: expression => `(DAYOFWEEK(${expression}) - 1)`,\n dateDiff: (unit, from, to) => `DATEDIFF(${unit}, ${from}, ${to})`,\n stringAgg: (expression, separator, orderBy) =>\n `LISTAGG(${expression}, ${separator})${orderBy.length > 0 ? ' WITHIN GROUP (ORDER BY ' + orderBy.join(', ') + ')' : ''}`,\n};\n\nconst DIALECTS: Record<DialectName, SqlDialect> = { postgres: POSTGRES, duckdb: DUCKDB, databricks: DATABRICKS };\n\n/** A dialect by name, or as given. */\nexport function dialectOf(dialect: DialectName | SqlDialect): SqlDialect {\n if (typeof dialect !== 'string') return dialect;\n const found = DIALECTS[dialect];\n if (found === undefined) throw new Error(`Unknown SQL dialect '${dialect}': one of ${Object.keys(DIALECTS).join(', ')}`);\n return found;\n}\n","import { Attribute } from './attribute';\nimport {\n RelationalOperationElement,\n Operation,\n NoOperation,\n ConstantOperation,\n StringConstantOperation,\n IntegerConstantOperation,\n FloatConstantOperation,\n DateConstantOperation,\n DateTimeConstantOperation,\n BooleanConstantOperation,\n DecimalConstantOperation,\n LogicalOperation,\n LogicalOperator,\n ComparisonOperation,\n ComparisonOperator,\n IsNullOperation,\n IsNotNullOperation,\n InOperation,\n NotInOperation,\n AggregateOperation,\n AggregateOperator,\n ScalarFunctionOperation,\n ScalarFunction,\n DateExtractOperation,\n DateArithmeticOperation,\n DateDiffOperation,\n WindowFunction,\n WindowFunctionOperation,\n WindowSpecification,\n Column,\n ColumnWithJoin,\n Table,\n JoinOperation,\n JoinTreeNodeOperation,\n SortOperation,\n SortDirection,\n DatePart,\n CountAllOperation,\n UnaryOperation,\n Alias,\n LIKE_ESCAPE,\n ExistsOperation,\n NotExistsOperation,\n SelectOperation,\n BinaryOperation,\n CaseOperation,\n ConcatOperation,\n DateTruncOperation,\n ArithmeticOperation,\n ArithmeticOperator,\n containsAggregate,\n containsAggregateOrWindow,\n} from '../model/relational';\nimport {\n MilestonedTable,\n BiTemporalColumns,\n BusinessDateAndProcessingTemporalColumns,\n MilestoningColumns,\n ProcessingTemporalColumns,\n SingleBusinessDateColumn,\n} from '../model/milestoning';\nimport { DateAttribute, DateTimeAttribute } from './typed-attributes';\nimport { DialectName, SqlDialect, dialectOf } from './dialect';\n\nclass TableAlias {\n constructor(readonly table: string, readonly alias: string) {}\n}\n\nclass TableAliasColumn extends RelationalOperationElement {\n constructor(readonly column: Column, readonly tableAlias: TableAlias) { super(); }\n}\n\nclass Join {\n constructor(\n readonly source: TableAliasColumn,\n readonly target: TableAliasColumn,\n readonly filterOp?: RelationalOperationElement,\n ) {}\n\n /** `source = target`, written with the key column first as Legend writes a join defined as key = foreign key. */\n condition(): string {\n let [first, second] = [this.source, this.target];\n if (second.column.primaryKey && !first.column.primaryKey) [first, second] = [second, first];\n return first.tableAlias.alias + '.' + first.column.name + ' = ' + second.tableAlias.alias + '.' + second.column.name;\n }\n}\n\nfunction sqlFormatDatetime(value: Date): string {\n const pad = (n: number, w = 2) => String(n).padStart(w, '0');\n return `'${value.getUTCFullYear()}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())} ${pad(value.getUTCHours())}:${pad(value.getUTCMinutes())}:${pad(value.getUTCSeconds())}'`;\n}\n\nfunction sqlFormatDate(value: Date): string {\n const pad = (n: number) => String(n).padStart(2, '0');\n return `'${value.getUTCFullYear()}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())}'`;\n}\n\nconst LOGICAL_OPERATOR_STR: Record<LogicalOperator, string> = {\n [LogicalOperator.AND]: ' AND ',\n [LogicalOperator.OR]: ' OR ',\n};\n\nconst COMPARISON_OPERATOR_STR: Record<ComparisonOperator, string> = {\n [ComparisonOperator.EQUAL]: ' = ',\n [ComparisonOperator.NOT_EQUAL]: ' <> ',\n [ComparisonOperator.LESS_THAN]: ' < ',\n [ComparisonOperator.GREATER_THAN]: ' > ',\n [ComparisonOperator.LESS_THAN_OR_EQUAL_TO]: ' <= ',\n [ComparisonOperator.GREATER_THAN_OR_EQUAL_TO]: ' >= ',\n [ComparisonOperator.LIKE]: ' LIKE ',\n [ComparisonOperator.NOT_LIKE]: ' NOT LIKE ',\n};\n\nconst AGGREGATE_SQL_NAMES: Partial<Record<AggregateOperator, string>> = {\n [AggregateOperator.AVERAGE]: 'AVG',\n};\n\n/**\n * Comparisons that are never true for a missing value. Legend guards these on an optional property with IS NOT NULL;\n * it does not guard `=` (which a missing value never matches either) or `<>`.\n */\nconst GUARDED_COMPARISONS = new Set<ComparisonOperator>([\n ComparisonOperator.LESS_THAN, ComparisonOperator.GREATER_THAN, ComparisonOperator.LESS_THAN_OR_EQUAL_TO,\n ComparisonOperator.GREATER_THAN_OR_EQUAL_TO, ComparisonOperator.LIKE,\n]);\n\nconst WINDOW_SQL_NAMES: Record<WindowFunction, string> = {\n [WindowFunction.ROW_NUMBER]: 'ROW_NUMBER',\n [WindowFunction.RANK]: 'RANK',\n [WindowFunction.DENSE_RANK]: 'DENSE_RANK',\n [WindowFunction.NTILE]: 'NTILE',\n [WindowFunction.LAG]: 'LAG',\n [WindowFunction.LEAD]: 'LEAD',\n [WindowFunction.FIRST_VALUE]: 'FIRST_VALUE',\n [WindowFunction.LAST_VALUE]: 'LAST_VALUE',\n [WindowFunction.CUME_DIST]: 'CUME_DIST',\n [WindowFunction.PERCENT_RANK]: 'PERCENT_RANK',\n};\n\nconst SCALAR_SQL_NAMES: Record<ScalarFunction, string> = {\n [ScalarFunction.ABS]: 'ABS',\n [ScalarFunction.CEILING]: 'CEILING',\n [ScalarFunction.FLOOR]: 'FLOOR',\n [ScalarFunction.MOD]: 'MOD',\n [ScalarFunction.POWER]: 'POWER',\n [ScalarFunction.SQRT]: 'SQRT',\n [ScalarFunction.ROUND]: 'ROUND',\n [ScalarFunction.UPPER]: 'UPPER',\n [ScalarFunction.LOWER]: 'LOWER',\n [ScalarFunction.TRIM]: 'TRIM',\n [ScalarFunction.LTRIM]: 'LTRIM',\n [ScalarFunction.RTRIM]: 'RTRIM',\n [ScalarFunction.LENGTH]: 'LENGTH',\n [ScalarFunction.REVERSE]: 'REVERSE',\n [ScalarFunction.LEFT]: 'LEFT',\n [ScalarFunction.RIGHT]: 'RIGHT',\n [ScalarFunction.REPEAT]: 'REPEAT',\n [ScalarFunction.REPLACE]: 'REPLACE',\n [ScalarFunction.SUBSTRING]: 'SUBSTRING',\n [ScalarFunction.COALESCE]: 'COALESCE',\n};\n\nfunction constantValueString(op: ConstantOperation, d: SqlDialect): string {\n if (op instanceof StringConstantOperation) return d.stringLiteral(op.value);\n if (op instanceof DateConstantOperation) return sqlFormatDate(op.value);\n if (op instanceof DateTimeConstantOperation) return sqlFormatDatetime(op.value);\n if (op instanceof IntegerConstantOperation) return String(op.value);\n if (op instanceof FloatConstantOperation) return Number.isInteger(op.value) && Math.abs(op.value) < 1e21 ? op.value.toFixed(1) : String(op.value); // 200.0, so it stays a float\n if (op instanceof BooleanConstantOperation) return op.value ? 'TRUE' : 'FALSE';\n if (op instanceof DecimalConstantOperation) return String(op.value);\n throw new Error('Unknown constant operation');\n}\n\n/**\n * A constant in the select list. A bare quoted literal would come back as text, so dates are typed, and a\n * bare 1.5 would come back as a DECIMAL, so a float is cast to DOUBLE.\n */\nfunction selectedConstantString(op: ConstantOperation, d: SqlDialect): string {\n if (op instanceof FloatConstantOperation) return 'CAST(' + constantValueString(op, d) + ' AS ' + d.doubleType + ')';\n if (op instanceof DateTimeConstantOperation) return 'TIMESTAMP ' + constantValueString(op, d);\n if (op instanceof DateConstantOperation) return 'DATE ' + constantValueString(op, d);\n return constantValueString(op, d);\n}\n\nfunction windowSpecToString(window: WindowSpecification, d: SqlDialect): string {\n const parts: string[] = [];\n if (window.partitionBy.length > 0) {\n parts.push('PARTITION BY ' + window.partitionBy.map(p => sqlOperationToString(p, d)).join(', '));\n }\n if (window.orderBy.length > 0) {\n parts.push('ORDER BY ' + window.orderBy.map(s =>\n sqlOperationToString(s.column, d) + d.orderDirection(s.direction),\n ).join(', '));\n }\n return 'OVER (' + parts.join(' ') + ')';\n}\n\nconst ARITHMETIC_PRECEDENCE: Record<ArithmeticOperator, number> = {\n [ArithmeticOperator.ADD]: 1,\n [ArithmeticOperator.SUBTRACT]: 1,\n [ArithmeticOperator.MULTIPLY]: 2,\n [ArithmeticOperator.DIVIDE]: 2,\n};\n\n/**\n * Whether `child` must be parenthesised as an operand of `parent`: it binds more loosely than the parent, or it\n * is the right operand of a - or / and binds equally (a - (b - c) is not a - b - c).\n */\nexport function arithmeticNeedsParentheses(parent: ArithmeticOperation, child: RelationalOperationElement, onRight: boolean): boolean {\n if (!(child instanceof ArithmeticOperation)) return false;\n const here = ARITHMETIC_PRECEDENCE[parent.operator];\n const there = ARITHMETIC_PRECEDENCE[child.operator];\n return there < here || (there === here && onRight\n && (parent.operator === ArithmeticOperator.SUBTRACT || parent.operator === ArithmeticOperator.DIVIDE));\n}\n\nfunction operandString(operation: RelationalOperationElement, d: SqlDialect): string {\n return operation instanceof ConstantOperation ? constantValueString(operation, d) : sqlOperationToString(operation, d);\n}\n\n/**\n * A condition or CASE already written as SQL, to be selected as a column. It is rendered while the query is being\n * built, where its columns can be resolved to table aliases, not when the text of the select is put together.\n */\nclass RenderedSql extends RelationalOperationElement {\n constructor(readonly sql: string) { super(); }\n}\n\nfunction isCondition(op: unknown): boolean {\n return op instanceof ComparisonOperation || op instanceof LogicalOperation || op instanceof IsNullOperation\n || op instanceof IsNotNullOperation || op instanceof InOperation || op instanceof NotInOperation\n || op instanceof ExistsOperation || op instanceof NotExistsOperation;\n}\n\nfunction sqlOperationToString(operation: RelationalOperationElement, d: SqlDialect): string {\n if (operation instanceof TableAliasColumn) {\n return operation.tableAlias.alias + '.' + operation.column.name;\n }\n if (operation instanceof WindowFunctionOperation) {\n const fn = WINDOW_SQL_NAMES[operation.func];\n const parts: string[] = [];\n if (operation.element !== null && operation.element !== undefined) {\n parts.push(sqlOperationToString(operation.element, d));\n }\n if (operation.secondArg !== undefined) parts.push(String(operation.secondArg));\n for (const arg of operation.extraArgs) {\n parts.push(typeof arg === 'string' ? d.stringLiteral(arg) : String(arg));\n }\n const sql = fn + '(' + parts.join(', ') + ')';\n return sql + (operation.window !== undefined ? ' ' + windowSpecToString(operation.window, d) : ' OVER ()');\n }\n if (operation instanceof AggregateOperation && operation.operator === AggregateOperator.COUNT_DISTINCT) {\n return 'COUNT(DISTINCT ' + sqlOperationToString(operation.element, d) + ')';\n }\n if (operation instanceof AggregateOperation && operation.operator === AggregateOperator.STRING_AGG) {\n let sql = d.stringAgg(\n sqlOperationToString(operation.element, d),\n d.stringLiteral(operation.separator ?? ''),\n operation.orderBy.map(s => sqlOperationToString(s.column, d) + d.orderDirection(s.direction)),\n );\n if (operation.window !== undefined) sql += ' ' + windowSpecToString(operation.window, d);\n return sql;\n }\n if (operation instanceof AggregateOperation) {\n const fn = AGGREGATE_SQL_NAMES[operation.operator] ?? operation.operator;\n let sql = fn + '(' + sqlOperationToString(operation.element, d) + ')';\n if (operation.window !== undefined) {\n sql += ' ' + windowSpecToString(operation.window, d);\n }\n return sql;\n }\n if (operation instanceof ScalarFunctionOperation) {\n const fn = SCALAR_SQL_NAMES[operation.func];\n const parts: string[] = [sqlOperationToString(operation.element, d)];\n if (operation.secondArg !== undefined) parts.push(String(operation.secondArg));\n for (const arg of operation.extraArgs) {\n parts.push(typeof arg === 'string' ? d.stringLiteral(arg) : String(arg));\n }\n return fn + '(' + parts.join(', ') + ')';\n }\n if (operation instanceof DateExtractOperation) {\n const element = sqlOperationToString(operation.element, d);\n return operation.part === DatePart.DOW ? d.dayOfWeek(element) : 'EXTRACT(' + operation.part + ' FROM ' + element + ')';\n }\n if (operation instanceof DateTruncOperation) {\n return \"CAST(DATE_TRUNC('\" + operation.part.toLowerCase() + \"', \" + sqlOperationToString(operation.element, d) + ') AS DATE)';\n }\n if (operation instanceof DateArithmeticOperation) {\n const op = operation.isAdd ? '+' : '-';\n return sqlOperationToString(operation.element, d) + ' ' + op + \" INTERVAL '\" + operation.n + \"' \" + operation.unit;\n }\n if (operation instanceof DateDiffOperation) {\n return d.dateDiff(operation.unit, sqlOperationToString(operation.element, d), 'TIMESTAMP ' + sqlFormatDatetime(operation.other));\n }\n if (operation instanceof CountAllOperation) return 'COUNT(*)';\n if (operation instanceof ConstantOperation) return selectedConstantString(operation, d);\n if (operation instanceof RenderedSql) return operation.sql;\n if (operation instanceof ConcatOperation) return operation.parts.map(part => operandString(part, d)).join(' || ');\n if (operation instanceof ArithmeticOperation) {\n let left = operandString(operation.left, d);\n let right = operandString(operation.right, d);\n if (arithmeticNeedsParentheses(operation, operation.left, false)) left = '(' + left + ')';\n if (arithmeticNeedsParentheses(operation, operation.right, true)) right = '(' + right + ')';\n return left + ' ' + operation.operator + ' ' + right;\n }\n if (operation instanceof Alias) {\n return sqlOperationToString(operation.element, d) + ' AS ' + d.quoteIdentifier(operation.name);\n }\n throw new TypeError('Unknown operation in sqlOperationToString: ' + operation.constructor.name);\n}\n\nfunction embeddedOf(ref: Attribute | ColumnWithJoin): Attribute | ColumnWithJoin | undefined {\n return ref instanceof Attribute ? ref.embedded() : ref.embedded;\n}\n\nfunction findColumn(operation: RelationalOperationElement): ColumnWithJoin {\n if (operation instanceof UnaryOperation) return findColumn(operation.element);\n if (operation instanceof ColumnWithJoin) return operation;\n throw new TypeError('Cannot find ColumnWithJoin in: ' + operation.constructor.name);\n}\n\nfunction openEndClause(\n endAttr: DateTimeAttribute | DateAttribute,\n value: Date,\n infiniteDatetime?: string,\n): Operation {\n const gtOp = endAttr instanceof DateTimeAttribute ? endAttr.gt(value) : endAttr.gt(value);\n if (infiniteDatetime === undefined) {\n const colRef = new ColumnWithJoin(endAttr.column(), endAttr.parent());\n return new LogicalOperation(gtOp, LogicalOperator.OR, new IsNullOperation(colRef));\n }\n return gtOp;\n}\n\n/** The operations ANDed together left to right, ignoring the missing ones; null if there are none. */\nfunction andAll(ops: (Operation | null)[]): Operation | null {\n const present = ops.filter((op): op is Operation => op !== null);\n if (present.length === 0) return null;\n return present.slice(1).reduce<Operation>((left, right) => new LogicalOperation(left, LogicalOperator.AND, right), present[0]);\n}\n\n/** The table's processing range contains the processing date. */\nfunction processingPredicate(\n mc: MilestoningColumns,\n processingDatetime: Date | null,\n joinNode?: JoinTreeNodeOperation,\n): Operation | null {\n if (!(mc instanceof ProcessingTemporalColumns || mc instanceof BusinessDateAndProcessingTemporalColumns || mc instanceof BiTemporalColumns)\n || processingDatetime === null) return null;\n const startAt = new DateTimeAttribute('start_at', mc.startAtColumn.name, mc.startAtColumn.type, mc.startAtColumn.table!.qualifiedName, joinNode);\n const endAt = new DateTimeAttribute('end_at', mc.endAtColumn.name, mc.endAtColumn.type, mc.endAtColumn.table!.qualifiedName, joinNode);\n return new LogicalOperation(startAt.lte(processingDatetime), LogicalOperator.AND, openEndClause(endAt, processingDatetime, mc.infiniteDatetime));\n}\n\n/** The table's business range contains the business date, or its business date column equals it. */\nfunction businessPredicate(\n mc: MilestoningColumns,\n businessDate: Date | null,\n joinNode?: JoinTreeNodeOperation,\n): Operation | null {\n if (businessDate === null) return null;\n if (mc instanceof BiTemporalColumns) {\n const dateFrom = new DateAttribute('business_date_from', mc.businessDateFromColumn.name, mc.businessDateFromColumn.type, mc.businessDateFromColumn.table!.qualifiedName, joinNode);\n const dateTo = new DateAttribute('business_date_to', mc.businessDateToColumn.name, mc.businessDateToColumn.type, mc.businessDateToColumn.table!.qualifiedName, joinNode);\n return new LogicalOperation(dateFrom.lte(businessDate), LogicalOperator.AND, openEndClause(dateTo, businessDate, mc.infiniteDatetime));\n }\n if (mc instanceof BusinessDateAndProcessingTemporalColumns || mc instanceof SingleBusinessDateColumn) {\n const businessAtt = new DateAttribute('business_date', mc.businessDateColumn.name, mc.businessDateColumn.type, mc.businessDateColumn.table!.qualifiedName, joinNode);\n return businessAtt.eq(businessDate);\n }\n return null;\n}\n\n/** The table's business range overlaps the business date range, or its business date column is within it. */\nfunction businessRangePredicate(\n mc: MilestoningColumns,\n businessDateFrom: Date | null,\n businessDateTo: Date | null,\n joinNode?: JoinTreeNodeOperation,\n): Operation | null {\n if (businessDateFrom === null || businessDateTo === null) return null;\n if (mc instanceof BiTemporalColumns) {\n const dateFrom = new DateAttribute('business_date_from', mc.businessDateFromColumn.name, mc.businessDateFromColumn.type, mc.businessDateFromColumn.table!.qualifiedName, joinNode);\n const dateTo = new DateAttribute('business_date_to', mc.businessDateToColumn.name, mc.businessDateToColumn.type, mc.businessDateToColumn.table!.qualifiedName, joinNode);\n return new LogicalOperation(dateFrom.lte(businessDateTo), LogicalOperator.AND, openEndClause(dateTo, businessDateFrom, mc.infiniteDatetime));\n }\n if (mc instanceof BusinessDateAndProcessingTemporalColumns || mc instanceof SingleBusinessDateColumn) {\n const businessAtt = new DateAttribute('business_date', mc.businessDateColumn.name, mc.businessDateColumn.type, mc.businessDateColumn.table!.qualifiedName, joinNode);\n return new LogicalOperation(businessAtt.gte(businessDateFrom), LogicalOperator.AND, businessAtt.lte(businessDateTo));\n }\n return null;\n}\n\n/** The milestoning filter for a point in time: the processing range, then the business range, ANDed together. */\nfunction buildMilestoningFilterOperation(\n businessDate: Date | null,\n processingDatetime: Date | null,\n table: MilestonedTable,\n joinNode?: JoinTreeNodeOperation,\n): Operation | null {\n const mc = table.milestoningColumns;\n return andAll([processingPredicate(mc, processingDatetime, joinNode), businessPredicate(mc, businessDate, joinNode)]);\n}\n\n/**\n * Like buildMilestoningFilterOperation but applies a business-date range filter.\n *\n * Bitemporal tables use interval overlap:\n * business_date_from_col <= businessDateTo AND business_date_to_col > businessDateFrom\n * Single-date tables:\n * business_date >= businessDateFrom AND business_date <= businessDateTo\n * Processing-date filtering is point-in-time, as in the normal path.\n */\nfunction buildMilestoningFilterOperationForDateRange(\n businessDateFrom: Date | null,\n businessDateTo: Date | null,\n processingDatetime: Date | null,\n table: MilestonedTable,\n joinNode?: JoinTreeNodeOperation,\n): Operation | null {\n const mc = table.milestoningColumns;\n return andAll([\n processingPredicate(mc, processingDatetime, joinNode),\n businessRangePredicate(mc, businessDateFrom, businessDateTo, joinNode),\n ]);\n}\n\ntype RefVisitor = (ref: Attribute | ColumnWithJoin) => void;\n\ntype NodeVisitor = (node: JoinTreeNodeOperation) => void;\n\n/**\n * Call `visit` for every Attribute/ColumnWithJoin referenced anywhere in `op`, and `visitExists` for the\n * join node of every exists()/notExists(). The latter are not attribute references, so they don't count\n * against whether other references to the same node can be satisfied by an embedded alternate.\n */\nfunction walkRefs(\n op: RelationalOperationElement | null | undefined,\n visit: RefVisitor,\n visitExists?: NodeVisitor,\n): void {\n if (op === null || op === undefined) return;\n if (op instanceof Attribute || op instanceof ColumnWithJoin) {\n visit(op);\n } else if (op instanceof ExistsOperation || op instanceof NotExistsOperation) {\n visitExists?.(op.node);\n } else if (op instanceof AggregateOperation) {\n walkRefs(op.element, visit, visitExists);\n if (op.window) walkWindowSpec(op.window, visit, visitExists);\n for (const sort of op.orderBy) walkRefs(sort, visit, visitExists);\n } else if (op instanceof WindowFunctionOperation) {\n if (op.element) walkRefs(op.element, visit, visitExists);\n if (op.window) walkWindowSpec(op.window, visit, visitExists);\n } else if (op instanceof ScalarFunctionOperation || op instanceof DateExtractOperation || op instanceof DateTruncOperation ||\n op instanceof DateArithmeticOperation || op instanceof DateDiffOperation ||\n op instanceof IsNullOperation || op instanceof IsNotNullOperation ||\n op instanceof InOperation || op instanceof NotInOperation) {\n walkRefs((op as UnaryOperation).element, visit, visitExists);\n } else if (op instanceof Alias) {\n walkRefs(op.element, visit, visitExists);\n } else if (op instanceof ConcatOperation) {\n for (const part of op.parts) walkRefs(part, visit, visitExists);\n } else if (op instanceof ArithmeticOperation) {\n walkRefs(op.left, visit, visitExists);\n walkRefs(op.right, visit, visitExists);\n } else if (op instanceof CaseOperation) {\n walkRefs(op.condition, visit, visitExists);\n walkRefs(op.then, visit, visitExists);\n walkRefs(op.fallback, visit, visitExists);\n } else if (op instanceof SortOperation) {\n walkRefs(op.column, visit, visitExists);\n } else if (op instanceof LogicalOperation || op instanceof ComparisonOperation) {\n walkRefs((op as any).left, visit, visitExists);\n walkRefs((op as any).right, visit, visitExists);\n }\n}\n\nfunction walkWindowSpec(window: WindowSpecification, visit: RefVisitor, visitExists?: NodeVisitor): void {\n for (const p of window.partitionBy) walkRefs(p, visit, visitExists);\n for (const s of window.orderBy) walkRefs(s.column, visit, visitExists);\n}\n\n/**\n * Translate property-equality filters given to a related finder (e.g. `ef.projects({ code: 'ALPHA' })`)\n * into a relational filter on the join node. `columnMap` maps property ids to [column, type, table].\n */\nfunction buildJoinFilterFromProperties(\n node: JoinTreeNodeOperation,\n filter: Record<string, unknown>,\n columnMap: Record<string, [string, string, string]>,\n): Operation {\n const ops: Operation[] = [];\n for (const [key, value] of Object.entries(filter)) {\n const entry = columnMap[key];\n if (entry === undefined) {\n throw new Error(`Unknown property '${key}' — valid properties are: ${Object.keys(columnMap).sort().join(', ')}`);\n }\n const [name, type, table] = entry;\n const col = new ColumnWithJoin(new Column(name, type, table), node);\n let constant: ConstantOperation;\n if (typeof value === 'boolean') constant = new BooleanConstantOperation(value);\n else if (typeof value === 'number') constant = Number.isInteger(value) ? new IntegerConstantOperation(value) : new FloatConstantOperation(value);\n else if (value instanceof Date) constant = type.toUpperCase() === 'DATE' ? new DateConstantOperation(value) : new DateTimeConstantOperation(value);\n else constant = new StringConstantOperation(String(value));\n ops.push(new ComparisonOperation(col, ComparisonOperator.EQUAL, constant));\n }\n return ops.reduce((acc, op) => new LogicalOperation(acc, LogicalOperator.AND, op));\n}\n\n/**\n * The nodes plus every ancestor, each once, ancestors first. The SQL generator joins a node's\n * ancestors whenever it joins the node, so each of them needs its join filter set too, not only the\n * nodes an expression refers to directly.\n */\nfunction withAncestors(nodes: Iterable<JoinTreeNodeOperation>): JoinTreeNodeOperation[] {\n const ordered = new Set<JoinTreeNodeOperation>();\n const add = (node: JoinTreeNodeOperation): void => {\n if (ordered.has(node)) return;\n if (node.parent !== undefined) add(node.parent);\n ordered.add(node);\n };\n for (const node of nodes) add(node);\n return [...ordered];\n}\n\nfunction buildQueryOperation(\n businessDate: Date | null,\n processingDatetime: Date | null,\n columns: (Attribute | RelationalOperationElement)[],\n table: Table,\n op: RelationalOperationElement,\n orderBy: SortOperation[] = [],\n groupBy: Attribute[] = [],\n limit?: number,\n businessDateTo: Date | null = null,\n distinct: boolean = false,\n offset?: number,\n having?: Operation,\n): SelectOperation {\n let filter = op;\n const milestoningFor = (t: MilestonedTable, node?: JoinTreeNodeOperation) =>\n businessDateTo !== null\n ? buildMilestoningFilterOperationForDateRange(businessDate, businessDateTo, processingDatetime, t, node)\n : buildMilestoningFilterOperation(businessDate, processingDatetime, t, node);\n\n if (table instanceof MilestonedTable) {\n const milestonedOp = milestoningFor(table);\n if (milestonedOp !== null) {\n filter = filter instanceof NoOperation\n ? milestonedOp\n : new LogicalOperation(filter, LogicalOperator.AND, milestonedOp);\n }\n }\n\n const requiredJoins = new Set<JoinTreeNodeOperation>();\n const collect: RefVisitor = ref => {\n const parent = ref instanceof Attribute ? ref.parent() : ref.parent;\n if (parent !== undefined) requiredJoins.add(parent);\n };\n const collectNode: NodeVisitor = node => requiredJoins.add(node);\n for (const col of columns) walkRefs(col, collect, collectNode);\n for (const expr of groupBy) walkRefs(expr, collect, collectNode);\n for (const sort of orderBy) walkRefs(sort, collect, collectNode);\n walkRefs(op, collect, collectNode);\n\n const joinFilters = new Map<JoinTreeNodeOperation, Operation>();\n for (const node of withAncestors(requiredJoins)) {\n let combined: Operation | undefined;\n if (Object.keys(node.join.filterKwargs).length > 0) {\n combined = buildJoinFilterFromProperties(node, node.join.filterKwargs, node.join.filterColumnMap);\n }\n if (node.join.target instanceof MilestonedTable) {\n const milestonedOp = milestoningFor(node.join.target, node);\n if (milestonedOp !== null) {\n combined = combined === undefined ? milestonedOp : new LogicalOperation(combined, LogicalOperator.AND, milestonedOp);\n }\n }\n if (combined !== undefined) joinFilters.set(node, combined);\n }\n\n return new SelectOperation(columns, filter, orderBy, groupBy, limit, table, joinFilters, distinct, offset, having);\n}\n\n/**\n * Whether `child` must be parenthesised where it is an operand of `parent`.\n *\n * A logical operation nested in one with a different operator is parenthesised: OR inside AND would\n * otherwise change meaning, and AND inside OR is easier to read. The same operator needs none, since\n * AND and OR are associative, so a AND (b AND c) is a AND b AND c.\n */\nexport function needsParentheses(parent: LogicalOperation, child: RelationalOperationElement): boolean {\n return child instanceof LogicalOperation && child.operator !== parent.operator;\n}\n\n/** Whether a value is read through a to-many association, so it repeats the row it is read for. */\nfunction reachesToMany(op: RelationalOperationElement): boolean {\n if (op instanceof ColumnWithJoin) {\n for (let node = op.parent; node !== undefined; node = node.parent) if (node.many) return true;\n return false;\n }\n if (op instanceof UnaryOperation || op instanceof Alias) return reachesToMany(op.element);\n if (op instanceof BinaryOperation) return reachesToMany(op.left) || reachesToMany(op.right);\n return false;\n}\n\n/** A column with any alias around it taken off. */\nfunction unaliased(op: unknown): unknown {\n return op instanceof Alias ? unaliased(op.element) : op;\n}\n\nclass SQLQueryGenerator {\n constructor(private readonly _dialect: SqlDialect) {}\n\n private _select: Alias[] = [];\n private _from: Set<TableAlias> = new Set();\n private _join: Join[] = [];\n private _groupByParts: string[] = [];\n private _having = '';\n private _orderByParts: string[] = [];\n private _where = '';\n private _limit?: number;\n private _distinct = false;\n private _offset?: number;\n private _tableAliasIncr = 0;\n private _tableAliasesByTable = new Map<unknown, TableAlias>();\n private _addedJoinIds = new Set<JoinTreeNodeOperation>();\n private _rootTable?: Table;\n private _elidableNodes = new Set<JoinTreeNodeOperation>();\n private _joinFilters: ReadonlyMap<JoinTreeNodeOperation, Operation> = new Map();\n private _guardOptional = true;\n\n generate(select: SelectOperation): void {\n this._rootTable = select.table;\n this._elidableNodes = this._computeElidableNodes(select);\n this._joinFilters = select.joinFilters;\n if (this._rootTable !== undefined) {\n this._from.add(this._tableAliasForTable(this._rootTable.qualifiedName, this._rootTable.qualifiedName));\n }\n this.processSelect(select.display);\n this._where = this.buildFilter(select.filter);\n const groupByJoins = new Map<JoinTreeNodeOperation, JoinTreeNodeOperation>();\n for (const expr of select.groupBy) {\n this._collectRequiredJoins(expr, groupByJoins);\n }\n for (const node of groupByJoins.values()) {\n this._addJoin(node);\n }\n this._groupByParts = this._groupByPartsFor(select);\n this._having = '';\n if (select.having !== undefined) {\n const havingJoins = new Map<JoinTreeNodeOperation, JoinTreeNodeOperation>();\n this._collectRequiredJoins(select.having, havingJoins);\n for (const node of havingJoins.values()) this._addJoin(node);\n // HAVING filters the grouped result, which Legend does not guard: it is a filter on projected columns\n this._guardOptional = false;\n try {\n this._having = this.buildFilter(select.having);\n } finally {\n this._guardOptional = true;\n }\n }\n this._orderByParts = select.orderBy.map(s =>\n this._sortExpression(s.column) + this._dialect.orderDirection(s.direction),\n );\n this._limit = select.limit;\n this._distinct = select.distinct;\n this._offset = select.offset;\n }\n\n /**\n * The GROUP BY of a query: the grouping it was given, else the grouping its columns imply.\n *\n * Columns that are not aggregated are what the aggregates are computed for, so a query that selects both is\n * grouped by those columns (as a DataFrame's `groupby(columns).agg(...)` does). An aggregate read through a\n * to-many association is computed for each row of the root table, as Legend does, so the root's primary key\n * is grouped by too. A query that selects only aggregates over the root's own columns is not grouped: the\n * aggregate covers every row. A constant needs no grouping: a bare\n * `GROUP BY 7` would be a column position.\n */\n private _groupByPartsFor(select: SelectOperation): string[] {\n if (select.groupBy.length > 0) return select.groupBy.map(a => this._attrToColString(a as Attribute));\n const aggregates = select.display.filter(containsAggregate);\n if (aggregates.length === 0) return [];\n const perRoot = select.table !== undefined && aggregates.some(reachesToMany);\n const keys = perRoot ? select.table!.columns.filter(c => c.primaryKey).map(c => this._columnToString(c)) : [];\n const grouped = select.display\n .map((column, i) => ({ column, shown: this._select[i] }))\n .filter(({ column }) => !containsAggregateOrWindow(column) && !(unaliased(column) instanceof ConstantOperation))\n .map(({ shown }) => sqlOperationToString(shown.element, this._dialect));\n return [...new Set([...keys, ...grouped])];\n }\n\n /** What a sort orders by: a column, or an expression such as an aggregate. */\n private _sortExpression(expression: RelationalOperationElement): string {\n if (expression instanceof ColumnWithJoin || expression instanceof Attribute) return this.buildFilter(expression);\n return sqlOperationToString(this._rewriteOperation(expression), this._dialect);\n }\n\n private _columnToString(column: Column): string {\n return this._tableAliasForTable(column.owner!, column.owner!).alias + '.' + column.name;\n }\n\n private _attrToColString(attr: Attribute): string {\n const { column, parent } = this._resolve(attr);\n const ta = this._tableAliasForTable(column.owner!, parent ?? column.owner!);\n return ta.alias + '.' + column.name;\n }\n\n private _collectRequiredJoins(op: RelationalOperationElement | null | undefined, out: Map<JoinTreeNodeOperation, JoinTreeNodeOperation>): void {\n walkRefs(op, ref => {\n const { parent } = this._resolve(ref);\n if (parent !== undefined) out.set(parent, parent);\n });\n }\n\n /**\n * Determine upfront which join nodes can be satisfied entirely by embedded (join-less) alternates:\n * a node is elidable when every reference to it has an embedded alternate. A reference without one\n * (e.g. a milestoning column) keeps the join for every reference to that node.\n */\n private _computeElidableNodes(select: SelectOperation): Set<JoinTreeNodeOperation> {\n const refsByNode = new Map<JoinTreeNodeOperation, (Attribute | ColumnWithJoin)[]>();\n const record = (ref: Attribute | ColumnWithJoin) => {\n const parent = ref instanceof Attribute ? ref.parent() : ref.parent;\n if (parent === undefined) return;\n const refs = refsByNode.get(parent);\n if (refs) refs.push(ref); else refsByNode.set(parent, [ref]);\n };\n for (const col of select.display) walkRefs(col, record);\n for (const expr of select.groupBy) walkRefs(expr, record);\n for (const sort of select.orderBy) walkRefs(sort, record);\n walkRefs(select.filter, record);\n\n const elidable = new Set<JoinTreeNodeOperation>();\n for (const [node, refs] of refsByNode) {\n if (refs.every(ref => embeddedOf(ref) !== undefined)) elidable.add(node);\n }\n return elidable;\n }\n\n /** The (column, parent) a reference should resolve to, substituting its embedded alternate when its join is elided. */\n private _resolve(ref: Attribute | ColumnWithJoin): { column: Column; parent?: JoinTreeNodeOperation } {\n const column = ref instanceof Attribute ? ref.column() : ref.column;\n const parent = ref instanceof Attribute ? ref.parent() : ref.parent;\n if (parent !== undefined && this._elidableNodes.has(parent)) {\n const embedded = embeddedOf(ref);\n if (embedded !== undefined) return this._resolve(embedded);\n }\n return { column, parent };\n }\n\n /** Whether the value `op` reads can be missing, in the join or embedded form that is used for it. */\n private _resolveOptional(op: ColumnWithJoin): boolean {\n if (op.parent !== undefined && this._elidableNodes.has(op.parent) && op.embedded !== undefined) {\n return this._resolveOptional(op.embedded);\n }\n return op.optional;\n }\n\n private _rewriteWindowSpec(window: WindowSpecification): WindowSpecification {\n const partitionBy = window.partitionBy.map(p => this._rewriteOperation(p));\n const orderBy = window.orderBy.map(s => new SortOperation(this._rewriteOperation(s.column) as ColumnWithJoin, s.direction));\n return new WindowSpecification(partitionBy, orderBy);\n }\n\n private _rewriteOperation(op: RelationalOperationElement): RelationalOperationElement {\n if (op instanceof Attribute || op instanceof ColumnWithJoin) {\n const { column, parent } = this._resolve(op);\n return new TableAliasColumn(column, this._tableAliasForTable(column.owner!, parent ?? column.owner!));\n }\n if (op instanceof Column) {\n const ta = this._tableAliasForTable(op.owner!, op.owner!);\n return new TableAliasColumn(op, ta);\n }\n if (op instanceof AggregateOperation) {\n return new AggregateOperation(\n this._rewriteOperation(op.element), op.operator, op.displayName,\n op.window ? this._rewriteWindowSpec(op.window) : undefined,\n op.separator, op.orderBy.map(s => new SortOperation(this._rewriteOperation(s.column), s.direction)),\n );\n }\n if (op instanceof CaseOperation) return new RenderedSql(this._caseSql(op));\n if (isCondition(op)) return new RenderedSql(this.buildFilter(op as Operation)); // a condition inside an expression, such as the argument of an aggregate\n if (op instanceof ConcatOperation) return new ConcatOperation(op.parts.map(part => this._rewriteOperation(part)), op.displayName);\n if (op instanceof ArithmeticOperation) {\n return new ArithmeticOperation(this._rewriteOperation(op.left), op.operator, this._rewriteOperation(op.right), op.displayName);\n }\n if (op instanceof WindowFunctionOperation) {\n const el = op.element ? this._rewriteOperation(op.element) : null;\n return new WindowFunctionOperation(el, op.func, op.displayName, op.secondArg, [...op.extraArgs],\n op.window ? this._rewriteWindowSpec(op.window) : undefined);\n }\n if (op instanceof ScalarFunctionOperation) {\n return new ScalarFunctionOperation(this._rewriteOperation(op.element), op.func, op.displayName, op.secondArg, op.extraArgs);\n }\n if (op instanceof DateExtractOperation) {\n return new DateExtractOperation(this._rewriteOperation(op.element), op.part, op.displayName);\n }\n if (op instanceof DateTruncOperation) {\n return new DateTruncOperation(this._rewriteOperation(op.element), op.part, op.displayName);\n }\n if (op instanceof DateArithmeticOperation) {\n return new DateArithmeticOperation(this._rewriteOperation(op.element), op.n, op.unit, op.isAdd, op.displayName);\n }\n if (op instanceof DateDiffOperation) {\n return new DateDiffOperation(this._rewriteOperation(op.element), (op as DateDiffOperation).other, (op as DateDiffOperation).unit, op.displayName);\n }\n return op;\n }\n\n /** The CASE written out now: its condition can only be rendered while the query is being built. */\n private _caseSql(op: CaseOperation): string {\n const branch = (value: RelationalOperationElement): string =>\n value instanceof ConstantOperation ? constantValueString(value, this._dialect) : sqlOperationToString(this._rewriteOperation(value), this._dialect);\n let sql = 'CASE WHEN ' + this.buildFilter(op.condition) + ' THEN ' + branch(op.then);\n if (op.fallback !== undefined) sql += ' ELSE ' + branch(op.fallback);\n return sql + ' END';\n }\n\n private processSelect(cols: (Attribute | RelationalOperationElement)[]): void {\n const requiredJoins = new Map<JoinTreeNodeOperation, JoinTreeNodeOperation>();\n\n for (const col of cols) {\n this._collectRequiredJoins(col, requiredJoins);\n }\n for (const node of requiredJoins.values()) {\n this._addJoin(node);\n }\n\n for (const col of cols) this._selectColumn(col);\n }\n\n /** Add one column to the select list. An alias reads the column it wraps, then names the entry. */\n private _selectColumn(col: Attribute | RelationalOperationElement): void {\n if (col instanceof Alias) {\n this._selectColumn(col.element);\n const read = this._select.pop()!;\n this._select.push(new Alias(read.element, col.name));\n } else if (col instanceof Attribute) {\n const { column, parent: node } = this._resolve(col);\n let ta: TableAlias;\n if (node !== undefined) {\n ta = this._tableAliasForTable(column.owner!, node);\n } else {\n ta = this._tableAliasForTable(column.owner!, column.owner!);\n this._from.add(ta);\n }\n this._select.push(new Alias(new TableAliasColumn(column, ta), col.displayName()));\n } else if (col instanceof WindowFunctionOperation) {\n const rewritten = this._rewriteOperation(col) as WindowFunctionOperation;\n let alias: string;\n if (col.displayName) {\n alias = col.displayName;\n } else if ([WindowFunction.ROW_NUMBER, WindowFunction.RANK, WindowFunction.DENSE_RANK].includes(col.func)) {\n alias = col.func.replace(/_/g, ' ').replace(/\\b\\w/g, c => c.toUpperCase());\n } else if (col.element) {\n alias = col.func + ' ' + findColumn(col).column.name;\n } else {\n alias = col.func;\n }\n this._select.push(new Alias(rewritten, alias));\n } else if (col instanceof AggregateOperation && !(col.element instanceof ColumnWithJoin)) {\n // an aggregate of an expression: rewritten as a whole, so every column in it is resolved\n this._select.push(new Alias(this._rewriteOperation(col), col.displayName ?? 'Expression'));\n } else if (col instanceof AggregateOperation) {\n const colNested = this._resolve(findColumn(col));\n const node = colNested.parent;\n let ta: TableAlias;\n if (node !== undefined) {\n ta = this._tableAliasForTable(colNested.column.owner!, node);\n } else {\n ta = this._tableAliasForTable(colNested.column.owner!, colNested.column.owner!);\n this._from.add(ta);\n }\n const alias = col.displayName ?? col.operator + ' ' + findColumn(col).column.name;\n const rewrittenAgg = new AggregateOperation(\n new TableAliasColumn(colNested.column, ta), col.operator, undefined,\n col.window ? this._rewriteWindowSpec(col.window) : undefined,\n col.separator, col.orderBy.map(s => new SortOperation(this._rewriteOperation(s.column), s.direction)),\n );\n this._select.push(new Alias(rewrittenAgg, alias));\n } else if (col instanceof ScalarFunctionOperation) {\n // rewritten as a whole, so a function of a function keeps every step\n this._select.push(new Alias(this._rewriteOperation(col), col.displayName ?? col.func + ' ' + findColumn(col).column.name));\n } else if (col instanceof DateExtractOperation || col instanceof DateArithmeticOperation || col instanceof DateDiffOperation) {\n const colNested = this._resolve(findColumn(col as RelationalOperationElement));\n const node = colNested.parent;\n let ta: TableAlias;\n if (node !== undefined) {\n ta = this._tableAliasForTable(colNested.column.owner!, node);\n } else {\n ta = this._tableAliasForTable(colNested.column.owner!, colNested.column.owner!);\n this._from.add(ta);\n }\n const alias = (col as DateExtractOperation).displayName ?? findColumn(col as RelationalOperationElement).column.name;\n let aliasedOp: RelationalOperationElement;\n if (col instanceof DateExtractOperation) {\n aliasedOp = new DateExtractOperation(new TableAliasColumn(colNested.column, ta), col.part);\n } else if (col instanceof DateArithmeticOperation) {\n aliasedOp = new DateArithmeticOperation(new TableAliasColumn(colNested.column, ta), col.n, col.unit, col.isAdd);\n } else {\n aliasedOp = new DateDiffOperation(new TableAliasColumn(colNested.column, ta), (col as DateDiffOperation).other, (col as DateDiffOperation).unit);\n }\n this._select.push(new Alias(aliasedOp, alias));\n } else if (col instanceof CaseOperation) {\n this._select.push(new Alias(this._rewriteOperation(col), col.displayName ?? 'Expression'));\n } else if (col instanceof ConcatOperation) {\n this._select.push(new Alias(this._rewriteOperation(col), col.displayName ?? 'Expression'));\n } else if (col instanceof ArithmeticOperation) {\n this._select.push(new Alias(this._rewriteOperation(col), col.displayName ?? 'Expression'));\n } else if (col instanceof DateTruncOperation) {\n this._select.push(new Alias(this._rewriteOperation(col), col.displayName ?? findColumn(col).column.name));\n } else if (isCondition(col)) {\n this._select.push(new Alias(new RenderedSql(this.buildFilter(col)), 'Expression'));\n } else if (col instanceof ConstantOperation) {\n this._select.push(new Alias(col, 'Constant'));\n } else if (col instanceof CountAllOperation) {\n if (col.table !== '') this._from.add(this._tableAliasForTable(col.table, col.table));\n this._select.push(new Alias(col, 'Count'));\n }\n }\n\n private _addJoin(node: JoinTreeNodeOperation): void {\n if (this._addedJoinIds.has(node)) return;\n if (node.parent !== undefined) this._addJoin(node.parent);\n this._addedJoinIds.add(node);\n\n const join = node.join;\n const left = join.left;\n const srcTa = this._tableAliasForTable(left.owner!, node.parent ?? left.owner!);\n if (node.parent === undefined) this._from.add(srcTa);\n const sc = new TableAliasColumn(left, srcTa);\n const right = join.right;\n const tc = new TableAliasColumn(right, this._tableAliasForTable(right.owner!, node));\n const queryFilter = this._joinFilters.get(node);\n const filterOp = join.filter !== undefined && queryFilter !== undefined\n ? new LogicalOperation(join.filter as Operation, LogicalOperator.AND, queryFilter)\n : join.filter ?? queryFilter;\n this._join.push(new Join(sc, tc, filterOp));\n }\n\n buildFilter(op: RelationalOperationElement): string {\n if (op instanceof NoOperation) return '';\n if (op instanceof ExistsOperation) {\n const col = op.node.join.right;\n return this.buildFilter(new ColumnWithJoin(col, op.node)) + ' IS NOT NULL';\n }\n if (op instanceof NotExistsOperation) {\n const col = op.node.join.right;\n return this.buildFilter(new ColumnWithJoin(col, op.node)) + ' IS NULL';\n }\n if (op instanceof InOperation) {\n return this.buildFilter(op.element) + ' IN (' + op.values.map(value => constantValueString(value, this._dialect)).join(', ') + ')';\n }\n if (op instanceof NotInOperation) {\n const column = this.buildFilter(op.element);\n const sql = column + ' NOT IN (' + op.values.map(value => constantValueString(value, this._dialect)).join(', ') + ')';\n // NULL NOT IN (...) is not true in SQL, so a nullable column has to match its NULLs explicitly\n if (op.element instanceof ColumnWithJoin && this._resolve(op.element).column.nullable) {\n return '(' + sql + ' OR ' + column + ' IS NULL)';\n }\n return sql;\n }\n if (op instanceof IsNotNullOperation) return this.buildFilter(op.element) + ' IS NOT NULL';\n if (op instanceof IsNullOperation) return this.buildFilter(op.element) + ' IS NULL';\n if (op instanceof LogicalOperation) {\n let left = this.buildFilter(op.left);\n let right = this.buildFilter(op.right);\n if (needsParentheses(op, op.left)) left = '(' + left + ')';\n if (needsParentheses(op, op.right)) right = '(' + right + ')';\n return left + LOGICAL_OPERATOR_STR[op.operator] + right;\n }\n if (op instanceof ComparisonOperation) {\n let sql = this.buildFilter(op.left) + COMPARISON_OPERATOR_STR[op.operator] + this.buildFilter(op.right);\n if ((op.operator === ComparisonOperator.LIKE || op.operator === ComparisonOperator.NOT_LIKE)\n && op.right instanceof StringConstantOperation\n && (op.right.value.includes(LIKE_ESCAPE) || op.right.value.includes('\\\\'))) {\n // the pattern has a literal %, _ or escape character in it, or a backslash, which Postgres and Databricks\n // would otherwise take as LIKE's own escape\n sql += \" ESCAPE '\" + LIKE_ESCAPE + \"'\";\n }\n if (this._guardOptional && GUARDED_COMPARISONS.has(op.operator) && op.left instanceof ColumnWithJoin\n && this._resolveOptional(op.left)) {\n // as in Legend, an ordering or pattern comparison on an optional property says it needs a value\n sql = '(' + this.buildFilter(op.left) + ' IS NOT NULL AND ' + sql + ')';\n }\n return sql;\n }\n if (op instanceof ConstantOperation) return constantValueString(op, this._dialect);\n if (op instanceof ScalarFunctionOperation || op instanceof ArithmeticOperation || op instanceof ConcatOperation\n || op instanceof DateTruncOperation || op instanceof AggregateOperation || op instanceof CountAllOperation) {\n // an expression compared in a filter needs its columns' joins, then is written as in a select list\n const required = new Map<JoinTreeNodeOperation, JoinTreeNodeOperation>();\n this._collectRequiredJoins(op, required);\n for (const node of required.values()) this._addJoin(node);\n return sqlOperationToString(this._rewriteOperation(op), this._dialect);\n }\n if (op instanceof ColumnWithJoin) {\n const { column, parent: node } = this._resolve(op);\n let ta: TableAlias;\n if (node !== undefined) {\n ta = this._tableAliasForTable(column.owner!, node);\n this._addJoin(node);\n } else {\n ta = this._tableAliasForTable(column.owner!, column.owner!);\n }\n return ta.alias + '.' + column.name;\n }\n if (op instanceof Column) {\n const ta = this._tableAliasForTable(op.owner!, op.owner!);\n return ta.alias + '.' + op.name;\n }\n throw new Error('Unknown operation in buildFilter: ' + op.constructor.name);\n }\n\n private _tableAliasForTable(table: string, key: unknown): TableAlias {\n if (this._tableAliasesByTable.has(key)) {\n return this._tableAliasesByTable.get(key)!;\n }\n const ta = new TableAlias(table, 't' + this._tableAliasIncr++);\n this._tableAliasesByTable.set(key, ta);\n return ta;\n }\n\n buildQueryString(): string {\n const joins = this._join.map(j =>\n ' LEFT OUTER JOIN ' + j.target.tableAlias.table + ' AS ' + j.target.tableAlias.alias +\n ' ON (' + j.condition() +\n (j.filterOp ? ' AND ' + this.buildFilter(j.filterOp) : '') + ')',\n );\n\n return (this._distinct ? 'SELECT DISTINCT ' : 'SELECT ') + this._select.map(ca => sqlOperationToString(ca, this._dialect)).join(',') +\n ' FROM ' + Array.from(this._from).map(ta => ta.table + ' AS ' + ta.alias).join(',') +\n joins.join('') +\n this._buildWhere() +\n this._buildGroupBy() +\n this._buildHaving() +\n this._buildOrderBy() +\n this._buildLimit() +\n this._buildOffset();\n }\n\n private _buildWhere(): string {\n return this._where.length > 0 ? ' WHERE ' + this._where : '';\n }\n private _buildGroupBy(): string {\n return this._groupByParts.length > 0 ? ' GROUP BY ' + this._groupByParts.join(', ') : '';\n }\n private _buildHaving(): string {\n return this._having.length > 0 ? ' HAVING ' + this._having : '';\n }\n private _buildOrderBy(): string {\n return this._orderByParts.length > 0 ? ' ORDER BY ' + this._orderByParts.join(', ') : '';\n }\n private _buildOffset(): string {\n return this._offset !== undefined ? ' OFFSET ' + this._offset : '';\n }\n\n private _buildLimit(): string {\n return this._limit !== undefined ? ' LIMIT ' + this._limit : '';\n }\n}\n\nexport function selectSqlToString(selectOperation: SelectOperation, dialect: DialectName | SqlDialect = 'postgres'): string {\n const qg = new SQLQueryGenerator(dialectOf(dialect));\n qg.generate(selectOperation);\n return qg.buildQueryString();\n}\n\nexport function toSql(\n businessDate: Date | null,\n processingDatetime: Date | null,\n columns: (Attribute | RelationalOperationElement)[],\n table: Table,\n op: RelationalOperationElement,\n orderBy: SortOperation[] = [],\n groupBy: Attribute[] = [],\n limit?: number,\n businessDateTo: Date | null = null,\n distinct: boolean = false,\n offset?: number,\n having?: Operation,\n dialect: DialectName | SqlDialect = 'postgres',\n): string {\n const selectOp = buildQueryOperation(businessDate, processingDatetime, columns, table, op, orderBy, groupBy, limit, businessDateTo, distinct, offset, having);\n return selectSqlToString(selectOp, dialect);\n}\n\nexport { buildQueryOperation };\n","/** Python's `str.title()`: uppercase the first letter of each alphabetic run and lowercase the rest. */\nexport function titleCase(value: string): string {\n return value.replace(/[A-Za-z]+/g, w => w[0].toUpperCase() + w.slice(1).toLowerCase());\n}\n","import type { Attribute } from './attribute';\n\n/**\n * Join-less alternates for a related class's properties, keyed by dotted property path relative to\n * that class (e.g. `name`, `branch.city`). The attributes point at flat columns on the owning table.\n */\nexport type EmbeddedAttributes = Record<string, Attribute>;\n\n/** The alternates under `prefix` (e.g. `branch.`), re-keyed relative to it; undefined when there are none. */\nexport function embeddedUnder(embedded: EmbeddedAttributes | undefined, prefix: string): EmbeddedAttributes | undefined {\n if (!embedded) return undefined;\n const result: EmbeddedAttributes = {};\n for (const [key, attr] of Object.entries(embedded)) {\n if (key.startsWith(prefix)) result[key.slice(prefix.length)] = attr;\n }\n return Object.keys(result).length > 0 ? result : undefined;\n}\n","import { ExistsOperation, NotExistsOperation, JoinTreeNodeOperation } from '../model/relational';\nimport { titleCase } from './naming';\n\n/**\n * The display-name prefix for a column reached through a join: the relation names from the root, so\n * `account().branch().city()` is \"Account Branch City\" and not just \"Branch City\".\n */\nexport function displayPrefix(relationName: string, parentJoin?: JoinTreeNodeOperation): string {\n const names = [relationName];\n for (let node = parentJoin; node !== undefined; node = node.parent) names.push(node.join.name);\n return names.reverse().map(titleCase).join(' ');\n}\n\nexport class RelatedFinder {\n constructor(private readonly _node: JoinTreeNodeOperation) {}\n\n exists(): ExistsOperation {\n return new ExistsOperation(this._node);\n }\n\n notExists(): NotExistsOperation {\n return new NotExistsOperation(this._node);\n }\n}\n","import { Attribute } from './attribute';\nimport { toSql } from './sql-generator';\nimport { DialectName, SqlDialect } from './dialect';\nimport {\n Table,\n Operation,\n SortOperation,\n NoOperation,\n RelationalOperationElement,\n ColumnWithJoin,\n DateOnly,\n DATE_ONLY_PATTERN,\n} from '../model/relational';\n\nexport type Row = unknown[];\n\nexport const DEFAULT_TIMEOUT_MS = 60_000;\n\n/** Thrown by a QueryRunner when a query runs longer than the timeout set on its FinderResult. */\nexport class QueryTimeoutError extends Error {\n constructor(readonly timeoutMs: number) {\n super(`Query exceeded ${timeoutMs}ms timeout`);\n this.name = 'QueryTimeoutError';\n }\n}\n\n/** Minimum interface satisfied by both Table (SQL) and GraphQLQuery (GraphQL). */\nexport interface QueryTarget {\n readonly name: string;\n}\n\nexport interface QueryRunner {\n /** The SQL a runner that executes SQL sends: `toSql()` writes it for this dialect. Postgres when absent. */\n readonly dialect?: DialectName | SqlDialect;\n\n select(\n businessDate: Date | null,\n processingDatetime: Date | null,\n columns: (Attribute | RelationalOperationElement)[],\n table: QueryTarget,\n op: RelationalOperationElement,\n orderBy?: SortOperation[],\n groupBy?: Attribute[],\n limit?: number,\n timeoutMs?: number,\n businessDateTo?: Date | null,\n distinct?: boolean,\n offset?: number,\n having?: Operation,\n ): Promise<Row[]>;\n}\n\nlet _runner: QueryRunner | null = null;\n\nexport function registerRunner(runner: QueryRunner): void { _runner = runner; }\nexport function clearRunner(): void { _runner = null; }\nexport function getRunner(): QueryRunner {\n if (!_runner) throw new Error('No query runner registered. Call registerRunner() first.');\n return _runner;\n}\n\nconst expressionIds = new WeakMap<object, number>();\nlet nextExpressionId = 1;\n\n/**\n * What a sort orders by: a column and the joins to reach it. Any other expression, such as an aggregate, is its\n * own target, so sorting by an expression again adds a sort.\n */\nfunction sortTarget(sort: SortOperation): string {\n const column = sort.column;\n if (!(column instanceof ColumnWithJoin)) {\n if (!expressionIds.has(column)) expressionIds.set(column, nextExpressionId++);\n return JSON.stringify(['expression', expressionIds.get(column)]);\n }\n const joins: string[] = [];\n for (let node = column.parent; node !== undefined; node = node.parent) joins.push(node.join.name);\n return JSON.stringify([column.column.owner, column.column.name, joins]);\n}\n\nexport class FinderResult {\n private _orderBy: SortOperation[] = [];\n private _groupBy: Attribute[] = [];\n private _limit?: number;\n private _distinct = false;\n private _offset?: number;\n private _having?: Operation;\n private _timeoutMs: number = DEFAULT_TIMEOUT_MS;\n\n constructor(\n private readonly _businessDate: Date | null,\n private readonly _processingDatetime: Date | null,\n private readonly _columns: (Attribute | RelationalOperationElement)[],\n private readonly _table: QueryTarget,\n private readonly _op: RelationalOperationElement,\n private readonly _businessDateTo: Date | null = null,\n ) {}\n\n /**\n * Order the rows. Calls accumulate: the sorts of the latest call take priority and earlier ones order the\n * rows it leaves tied, as in a chain of `sortBy` calls. Sorting a column again replaces its earlier direction.\n */\n orderBy(...sorts: SortOperation[]): this {\n const resorted = new Set(sorts.map(sortTarget));\n this._orderBy = [...sorts, ...this._orderBy.filter(s => !resorted.has(sortTarget(s)))];\n return this;\n }\n\n groupBy(...attrs: Attribute[]): this {\n this._groupBy = attrs;\n return this;\n }\n\n limit(n: number): this {\n this._limit = n;\n return this;\n }\n\n /** Skip the first `n` rows. Sort the rows first: without an order, which rows are first is not defined. */\n offset(n: number): this {\n if (!Number.isInteger(n) || n < 0) throw new Error('offset cannot be negative');\n this._offset = n;\n return this;\n }\n\n /** Rows `start` up to but not including `stop`, counting from 0: `offset(start).limit(stop - start)`. */\n slice(start: number, stop: number): this {\n if (!Number.isInteger(start) || !Number.isInteger(stop) || start < 0 || stop < start) {\n throw new Error('slice needs 0 <= start <= stop');\n }\n return this.offset(start).limit(stop - start);\n }\n\n /**\n * Keep the groups for which every condition holds: `HAVING`. A condition tests an aggregate or a grouping column:\n * `f.findAll(null, null, [f.category(), countAll()]).groupBy(f.category()).having(countAll().gt(1))`.\n * Calls accumulate, as `and` does.\n */\n having(...conditions: Operation[]): this {\n for (const condition of conditions) this._having = this._having === undefined ? condition : this._having.and(condition) as Operation;\n return this;\n }\n\n /** Return each distinct row once: `SELECT DISTINCT`. A sort on a distinct query has to use a selected column. */\n distinct(): this {\n this._distinct = true;\n return this;\n }\n\n /** Abort the query and throw QueryTimeoutError if it runs longer than `milliseconds` (default 60000). */\n timeout(milliseconds: number): this {\n this._timeoutMs = milliseconds;\n return this;\n }\n\n /** The query as SQL, in Postgres unless a dialect is given: `toSql('databricks')`. Nothing is run. */\n toSql(dialect: DialectName | SqlDialect = 'postgres'): string {\n return toSql(\n this._businessDate,\n this._processingDatetime,\n this._columns,\n this._table as Table,\n this._op,\n this._orderBy,\n this._groupBy,\n this._limit,\n this._businessDateTo,\n this._distinct,\n this._offset,\n this._having,\n dialect,\n );\n }\n\n async toRows(): Promise<Row[]> {\n return getRunner().select(\n this._businessDate,\n this._processingDatetime,\n this._columns,\n this._table,\n this._op,\n this._orderBy,\n this._groupBy,\n this._limit,\n this._timeoutMs,\n this._businessDateTo,\n this._distinct,\n this._offset,\n this._having,\n );\n }\n}\n\n/** A processing date input keeps the precision it was given: a date stays a date, a timestamp a timestamp. */\nfunction convertProcessingDate(value: Date | string | null): Date | null {\n if (typeof value === 'string' && DATE_ONLY_PATTERN.test(value)) return new DateOnly(value + 'T00:00:00Z');\n return convertDate(value);\n}\n\nfunction convertDate(value: Date | string | null): Date | null {\n if (value === null) return null;\n if (value instanceof Date) return value;\n // Zone-less strings (YYYY-MM-DD, or YYYY-MM-DD HH:MM[:SS]) are read as UTC, matching how\n // dates are formatted into SQL, so the value doesn't shift with the machine's timezone.\n let normalized = value;\n if (DATE_ONLY_PATTERN.test(value)) normalized = value + 'T00:00:00Z';\n else if (/^\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$/.test(value)) normalized = value.replace(' ', 'T') + 'Z';\n const d = new Date(normalized);\n if (isNaN(d.getTime())) throw new Error(`Cannot parse date: ${value}`);\n return d;\n}\n\nexport function convertInputsAndSelect(\n businessDate: Date | string | null,\n processingDatetime: Date | string | null,\n columns: (Attribute | RelationalOperationElement)[],\n table: QueryTarget,\n op: RelationalOperationElement = new NoOperation(),\n): FinderResult {\n return new FinderResult(\n convertDate(businessDate),\n convertProcessingDate(processingDatetime),\n columns,\n table,\n op,\n );\n}\n\nexport function convertInputsAndSelectForDateRange(\n businessDateFrom: Date | string,\n businessDateTo: Date | string,\n processingDatetime: Date | string,\n columns: (Attribute | RelationalOperationElement)[],\n table: QueryTarget,\n op: RelationalOperationElement = new NoOperation(),\n): FinderResult {\n if (businessDateFrom == null) throw new Error('businessDateFrom is required for findForDateRange');\n if (businessDateTo == null) throw new Error('businessDateTo is required for findForDateRange');\n if (processingDatetime == null) throw new Error('processingValidAt is required for findForDateRange');\n return new FinderResult(\n convertDate(businessDateFrom),\n convertProcessingDate(processingDatetime),\n columns,\n table,\n op,\n convertDate(businessDateTo),\n );\n}\n","/**\n * Runs a query on a Databricks SQL warehouse through the SQL Statement Execution REST API\n * (`/api/2.0/sql/statements`), which is plain HTTPS and so works from a browser as well as Node.\n *\n * A browser cannot call a Databricks workspace directly, as the workspace does not send CORS headers, so\n * `host` is usually a server of your own that forwards `/api/2.0/sql/…` to the workspace (and may add the\n * credentials, in which case no `token` is needed here).\n */\nimport { Attribute } from './attribute';\nimport { DEFAULT_TIMEOUT_MS, QueryRunner, QueryTarget, QueryTimeoutError, Row } from './runner';\nimport { toSql } from './sql-generator';\nimport {\n DateOnly,\n Operation,\n RelationalOperationElement,\n SortOperation,\n Table,\n} from '../model/relational';\n\nexport interface DatabricksConfig {\n /** The workspace URL, or a server that forwards the Statement Execution API to it. No trailing path. */\n host: string;\n /** The SQL warehouse that runs the statements. */\n warehouseId: string;\n /** Sent as the bearer token. A function is called for every request, so a token can be refreshed. */\n token?: string | (() => string | Promise<string>);\n /** The catalog and schema unqualified table names resolve in. */\n catalog?: string;\n schema?: string;\n /** Extra request headers, for a gateway in front of the workspace. */\n headers?: Record<string, string>;\n /** `fetch`, if not the global one. */\n fetch?: typeof fetch;\n /** How long to wait before first asking again whether a statement has finished (it backs off from there). */\n pollIntervalMs?: number;\n}\n\n/** A statement Databricks ran and failed, or the API refused. */\nexport class DatabricksQueryError extends Error {\n constructor(message: string, readonly code?: string, readonly statementId?: string) {\n super(message);\n this.name = 'DatabricksQueryError';\n }\n}\n\ninterface ColumnInfo { name: string; type_name?: string; type_text?: string }\n\n/** A chunk of rows, as the statement itself carries the first and the chunks endpoint the rest. */\ninterface ResultData { data_array?: (string | null)[][]; next_chunk_index?: number }\n\ninterface StatementResponse {\n statement_id: string;\n status: { state: string; error?: { error_code?: string; message?: string } };\n manifest?: { schema?: { columns?: ColumnInfo[] } };\n result?: ResultData;\n}\n\nconst API = '/api/2.0/sql/statements';\nconst MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);\n\n/** A value as Databricks sends it (text, or null) as the JavaScript value for its column type. */\nexport function convertValue(text: string | null, typeName: string | undefined): unknown {\n if (text === null || text === undefined) return null;\n switch ((typeName ?? '').toUpperCase()) {\n case 'BYTE': case 'SHORT': case 'INT': return Number(text);\n case 'LONG': {\n const value = BigInt(text);\n return value >= -MAX_SAFE && value <= MAX_SAFE ? Number(value) : value; // exact when it cannot be a number\n }\n case 'FLOAT': case 'DOUBLE': case 'DECIMAL': return Number(text);\n case 'BOOLEAN': return text.toLowerCase() === 'true';\n case 'DATE': return new DateOnly(text + 'T00:00:00Z');\n case 'TIMESTAMP': case 'TIMESTAMP_NTZ': {\n const zoned = /(Z|[+-]\\d{2}:?\\d{2})$/.test(text);\n return new Date(zoned ? text : text.replace(' ', 'T') + 'Z');\n }\n default: return text; // STRING, and anything structured (ARRAY, MAP, STRUCT, BINARY, INTERVAL) as the text sent\n }\n}\n\nconst sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));\n\nexport class DatabricksConnect implements QueryRunner {\n readonly dialect = 'databricks' as const;\n\n /** Names of the columns of the last query that returned. */\n lastColumns: string[] = [];\n\n constructor(private readonly config: DatabricksConfig) {\n if (!config.host) throw new Error('DatabricksConnect needs the host of a workspace, or of a server in front of it');\n if (!config.warehouseId) throw new Error('DatabricksConnect needs the id of a SQL warehouse');\n }\n\n async select(\n businessDate: Date | null,\n processingDatetime: Date | null,\n columns: (Attribute | RelationalOperationElement)[],\n table: QueryTarget,\n op: RelationalOperationElement,\n orderBy?: SortOperation[],\n groupBy?: Attribute[],\n limit?: number,\n timeoutMs: number = DEFAULT_TIMEOUT_MS,\n businessDateTo: Date | null = null,\n distinct: boolean = false,\n offset?: number,\n having?: Operation,\n ): Promise<Row[]> {\n const statement = toSql(\n businessDate, processingDatetime, columns, table as Table, op, orderBy, groupBy, limit,\n businessDateTo, distinct, offset, having, this.dialect,\n );\n const deadline = Date.now() + timeoutMs;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n let statementId: string | undefined;\n try {\n let response = await this.call('POST', `${API}/`, controller.signal, {\n warehouse_id: this.config.warehouseId,\n statement,\n // the API holds the request for up to 50 s and answers at once if the statement is quicker; a shorter\n // wait than 5 s is not allowed except 0, so poll\n wait_timeout: timeoutMs >= 5000 ? `${Math.min(50, Math.floor(timeoutMs / 1000))}s` : '0s',\n on_wait_timeout: 'CONTINUE',\n disposition: 'INLINE',\n format: 'JSON_ARRAY',\n ...(this.config.catalog ? { catalog: this.config.catalog } : {}),\n ...(this.config.schema ? { schema: this.config.schema } : {}),\n });\n statementId = response.statement_id;\n\n let delay = this.config.pollIntervalMs ?? 250;\n while (response.status.state === 'PENDING' || response.status.state === 'RUNNING') {\n if (Date.now() >= deadline) throw new QueryTimeoutError(timeoutMs);\n await sleep(Math.min(delay, Math.max(0, deadline - Date.now())));\n delay = Math.min(delay * 2, 2000);\n response = await this.call('GET', `${API}/${statementId}`, controller.signal);\n }\n\n if (response.status.state !== 'SUCCEEDED') {\n const error = response.status.error;\n throw new DatabricksQueryError(\n error?.message ?? `The statement ${response.status.state.toLowerCase()}`, error?.error_code, statementId);\n }\n return await this.rows(response, controller.signal);\n } catch (e) {\n const timedOut = controller.signal.aborted || e instanceof QueryTimeoutError;\n if (timedOut && statementId !== undefined) await this.cancel(statementId);\n if (controller.signal.aborted) throw new QueryTimeoutError(timeoutMs);\n throw e;\n } finally {\n clearTimeout(timer);\n }\n }\n\n /** The rows of a finished statement, following its chunks. */\n private async rows(first: StatementResponse, signal: AbortSignal): Promise<Row[]> {\n const info = first.manifest?.schema?.columns ?? [];\n this.lastColumns = info.map(c => c.name);\n const rows: Row[] = [];\n const take = (data: (string | null)[][] | undefined) => {\n for (const row of data ?? []) rows.push(row.map((text, i) => convertValue(text, info[i]?.type_name)));\n };\n take(first.result?.data_array);\n let next = first.result?.next_chunk_index;\n while (next !== undefined && next !== null) {\n const chunk = await this.call<ResultData>('GET', `${API}/${first.statement_id}/result/chunks/${next}`, signal);\n take(chunk.data_array);\n next = chunk.next_chunk_index;\n }\n return rows;\n }\n\n /** Ask Databricks to stop a statement. Best effort: the query is already given up on. */\n private async cancel(statementId: string): Promise<void> {\n try {\n await this.call('POST', `${API}/${statementId}/cancel`, undefined, {});\n } catch {\n // nothing more can be done about it\n }\n }\n\n private async call<T = StatementResponse>(method: 'GET' | 'POST', path: string, signal: AbortSignal | undefined, body?: object): Promise<T> {\n const { host, token, headers, fetch: custom } = this.config;\n const bearer = typeof token === 'function' ? await token() : token;\n const response = await (custom ?? fetch)(host.replace(/\\/+$/, '') + path, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...(bearer ? { Authorization: `Bearer ${bearer}` } : {}),\n ...headers,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal,\n });\n const text = await response.text();\n let parsed: unknown;\n try { parsed = text ? JSON.parse(text) : {}; } catch { parsed = undefined; }\n if (!response.ok) {\n const detail = parsed as { error_code?: string; message?: string } | undefined;\n throw new DatabricksQueryError(\n detail?.message ?? `Databricks request failed: ${response.status} ${response.statusText}`, detail?.error_code);\n }\n return parsed as T;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAK,qBAAL,kBAAKA,wBAAL;AACL,EAAAA,oBAAA,WAAQ;AACR,EAAAA,oBAAA,eAAY;AACZ,EAAAA,oBAAA,eAAY;AACZ,EAAAA,oBAAA,kBAAe;AACf,EAAAA,oBAAA,2BAAwB;AACxB,EAAAA,oBAAA,8BAA2B;AAC3B,EAAAA,oBAAA,UAAO;AACP,EAAAA,oBAAA,cAAW;AARD,SAAAA;AAAA,GAAA;AAYL,IAAM,cAAc;AAMpB,SAAS,WAAWC,QAAuB;AAChD,SAAOA,OAAM,WAAW,aAAa,cAAc,WAAW,EAAE,WAAW,KAAK,cAAc,GAAG,EAAE,WAAW,KAA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WAAW,QAAW,CAAC,CAAC;AAAA,IACvE,QAAQ;AAAA,IAER;AAAA,EACF;AAAA,EAEA,MAAc,KAA4B,QAAwB,MAAc,QAAiC,MAA2B;AAC1I,UAAM,EAAE,MAAM,OAAO,SAAS,OAAO,OAAO,IAAI,KAAK;AACrD,UAAM,SAAS,OAAO,UAAU,aAAa,MAAM,MAAM,IAAI;AAC7D,UAAM,WAAW,OAAO,UAAU,OAAO,KAAK,QAAQ,QAAQ,EAAE,IAAI,MAAM;AAAA,MACxE;AAAA,MACA,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,GAAI,SAAS,EAAE,eAAe,UAAU,MAAM,GAAG,IAAI,CAAC;AAAA,QACtD,GAAG;AAAA,MACL;AAAA,MACA,MAAM,SAAS,SAAY,SAAY,KAAK,UAAU,IAAI;AAAA,MAC1D;AAAA,IACF,CAAC;AACD,UAAM,OAAO,MAAM,SAAS,KAAK;AACjC,QAAI;AACJ,QAAI;AAAE,eAAS,OAAO,KAAK,MAAM,IAAI,IAAI,CAAC;AAAA,IAAG,QAAQ;AAAE,eAAS;AAAA,IAAW;AAC3E,QAAI,CAAC,SAAS,IAAI;AAChB,YAAM,SAAS;AACf,YAAM,IAAI;AAAA,QACR,QAAQ,WAAW,8BAA8B,SAAS,MAAM,IAAI,SAAS,UAAU;AAAA,QAAI,QAAQ;AAAA,MAAU;AAAA,IACjH;AACA,WAAO;AAAA,EACT;AACF;","names":["ComparisonOperator","value","LogicalOperator","AggregateOperator","ScalarFunction","DatePart","SortDirection","WindowFunction","ArithmeticOperator","value","value","value","value","constant","value","value","value"]}