data-finder-ts 0.1.0 → 0.1.4

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 (64) hide show
  1. package/README.md +17 -55
  2. package/dist/chunk-4JVW4TAB.js +180 -0
  3. package/dist/chunk-4JVW4TAB.js.map +1 -0
  4. package/dist/chunk-4LNZV6EN.js +500 -0
  5. package/dist/chunk-4LNZV6EN.js.map +1 -0
  6. package/dist/chunk-FJYA2ASS.js +136 -0
  7. package/dist/chunk-FJYA2ASS.js.map +1 -0
  8. package/dist/chunk-FLEIUDZZ.js +14 -0
  9. package/dist/chunk-FLEIUDZZ.js.map +1 -0
  10. package/dist/chunk-MH4XMYVB.js +696 -0
  11. package/dist/chunk-MH4XMYVB.js.map +1 -0
  12. package/dist/chunk-PMPLCEWQ.js +90 -0
  13. package/dist/chunk-PMPLCEWQ.js.map +1 -0
  14. package/dist/chunk-UYMOE6YU.js +509 -0
  15. package/dist/chunk-UYMOE6YU.js.map +1 -0
  16. package/dist/datafinder/attribute.cjs +320 -0
  17. package/dist/datafinder/attribute.cjs.map +1 -0
  18. package/dist/datafinder/attribute.d.cts +86 -0
  19. package/dist/datafinder/attribute.d.ts +86 -0
  20. package/dist/datafinder/attribute.js +8 -0
  21. package/dist/datafinder/attribute.js.map +1 -0
  22. package/dist/datafinder/finder-registry.cjs +39 -0
  23. package/dist/datafinder/finder-registry.cjs.map +1 -0
  24. package/dist/datafinder/finder-registry.d.cts +4 -0
  25. package/dist/datafinder/finder-registry.d.ts +4 -0
  26. package/dist/datafinder/finder-registry.js +9 -0
  27. package/dist/datafinder/finder-registry.js.map +1 -0
  28. package/dist/datafinder/runner.cjs +1595 -0
  29. package/dist/datafinder/runner.cjs.map +1 -0
  30. package/dist/datafinder/runner.d.cts +44 -0
  31. package/dist/datafinder/runner.d.ts +44 -0
  32. package/dist/datafinder/runner.js +26 -0
  33. package/dist/datafinder/runner.js.map +1 -0
  34. package/dist/datafinder/sql-generator.cjs +1467 -0
  35. package/dist/datafinder/sql-generator.cjs.map +1 -0
  36. package/dist/datafinder/sql-generator.d.cts +8 -0
  37. package/dist/datafinder/sql-generator.d.ts +8 -0
  38. package/dist/datafinder/sql-generator.js +15 -0
  39. package/dist/datafinder/sql-generator.js.map +1 -0
  40. package/dist/datafinder/typed-attributes.cjs +909 -0
  41. package/dist/datafinder/typed-attributes.cjs.map +1 -0
  42. package/dist/datafinder/typed-attributes.d.cts +242 -0
  43. package/dist/datafinder/typed-attributes.d.ts +242 -0
  44. package/dist/datafinder/typed-attributes.js +25 -0
  45. package/dist/datafinder/typed-attributes.js.map +1 -0
  46. package/dist/index.cjs +2153 -0
  47. package/dist/index.cjs.map +1 -0
  48. package/dist/index.d.cts +28 -0
  49. package/dist/index.d.ts +28 -0
  50. package/dist/index.js +199 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/model/milestoning.cjs +145 -0
  53. package/dist/model/milestoning.cjs.map +1 -0
  54. package/dist/model/milestoning.d.cts +40 -0
  55. package/dist/model/milestoning.d.ts +40 -0
  56. package/dist/model/milestoning.js +18 -0
  57. package/dist/model/milestoning.js.map +1 -0
  58. package/dist/model/relational.cjs +579 -0
  59. package/dist/model/relational.cjs.map +1 -0
  60. package/dist/model/relational.d.cts +291 -0
  61. package/dist/model/relational.d.ts +291 -0
  62. package/dist/model/relational.js +99 -0
  63. package/dist/model/relational.js.map +1 -0
  64. package/package.json +6 -4
@@ -0,0 +1,696 @@
1
+ import {
2
+ BiTemporalColumns,
3
+ BusinessDateAndProcessingTemporalColumns,
4
+ MilestonedTable,
5
+ ProcessingTemporalColumns,
6
+ SingleBusinessDateColumn
7
+ } from "./chunk-PMPLCEWQ.js";
8
+ import {
9
+ DateAttribute,
10
+ DateTimeAttribute
11
+ } from "./chunk-4LNZV6EN.js";
12
+ import {
13
+ Attribute
14
+ } from "./chunk-4JVW4TAB.js";
15
+ import {
16
+ AggregateOperation,
17
+ Alias,
18
+ BooleanConstantOperation,
19
+ Column,
20
+ ColumnWithJoin,
21
+ ComparisonOperation,
22
+ ConstantOperation,
23
+ CountAllOperation,
24
+ DateArithmeticOperation,
25
+ DateConstantOperation,
26
+ DateDiffOperation,
27
+ DateExtractOperation,
28
+ DateTimeConstantOperation,
29
+ DecimalConstantOperation,
30
+ ExistsOperation,
31
+ FloatConstantOperation,
32
+ IntegerConstantOperation,
33
+ IsNotNullOperation,
34
+ IsNullOperation,
35
+ LogicalOperation,
36
+ NoOperation,
37
+ NotExistsOperation,
38
+ RelationalOperationElement,
39
+ ScalarFunctionOperation,
40
+ SelectOperation,
41
+ SortOperation,
42
+ StringConstantOperation,
43
+ UnaryOperation,
44
+ WindowFunctionOperation,
45
+ WindowSpecification
46
+ } from "./chunk-UYMOE6YU.js";
47
+
48
+ // src/datafinder/sql-generator.ts
49
+ var TableAlias = class {
50
+ constructor(table, alias) {
51
+ this.table = table;
52
+ this.alias = alias;
53
+ }
54
+ table;
55
+ alias;
56
+ };
57
+ var TableAliasColumn = class extends RelationalOperationElement {
58
+ constructor(column, tableAlias) {
59
+ super();
60
+ this.column = column;
61
+ this.tableAlias = tableAlias;
62
+ }
63
+ column;
64
+ tableAlias;
65
+ };
66
+ var Join = class {
67
+ constructor(source, target, filterOp) {
68
+ this.source = source;
69
+ this.target = target;
70
+ this.filterOp = filterOp;
71
+ }
72
+ source;
73
+ target;
74
+ filterOp;
75
+ };
76
+ function sqlFormatDatetime(value) {
77
+ const pad = (n, w = 2) => String(n).padStart(w, "0");
78
+ return `'${value.getUTCFullYear()}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())} ${pad(value.getUTCHours())}:${pad(value.getUTCMinutes())}:${pad(value.getUTCSeconds())}'`;
79
+ }
80
+ function sqlFormatDate(value) {
81
+ const pad = (n) => String(n).padStart(2, "0");
82
+ return `'${value.getUTCFullYear()}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())}'`;
83
+ }
84
+ var LOGICAL_OPERATOR_STR = {
85
+ ["AND" /* AND */]: " AND ",
86
+ ["OR" /* OR */]: " OR "
87
+ };
88
+ var COMPARISON_OPERATOR_STR = {
89
+ ["EQUAL" /* EQUAL */]: " = ",
90
+ ["NOT_EQUAL" /* NOT_EQUAL */]: " <> ",
91
+ ["LESS_THAN" /* LESS_THAN */]: " < ",
92
+ ["GREATER_THAN" /* GREATER_THAN */]: " > ",
93
+ ["LESS_THAN_OR_EQUAL_TO" /* LESS_THAN_OR_EQUAL_TO */]: " <= ",
94
+ ["GREATER_THAN_OR_EQUAL_TO" /* GREATER_THAN_OR_EQUAL_TO */]: " >= ",
95
+ ["LIKE" /* LIKE */]: " LIKE ",
96
+ ["NOT_LIKE" /* NOT_LIKE */]: " NOT LIKE "
97
+ };
98
+ var AGGREGATE_SQL_NAMES = {
99
+ ["AVERAGE" /* AVERAGE */]: "AVG"
100
+ };
101
+ var WINDOW_SQL_NAMES = {
102
+ ["ROW_NUMBER" /* ROW_NUMBER */]: "ROW_NUMBER",
103
+ ["RANK" /* RANK */]: "RANK",
104
+ ["DENSE_RANK" /* DENSE_RANK */]: "DENSE_RANK",
105
+ ["NTILE" /* NTILE */]: "NTILE",
106
+ ["LAG" /* LAG */]: "LAG",
107
+ ["LEAD" /* LEAD */]: "LEAD",
108
+ ["FIRST_VALUE" /* FIRST_VALUE */]: "FIRST_VALUE",
109
+ ["LAST_VALUE" /* LAST_VALUE */]: "LAST_VALUE",
110
+ ["CUME_DIST" /* CUME_DIST */]: "CUME_DIST",
111
+ ["PERCENT_RANK" /* PERCENT_RANK */]: "PERCENT_RANK"
112
+ };
113
+ var SCALAR_SQL_NAMES = {
114
+ ["ABS" /* ABS */]: "ABS",
115
+ ["CEILING" /* CEILING */]: "CEILING",
116
+ ["FLOOR" /* FLOOR */]: "FLOOR",
117
+ ["MOD" /* MOD */]: "MOD",
118
+ ["POWER" /* POWER */]: "POWER",
119
+ ["SQRT" /* SQRT */]: "SQRT",
120
+ ["ROUND" /* ROUND */]: "ROUND",
121
+ ["UPPER" /* UPPER */]: "UPPER",
122
+ ["LOWER" /* LOWER */]: "LOWER",
123
+ ["TRIM" /* TRIM */]: "TRIM",
124
+ ["LTRIM" /* LTRIM */]: "LTRIM",
125
+ ["RTRIM" /* RTRIM */]: "RTRIM",
126
+ ["LENGTH" /* LENGTH */]: "LENGTH",
127
+ ["REVERSE" /* REVERSE */]: "REVERSE",
128
+ ["LEFT" /* LEFT */]: "LEFT",
129
+ ["RIGHT" /* RIGHT */]: "RIGHT",
130
+ ["REPEAT" /* REPEAT */]: "REPEAT",
131
+ ["REPLACE" /* REPLACE */]: "REPLACE",
132
+ ["SUBSTRING" /* SUBSTRING */]: "SUBSTRING"
133
+ };
134
+ function constantValueString(op) {
135
+ if (op instanceof StringConstantOperation) return "'" + op.value + "'";
136
+ if (op instanceof DateConstantOperation) return sqlFormatDate(op.value);
137
+ if (op instanceof DateTimeConstantOperation) return sqlFormatDatetime(op.value);
138
+ if (op instanceof IntegerConstantOperation) return String(op.value);
139
+ if (op instanceof FloatConstantOperation) return String(op.value);
140
+ if (op instanceof BooleanConstantOperation) return op.value ? "TRUE" : "FALSE";
141
+ if (op instanceof DecimalConstantOperation) return String(op.value);
142
+ throw new Error("Unknown constant operation");
143
+ }
144
+ function windowSpecToString(window) {
145
+ const parts = [];
146
+ if (window.partitionBy.length > 0) {
147
+ parts.push("PARTITION BY " + window.partitionBy.map((p) => sqlOperationToString(p)).join(", "));
148
+ }
149
+ if (window.orderBy.length > 0) {
150
+ parts.push("ORDER BY " + window.orderBy.map(
151
+ (s) => sqlOperationToString(s.column) + (s.direction === "ASC" /* ASC */ ? " ASC" : " DESC")
152
+ ).join(", "));
153
+ }
154
+ return "OVER (" + parts.join(" ") + ")";
155
+ }
156
+ function sqlOperationToString(operation) {
157
+ if (operation instanceof TableAliasColumn) {
158
+ return operation.tableAlias.alias + "." + operation.column.name;
159
+ }
160
+ if (operation instanceof WindowFunctionOperation) {
161
+ const fn = WINDOW_SQL_NAMES[operation.func];
162
+ const parts = [];
163
+ if (operation.element !== null && operation.element !== void 0) {
164
+ parts.push(sqlOperationToString(operation.element));
165
+ }
166
+ if (operation.secondArg !== void 0) parts.push(String(operation.secondArg));
167
+ for (const arg of operation.extraArgs) {
168
+ parts.push(typeof arg === "string" ? "'" + arg + "'" : String(arg));
169
+ }
170
+ const sql = fn + "(" + parts.join(", ") + ")";
171
+ return sql + (operation.window !== void 0 ? " " + windowSpecToString(operation.window) : " OVER ()");
172
+ }
173
+ if (operation instanceof AggregateOperation) {
174
+ const fn = AGGREGATE_SQL_NAMES[operation.operator] ?? operation.operator;
175
+ let sql = fn + "(" + sqlOperationToString(operation.element) + ")";
176
+ if (operation.window !== void 0) {
177
+ sql += " " + windowSpecToString(operation.window);
178
+ }
179
+ return sql;
180
+ }
181
+ if (operation instanceof ScalarFunctionOperation) {
182
+ const fn = SCALAR_SQL_NAMES[operation.func];
183
+ const parts = [sqlOperationToString(operation.element)];
184
+ if (operation.secondArg !== void 0) parts.push(String(operation.secondArg));
185
+ for (const arg of operation.extraArgs) {
186
+ parts.push(typeof arg === "string" ? "'" + arg + "'" : String(arg));
187
+ }
188
+ return fn + "(" + parts.join(", ") + ")";
189
+ }
190
+ if (operation instanceof DateExtractOperation) {
191
+ return "EXTRACT(" + operation.part + " FROM " + sqlOperationToString(operation.element) + ")";
192
+ }
193
+ if (operation instanceof DateArithmeticOperation) {
194
+ const op = operation.isAdd ? "+" : "-";
195
+ return sqlOperationToString(operation.element) + " " + op + " INTERVAL " + operation.n + " " + operation.unit;
196
+ }
197
+ if (operation instanceof DateDiffOperation) {
198
+ const otherSql = sqlFormatDatetime(operation.other);
199
+ return "DATE_DIFF('" + operation.unit.toLowerCase() + "', " + sqlOperationToString(operation.element) + ", " + otherSql + ")";
200
+ }
201
+ if (operation instanceof CountAllOperation) return "COUNT(*)";
202
+ if (operation instanceof Alias) {
203
+ return sqlOperationToString(operation.element) + ' AS "' + operation.name + '"';
204
+ }
205
+ throw new TypeError("Unknown operation in sqlOperationToString: " + operation.constructor.name);
206
+ }
207
+ function embeddedOf(ref) {
208
+ return ref instanceof Attribute ? ref.embedded() : ref.embedded;
209
+ }
210
+ function findColumn(operation) {
211
+ if (operation instanceof UnaryOperation) return findColumn(operation.element);
212
+ if (operation instanceof ColumnWithJoin) return operation;
213
+ throw new TypeError("Cannot find ColumnWithJoin in: " + operation.constructor.name);
214
+ }
215
+ function openEndClause(endAttr, value, infiniteDatetime) {
216
+ const gtOp = endAttr instanceof DateTimeAttribute ? endAttr.gt(value) : endAttr.gt(value);
217
+ if (infiniteDatetime === void 0) {
218
+ const colRef = new ColumnWithJoin(endAttr.column(), endAttr.parent());
219
+ return new LogicalOperation(gtOp, "OR" /* OR */, new IsNullOperation(colRef));
220
+ }
221
+ return gtOp;
222
+ }
223
+ function buildMilestoningFilterOperation(businessDate, processingDatetime, table, joinNode) {
224
+ const mc = table.milestoningColumns;
225
+ const ops = [];
226
+ if (mc instanceof BiTemporalColumns) {
227
+ if (businessDate !== null) {
228
+ const dateFrom = new DateAttribute("business_date_from", mc.businessDateFromColumn.name, mc.businessDateFromColumn.type, mc.businessDateFromColumn.table.qualifiedName, joinNode);
229
+ const dateTo = new DateAttribute("business_date_to", mc.businessDateToColumn.name, mc.businessDateToColumn.type, mc.businessDateToColumn.table.qualifiedName, joinNode);
230
+ ops.push(new LogicalOperation(dateFrom.lte(businessDate), "AND" /* AND */, openEndClause(dateTo, businessDate, mc.infiniteDatetime)));
231
+ }
232
+ if (processingDatetime !== null) {
233
+ const startAt = new DateTimeAttribute("start_at", mc.startAtColumn.name, mc.startAtColumn.type, mc.startAtColumn.table.qualifiedName, joinNode);
234
+ const endAt = new DateTimeAttribute("end_at", mc.endAtColumn.name, mc.endAtColumn.type, mc.endAtColumn.table.qualifiedName, joinNode);
235
+ ops.push(new LogicalOperation(startAt.lte(processingDatetime), "AND" /* AND */, openEndClause(endAt, processingDatetime, mc.infiniteDatetime)));
236
+ }
237
+ } else if (mc instanceof BusinessDateAndProcessingTemporalColumns) {
238
+ if (businessDate !== null) {
239
+ const businessAtt = new DateAttribute("business_date", mc.businessDateColumn.name, mc.businessDateColumn.type, mc.businessDateColumn.table.qualifiedName, joinNode);
240
+ ops.push(businessAtt.eq(businessDate));
241
+ }
242
+ if (processingDatetime !== null) {
243
+ const startAt = new DateTimeAttribute("start_at", mc.startAtColumn.name, mc.startAtColumn.type, mc.startAtColumn.table.qualifiedName, joinNode);
244
+ const endAt = new DateTimeAttribute("end_at", mc.endAtColumn.name, mc.endAtColumn.type, mc.endAtColumn.table.qualifiedName, joinNode);
245
+ ops.push(new LogicalOperation(startAt.lte(processingDatetime), "AND" /* AND */, openEndClause(endAt, processingDatetime, mc.infiniteDatetime)));
246
+ }
247
+ } else if (mc instanceof ProcessingTemporalColumns && processingDatetime !== null) {
248
+ const startAt = new DateTimeAttribute("start_at", mc.startAtColumn.name, mc.startAtColumn.type, mc.startAtColumn.table.qualifiedName, joinNode);
249
+ const endAt = new DateTimeAttribute("end_at", mc.endAtColumn.name, mc.endAtColumn.type, mc.endAtColumn.table.qualifiedName, joinNode);
250
+ ops.push(new LogicalOperation(startAt.lte(processingDatetime), "AND" /* AND */, openEndClause(endAt, processingDatetime, mc.infiniteDatetime)));
251
+ } else if (mc instanceof SingleBusinessDateColumn && businessDate !== null) {
252
+ const businessAtt = new DateAttribute("business_date", mc.businessDateColumn.name, mc.businessDateColumn.type, mc.businessDateColumn.table.qualifiedName, joinNode);
253
+ ops.push(businessAtt.eq(businessDate));
254
+ }
255
+ if (ops.length === 0) return null;
256
+ if (ops.length === 1) return ops[0];
257
+ return new LogicalOperation(ops[0], "AND" /* AND */, ops[1]);
258
+ }
259
+ function buildMilestoningFilterOperationForDateRange(businessDateFrom, businessDateTo, processingDatetime, table, joinNode) {
260
+ const mc = table.milestoningColumns;
261
+ const ops = [];
262
+ const hasRange = businessDateFrom !== null && businessDateTo !== null;
263
+ const processingOp = (m) => {
264
+ const startAt = new DateTimeAttribute("start_at", m.startAtColumn.name, m.startAtColumn.type, m.startAtColumn.table.qualifiedName, joinNode);
265
+ const endAt = new DateTimeAttribute("end_at", m.endAtColumn.name, m.endAtColumn.type, m.endAtColumn.table.qualifiedName, joinNode);
266
+ return new LogicalOperation(startAt.lte(processingDatetime), "AND" /* AND */, openEndClause(endAt, processingDatetime, m.infiniteDatetime));
267
+ };
268
+ if (mc instanceof BiTemporalColumns) {
269
+ if (hasRange) {
270
+ const dateFrom = new DateAttribute("business_date_from", mc.businessDateFromColumn.name, mc.businessDateFromColumn.type, mc.businessDateFromColumn.table.qualifiedName, joinNode);
271
+ const dateTo = new DateAttribute("business_date_to", mc.businessDateToColumn.name, mc.businessDateToColumn.type, mc.businessDateToColumn.table.qualifiedName, joinNode);
272
+ ops.push(new LogicalOperation(dateFrom.lte(businessDateTo), "AND" /* AND */, openEndClause(dateTo, businessDateFrom, mc.infiniteDatetime)));
273
+ }
274
+ if (processingDatetime !== null) ops.push(processingOp(mc));
275
+ } else if (mc instanceof BusinessDateAndProcessingTemporalColumns) {
276
+ if (hasRange) {
277
+ const businessAtt = new DateAttribute("business_date", mc.businessDateColumn.name, mc.businessDateColumn.type, mc.businessDateColumn.table.qualifiedName, joinNode);
278
+ ops.push(new LogicalOperation(businessAtt.gte(businessDateFrom), "AND" /* AND */, businessAtt.lte(businessDateTo)));
279
+ }
280
+ if (processingDatetime !== null) ops.push(processingOp(mc));
281
+ } else if (mc instanceof ProcessingTemporalColumns) {
282
+ if (processingDatetime !== null) ops.push(processingOp(mc));
283
+ } else if (mc instanceof SingleBusinessDateColumn && hasRange) {
284
+ const businessAtt = new DateAttribute("business_date", mc.businessDateColumn.name, mc.businessDateColumn.type, mc.businessDateColumn.table.qualifiedName, joinNode);
285
+ ops.push(new LogicalOperation(businessAtt.gte(businessDateFrom), "AND" /* AND */, businessAtt.lte(businessDateTo)));
286
+ }
287
+ if (ops.length === 0) return null;
288
+ if (ops.length === 1) return ops[0];
289
+ return new LogicalOperation(ops[0], "AND" /* AND */, ops[1]);
290
+ }
291
+ function walkRefs(op, visit, visitExists) {
292
+ if (op === null || op === void 0) return;
293
+ if (op instanceof Attribute || op instanceof ColumnWithJoin) {
294
+ visit(op);
295
+ } else if (op instanceof ExistsOperation || op instanceof NotExistsOperation) {
296
+ visitExists?.(op.node);
297
+ } else if (op instanceof AggregateOperation) {
298
+ walkRefs(op.element, visit, visitExists);
299
+ if (op.window) walkWindowSpec(op.window, visit, visitExists);
300
+ } else if (op instanceof WindowFunctionOperation) {
301
+ if (op.element) walkRefs(op.element, visit, visitExists);
302
+ if (op.window) walkWindowSpec(op.window, visit, visitExists);
303
+ } else if (op instanceof ScalarFunctionOperation || op instanceof DateExtractOperation || op instanceof DateArithmeticOperation || op instanceof DateDiffOperation || op instanceof IsNullOperation || op instanceof IsNotNullOperation) {
304
+ walkRefs(op.element, visit, visitExists);
305
+ } else if (op instanceof SortOperation) {
306
+ walkRefs(op.column, visit, visitExists);
307
+ } else if (op instanceof LogicalOperation || op instanceof ComparisonOperation) {
308
+ walkRefs(op.left, visit, visitExists);
309
+ walkRefs(op.right, visit, visitExists);
310
+ }
311
+ }
312
+ function walkWindowSpec(window, visit, visitExists) {
313
+ for (const p of window.partitionBy) walkRefs(p, visit, visitExists);
314
+ for (const s of window.orderBy) walkRefs(s.column, visit, visitExists);
315
+ }
316
+ function buildJoinFilterFromProperties(node, filter, columnMap) {
317
+ const ops = [];
318
+ for (const [key, value] of Object.entries(filter)) {
319
+ const entry = columnMap[key];
320
+ if (entry === void 0) {
321
+ throw new Error(`Unknown property '${key}' \u2014 valid properties are: ${Object.keys(columnMap).sort().join(", ")}`);
322
+ }
323
+ const [name, type, table] = entry;
324
+ const col = new ColumnWithJoin(new Column(name, type, table), node);
325
+ let constant;
326
+ if (typeof value === "boolean") constant = new BooleanConstantOperation(value);
327
+ else if (typeof value === "number") constant = Number.isInteger(value) ? new IntegerConstantOperation(value) : new FloatConstantOperation(value);
328
+ else if (value instanceof Date) constant = type.toUpperCase() === "DATE" ? new DateConstantOperation(value) : new DateTimeConstantOperation(value);
329
+ else constant = new StringConstantOperation(String(value));
330
+ ops.push(new ComparisonOperation(col, "EQUAL" /* EQUAL */, constant));
331
+ }
332
+ return ops.reduce((acc, op) => new LogicalOperation(acc, "AND" /* AND */, op));
333
+ }
334
+ function withAncestors(nodes) {
335
+ const ordered = /* @__PURE__ */ new Set();
336
+ const add = (node) => {
337
+ if (ordered.has(node)) return;
338
+ if (node.parent !== void 0) add(node.parent);
339
+ ordered.add(node);
340
+ };
341
+ for (const node of nodes) add(node);
342
+ return [...ordered];
343
+ }
344
+ function buildQueryOperation(businessDate, processingDatetime, columns, table, op, orderBy = [], groupBy = [], limit, businessDateTo = null) {
345
+ let filter = op;
346
+ const milestoningFor = (t, node) => businessDateTo !== null ? buildMilestoningFilterOperationForDateRange(businessDate, businessDateTo, processingDatetime, t, node) : buildMilestoningFilterOperation(businessDate, processingDatetime, t, node);
347
+ if (table instanceof MilestonedTable) {
348
+ const milestonedOp = milestoningFor(table);
349
+ if (milestonedOp !== null) {
350
+ filter = filter instanceof NoOperation ? milestonedOp : new LogicalOperation(filter, "AND" /* AND */, milestonedOp);
351
+ }
352
+ }
353
+ const requiredJoins = /* @__PURE__ */ new Set();
354
+ const collect = (ref) => {
355
+ const parent = ref instanceof Attribute ? ref.parent() : ref.parent;
356
+ if (parent !== void 0) requiredJoins.add(parent);
357
+ };
358
+ const collectNode = (node) => requiredJoins.add(node);
359
+ for (const col of columns) walkRefs(col, collect, collectNode);
360
+ for (const expr of groupBy) walkRefs(expr, collect, collectNode);
361
+ for (const sort of orderBy) walkRefs(sort, collect, collectNode);
362
+ walkRefs(op, collect, collectNode);
363
+ const joinFilters = /* @__PURE__ */ new Map();
364
+ for (const node of withAncestors(requiredJoins)) {
365
+ let combined;
366
+ if (Object.keys(node.join.filterKwargs).length > 0) {
367
+ combined = buildJoinFilterFromProperties(node, node.join.filterKwargs, node.join.filterColumnMap);
368
+ }
369
+ if (node.join.target instanceof MilestonedTable) {
370
+ const milestonedOp = milestoningFor(node.join.target, node);
371
+ if (milestonedOp !== null) {
372
+ combined = combined === void 0 ? milestonedOp : new LogicalOperation(combined, "AND" /* AND */, milestonedOp);
373
+ }
374
+ }
375
+ if (combined !== void 0) joinFilters.set(node, combined);
376
+ }
377
+ return new SelectOperation(columns, filter, orderBy, groupBy, limit, table, joinFilters);
378
+ }
379
+ var SQLQueryGenerator = class {
380
+ _select = [];
381
+ _from = /* @__PURE__ */ new Set();
382
+ _join = [];
383
+ _groupByParts = [];
384
+ _orderByParts = [];
385
+ _where = "";
386
+ _limit;
387
+ _tableAliasIncr = 0;
388
+ _tableAliasesByTable = /* @__PURE__ */ new Map();
389
+ _addedJoinIds = /* @__PURE__ */ new Set();
390
+ _rootTable;
391
+ _elidableNodes = /* @__PURE__ */ new Set();
392
+ _joinFilters = /* @__PURE__ */ new Map();
393
+ generate(select) {
394
+ this._rootTable = select.table;
395
+ this._elidableNodes = this._computeElidableNodes(select);
396
+ this._joinFilters = select.joinFilters;
397
+ if (this._rootTable !== void 0) {
398
+ this._from.add(this._tableAliasForTable(this._rootTable.qualifiedName, this._rootTable.qualifiedName));
399
+ }
400
+ this.processSelect(select.display);
401
+ this._where = this.buildFilter(select.filter);
402
+ const groupByJoins = /* @__PURE__ */ new Map();
403
+ for (const expr of select.groupBy) {
404
+ this._collectRequiredJoins(expr, groupByJoins);
405
+ }
406
+ for (const node of groupByJoins.values()) {
407
+ this._addJoin(node);
408
+ }
409
+ this._groupByParts = select.groupBy.map((a) => this._attrToColString(a));
410
+ this._orderByParts = select.orderBy.map(
411
+ (s) => this.buildFilter(s.column) + (s.direction === "ASC" /* ASC */ ? " ASC" : " DESC")
412
+ );
413
+ this._limit = select.limit;
414
+ }
415
+ _attrToColString(attr) {
416
+ const { column, parent } = this._resolve(attr);
417
+ const ta = this._tableAliasForTable(column.owner, parent ?? column.owner);
418
+ return ta.alias + "." + column.name;
419
+ }
420
+ _collectRequiredJoins(op, out) {
421
+ walkRefs(op, (ref) => {
422
+ const { parent } = this._resolve(ref);
423
+ if (parent !== void 0) out.set(parent, parent);
424
+ });
425
+ }
426
+ /**
427
+ * Determine upfront which join nodes can be satisfied entirely by embedded (join-less) alternates:
428
+ * a node is elidable when every reference to it has an embedded alternate. A reference without one
429
+ * (e.g. a milestoning column) keeps the join for every reference to that node.
430
+ */
431
+ _computeElidableNodes(select) {
432
+ const refsByNode = /* @__PURE__ */ new Map();
433
+ const record = (ref) => {
434
+ const parent = ref instanceof Attribute ? ref.parent() : ref.parent;
435
+ if (parent === void 0) return;
436
+ const refs = refsByNode.get(parent);
437
+ if (refs) refs.push(ref);
438
+ else refsByNode.set(parent, [ref]);
439
+ };
440
+ for (const col of select.display) walkRefs(col, record);
441
+ for (const expr of select.groupBy) walkRefs(expr, record);
442
+ for (const sort of select.orderBy) walkRefs(sort, record);
443
+ walkRefs(select.filter, record);
444
+ const elidable = /* @__PURE__ */ new Set();
445
+ for (const [node, refs] of refsByNode) {
446
+ if (refs.every((ref) => embeddedOf(ref) !== void 0)) elidable.add(node);
447
+ }
448
+ return elidable;
449
+ }
450
+ /** The (column, parent) a reference should resolve to, substituting its embedded alternate when its join is elided. */
451
+ _resolve(ref) {
452
+ const column = ref instanceof Attribute ? ref.column() : ref.column;
453
+ const parent = ref instanceof Attribute ? ref.parent() : ref.parent;
454
+ if (parent !== void 0 && this._elidableNodes.has(parent)) {
455
+ const embedded = embeddedOf(ref);
456
+ if (embedded !== void 0) return this._resolve(embedded);
457
+ }
458
+ return { column, parent };
459
+ }
460
+ _rewriteWindowSpec(window) {
461
+ const partitionBy = window.partitionBy.map((p) => this._rewriteOperation(p));
462
+ const orderBy = window.orderBy.map((s) => new SortOperation(this._rewriteOperation(s.column), s.direction));
463
+ return new WindowSpecification(partitionBy, orderBy);
464
+ }
465
+ _rewriteOperation(op) {
466
+ if (op instanceof Attribute || op instanceof ColumnWithJoin) {
467
+ const { column, parent } = this._resolve(op);
468
+ return new TableAliasColumn(column, this._tableAliasForTable(column.owner, parent ?? column.owner));
469
+ }
470
+ if (op instanceof Column) {
471
+ const ta = this._tableAliasForTable(op.owner, op.owner);
472
+ return new TableAliasColumn(op, ta);
473
+ }
474
+ if (op instanceof AggregateOperation) {
475
+ return new AggregateOperation(
476
+ this._rewriteOperation(op.element),
477
+ op.operator,
478
+ op.displayName,
479
+ op.window ? this._rewriteWindowSpec(op.window) : void 0
480
+ );
481
+ }
482
+ if (op instanceof WindowFunctionOperation) {
483
+ const el = op.element ? this._rewriteOperation(op.element) : null;
484
+ return new WindowFunctionOperation(
485
+ el,
486
+ op.func,
487
+ op.displayName,
488
+ op.secondArg,
489
+ [...op.extraArgs],
490
+ op.window ? this._rewriteWindowSpec(op.window) : void 0
491
+ );
492
+ }
493
+ if (op instanceof ScalarFunctionOperation) {
494
+ return new ScalarFunctionOperation(this._rewriteOperation(op.element), op.func, op.displayName, op.secondArg, op.extraArgs);
495
+ }
496
+ if (op instanceof DateExtractOperation) {
497
+ return new DateExtractOperation(this._rewriteOperation(op.element), op.part, op.displayName);
498
+ }
499
+ if (op instanceof DateArithmeticOperation) {
500
+ return new DateArithmeticOperation(this._rewriteOperation(op.element), op.n, op.unit, op.isAdd, op.displayName);
501
+ }
502
+ if (op instanceof DateDiffOperation) {
503
+ return new DateDiffOperation(this._rewriteOperation(op.element), op.other, op.unit, op.displayName);
504
+ }
505
+ return op;
506
+ }
507
+ processSelect(cols) {
508
+ const requiredJoins = /* @__PURE__ */ new Map();
509
+ for (const col of cols) {
510
+ this._collectRequiredJoins(col, requiredJoins);
511
+ }
512
+ for (const node of requiredJoins.values()) {
513
+ this._addJoin(node);
514
+ }
515
+ for (const col of cols) {
516
+ if (col instanceof Attribute) {
517
+ const { column, parent: node } = this._resolve(col);
518
+ let ta;
519
+ if (node !== void 0) {
520
+ ta = this._tableAliasForTable(column.owner, node);
521
+ } else {
522
+ ta = this._tableAliasForTable(column.owner, column.owner);
523
+ this._from.add(ta);
524
+ }
525
+ this._select.push(new Alias(new TableAliasColumn(column, ta), col.displayName()));
526
+ } else if (col instanceof WindowFunctionOperation) {
527
+ const rewritten = this._rewriteOperation(col);
528
+ let alias;
529
+ if (col.displayName) {
530
+ alias = col.displayName;
531
+ } else if (["ROW_NUMBER" /* ROW_NUMBER */, "RANK" /* RANK */, "DENSE_RANK" /* DENSE_RANK */].includes(col.func)) {
532
+ alias = col.func.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
533
+ } else if (col.element) {
534
+ alias = col.func + " " + findColumn(col).column.name;
535
+ } else {
536
+ alias = col.func;
537
+ }
538
+ this._select.push(new Alias(rewritten, alias));
539
+ } else if (col instanceof AggregateOperation) {
540
+ const colNested = this._resolve(findColumn(col));
541
+ const node = colNested.parent;
542
+ let ta;
543
+ if (node !== void 0) {
544
+ ta = this._tableAliasForTable(colNested.column.owner, node);
545
+ } else {
546
+ ta = this._tableAliasForTable(colNested.column.owner, colNested.column.owner);
547
+ this._from.add(ta);
548
+ }
549
+ const alias = col.displayName ?? col.operator + " " + findColumn(col).column.name;
550
+ const rewrittenAgg = new AggregateOperation(
551
+ new TableAliasColumn(colNested.column, ta),
552
+ col.operator,
553
+ void 0,
554
+ col.window ? this._rewriteWindowSpec(col.window) : void 0
555
+ );
556
+ this._select.push(new Alias(rewrittenAgg, alias));
557
+ } else if (col instanceof ScalarFunctionOperation) {
558
+ const colNested = this._resolve(findColumn(col));
559
+ const node = colNested.parent;
560
+ let ta;
561
+ if (node !== void 0) {
562
+ ta = this._tableAliasForTable(colNested.column.owner, node);
563
+ } else {
564
+ ta = this._tableAliasForTable(colNested.column.owner, colNested.column.owner);
565
+ this._from.add(ta);
566
+ }
567
+ const alias = col.displayName ?? col.func + " " + findColumn(col).column.name;
568
+ this._select.push(new Alias(
569
+ new ScalarFunctionOperation(new TableAliasColumn(colNested.column, ta), col.func, void 0, col.secondArg, col.extraArgs),
570
+ alias
571
+ ));
572
+ } else if (col instanceof DateExtractOperation || col instanceof DateArithmeticOperation || col instanceof DateDiffOperation) {
573
+ const colNested = this._resolve(findColumn(col));
574
+ const node = colNested.parent;
575
+ let ta;
576
+ if (node !== void 0) {
577
+ ta = this._tableAliasForTable(colNested.column.owner, node);
578
+ } else {
579
+ ta = this._tableAliasForTable(colNested.column.owner, colNested.column.owner);
580
+ this._from.add(ta);
581
+ }
582
+ const alias = col.displayName ?? findColumn(col).column.name;
583
+ let aliasedOp;
584
+ if (col instanceof DateExtractOperation) {
585
+ aliasedOp = new DateExtractOperation(new TableAliasColumn(colNested.column, ta), col.part);
586
+ } else if (col instanceof DateArithmeticOperation) {
587
+ aliasedOp = new DateArithmeticOperation(new TableAliasColumn(colNested.column, ta), col.n, col.unit, col.isAdd);
588
+ } else {
589
+ aliasedOp = new DateDiffOperation(new TableAliasColumn(colNested.column, ta), col.other, col.unit);
590
+ }
591
+ this._select.push(new Alias(aliasedOp, alias));
592
+ } else if (col instanceof CountAllOperation) {
593
+ const ta = this._tableAliasForTable(col.table, col.table);
594
+ this._from.add(ta);
595
+ this._select.push(new Alias(col, "Count"));
596
+ }
597
+ }
598
+ }
599
+ _addJoin(node) {
600
+ if (this._addedJoinIds.has(node)) return;
601
+ if (node.parent !== void 0) this._addJoin(node.parent);
602
+ this._addedJoinIds.add(node);
603
+ const join = node.join;
604
+ const left = join.left;
605
+ const srcTa = this._tableAliasForTable(left.owner, node.parent ?? left.owner);
606
+ if (node.parent === void 0) this._from.add(srcTa);
607
+ const sc = new TableAliasColumn(left, srcTa);
608
+ const right = join.right;
609
+ const tc = new TableAliasColumn(right, this._tableAliasForTable(right.owner, node));
610
+ const queryFilter = this._joinFilters.get(node);
611
+ const filterOp = join.filter !== void 0 && queryFilter !== void 0 ? new LogicalOperation(join.filter, "AND" /* AND */, queryFilter) : join.filter ?? queryFilter;
612
+ this._join.push(new Join(sc, tc, filterOp));
613
+ }
614
+ buildFilter(op) {
615
+ if (op instanceof NoOperation) return "";
616
+ if (op instanceof ExistsOperation) {
617
+ const col = op.node.join.right;
618
+ return this.buildFilter(new ColumnWithJoin(col, op.node)) + " IS NOT NULL";
619
+ }
620
+ if (op instanceof NotExistsOperation) {
621
+ const col = op.node.join.right;
622
+ return this.buildFilter(new ColumnWithJoin(col, op.node)) + " IS NULL";
623
+ }
624
+ if (op instanceof IsNotNullOperation) return this.buildFilter(op.element) + " IS NOT NULL";
625
+ if (op instanceof IsNullOperation) return this.buildFilter(op.element) + " IS NULL";
626
+ if (op instanceof LogicalOperation) {
627
+ let left = this.buildFilter(op.left);
628
+ let right = this.buildFilter(op.right);
629
+ if (op.left instanceof LogicalOperation) left = "(" + left + ")";
630
+ if (op.right instanceof LogicalOperation) right = "(" + right + ")";
631
+ return left + LOGICAL_OPERATOR_STR[op.operator] + right;
632
+ }
633
+ if (op instanceof ComparisonOperation) {
634
+ return this.buildFilter(op.left) + COMPARISON_OPERATOR_STR[op.operator] + this.buildFilter(op.right);
635
+ }
636
+ if (op instanceof ConstantOperation) return constantValueString(op);
637
+ if (op instanceof ColumnWithJoin) {
638
+ const { column, parent: node } = this._resolve(op);
639
+ let ta;
640
+ if (node !== void 0) {
641
+ ta = this._tableAliasForTable(column.owner, node);
642
+ this._addJoin(node);
643
+ } else {
644
+ ta = this._tableAliasForTable(column.owner, column.owner);
645
+ }
646
+ return ta.alias + "." + column.name;
647
+ }
648
+ if (op instanceof Column) {
649
+ const ta = this._tableAliasForTable(op.owner, op.owner);
650
+ return ta.alias + "." + op.name;
651
+ }
652
+ throw new Error("Unknown operation in buildFilter: " + op.constructor.name);
653
+ }
654
+ _tableAliasForTable(table, key) {
655
+ if (this._tableAliasesByTable.has(key)) {
656
+ return this._tableAliasesByTable.get(key);
657
+ }
658
+ const ta = new TableAlias(table, "t" + this._tableAliasIncr++);
659
+ this._tableAliasesByTable.set(key, ta);
660
+ return ta;
661
+ }
662
+ buildQueryString() {
663
+ const joins = this._join.map(
664
+ (j) => " LEFT OUTER JOIN " + j.target.tableAlias.table + " AS " + j.target.tableAlias.alias + " ON " + j.source.tableAlias.alias + "." + j.source.column.name + " = " + j.target.tableAlias.alias + "." + j.target.column.name + (j.filterOp ? " AND " + this.buildFilter(j.filterOp) : "")
665
+ );
666
+ return "SELECT " + this._select.map((ca) => sqlOperationToString(ca)).join(",") + " FROM " + Array.from(this._from).map((ta) => ta.table + " AS " + ta.alias).join(",") + joins.join("") + this._buildWhere() + this._buildGroupBy() + this._buildOrderBy() + this._buildLimit();
667
+ }
668
+ _buildWhere() {
669
+ return this._where.length > 0 ? " WHERE " + this._where : "";
670
+ }
671
+ _buildGroupBy() {
672
+ return this._groupByParts.length > 0 ? " GROUP BY " + this._groupByParts.join(", ") : "";
673
+ }
674
+ _buildOrderBy() {
675
+ return this._orderByParts.length > 0 ? " ORDER BY " + this._orderByParts.join(", ") : "";
676
+ }
677
+ _buildLimit() {
678
+ return this._limit !== void 0 ? " LIMIT " + this._limit : "";
679
+ }
680
+ };
681
+ function selectSqlToString(selectOperation) {
682
+ const qg = new SQLQueryGenerator();
683
+ qg.generate(selectOperation);
684
+ return qg.buildQueryString();
685
+ }
686
+ function toSql(businessDate, processingDatetime, columns, table, op, orderBy = [], groupBy = [], limit, businessDateTo = null) {
687
+ const selectOp = buildQueryOperation(businessDate, processingDatetime, columns, table, op, orderBy, groupBy, limit, businessDateTo);
688
+ return selectSqlToString(selectOp);
689
+ }
690
+
691
+ export {
692
+ buildQueryOperation,
693
+ selectSqlToString,
694
+ toSql
695
+ };
696
+ //# sourceMappingURL=chunk-MH4XMYVB.js.map