@nongt/visql 0.0.0-stage → 0.3.0

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 (186) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +916 -2
  3. package/dist/PipelineEditor-DNZkDSaY.js +10042 -0
  4. package/dist/calendarDate-CYlr9TvX.js +43 -0
  5. package/dist/core-api-CBN6rAQG.js +1052 -0
  6. package/dist/core.js +80 -0
  7. package/dist/fixtures.js +7 -0
  8. package/dist/index.js +145 -0
  9. package/dist/issueLocation-Cw5sttQL.js +3183 -0
  10. package/dist/mui-date-pickers.js +117 -0
  11. package/dist/mui.js +510 -0
  12. package/dist/schema-z95dxLxu.js +839 -0
  13. package/dist/sql-import.js +1366 -0
  14. package/dist/style.css +1 -0
  15. package/dist/tokens-BTaVMSOx.js +95 -0
  16. package/dist/types/adapters/mui/MuiDatePicker.d.ts +12 -0
  17. package/dist/types/adapters/mui/MuiDateTimePicker.d.ts +10 -0
  18. package/dist/types/adapters/mui/MuiListInput.d.ts +9 -0
  19. package/dist/types/adapters/mui/MuiTimePicker.d.ts +10 -0
  20. package/dist/types/adapters/mui/QueryBuilder.d.ts +12 -0
  21. package/dist/types/adapters/mui/components.d.ts +16 -0
  22. package/dist/types/adapters/mui/index.d.ts +6 -0
  23. package/dist/types/adapters/mui/muiPickers.d.ts +6 -0
  24. package/dist/types/adapters/mui/pickerStyles.d.ts +28 -0
  25. package/dist/types/adapters/mui/theme.d.ts +11 -0
  26. package/dist/types/core/BetweenOnTextContext.d.ts +11 -0
  27. package/dist/types/core/DialectContext.d.ts +10 -0
  28. package/dist/types/core/DrillDownContext.d.ts +22 -0
  29. package/dist/types/core/ExistsContext.d.ts +29 -0
  30. package/dist/types/core/FlowDirectionContext.d.ts +8 -0
  31. package/dist/types/core/FlowOrientationContext.d.ts +6 -0
  32. package/dist/types/core/FunctionsContext.d.ts +25 -0
  33. package/dist/types/core/GroupKeysContext.d.ts +18 -0
  34. package/dist/types/core/MeasureLockContext.d.ts +12 -0
  35. package/dist/types/core/ReadOnlyContext.d.ts +6 -0
  36. package/dist/types/core/SchemaContext.d.ts +8 -0
  37. package/dist/types/core/SubqueryContext.d.ts +16 -0
  38. package/dist/types/core/UnionBranchContext.d.ts +6 -0
  39. package/dist/types/core/ValueInputContext.d.ts +24 -0
  40. package/dist/types/core/absolutePath.d.ts +57 -0
  41. package/dist/types/core/ast.d.ts +154 -0
  42. package/dist/types/core/astChildren.d.ts +4 -0
  43. package/dist/types/core/astEqual.d.ts +4 -0
  44. package/dist/types/core/astMap.d.ts +21 -0
  45. package/dist/types/core/calendarDate.d.ts +21 -0
  46. package/dist/types/core/columnFormats.d.ts +23 -0
  47. package/dist/types/core/components/BoolPicker.d.ts +8 -0
  48. package/dist/types/core/components/NumberInput.d.ts +8 -0
  49. package/dist/types/core/components/ReadOnlyPart.d.ts +10 -0
  50. package/dist/types/core/components/TextInput.d.ts +8 -0
  51. package/dist/types/core/components/expression/BinaryView.d.ts +10 -0
  52. package/dist/types/core/components/expression/ExprSummary.d.ts +12 -0
  53. package/dist/types/core/components/expression/ExpressionTypeSelector.d.ts +35 -0
  54. package/dist/types/core/components/expression/ExpressionView.d.ts +30 -0
  55. package/dist/types/core/components/expression/FieldView.d.ts +15 -0
  56. package/dist/types/core/components/expression/FormulaPeek.d.ts +14 -0
  57. package/dist/types/core/components/expression/FunctionArgInput.d.ts +22 -0
  58. package/dist/types/core/components/expression/FunctionView.d.ts +7 -0
  59. package/dist/types/core/components/expression/ListView.d.ts +20 -0
  60. package/dist/types/core/components/expression/LiteralView.d.ts +23 -0
  61. package/dist/types/core/components/expression/LogicalView.d.ts +9 -0
  62. package/dist/types/core/components/expression/MeasureMenu.d.ts +21 -0
  63. package/dist/types/core/components/expression/ParamView.d.ts +13 -0
  64. package/dist/types/core/components/expression/RelativeDateView.d.ts +15 -0
  65. package/dist/types/core/components/expression/SubqueryView.d.ts +8 -0
  66. package/dist/types/core/components/expression/formulaClasses.d.ts +8 -0
  67. package/dist/types/core/components/flow/CaseBranchFlowNode.d.ts +5 -0
  68. package/dist/types/core/components/flow/CaseElseFlowNode.d.ts +5 -0
  69. package/dist/types/core/components/flow/CaseFlowNode.d.ts +5 -0
  70. package/dist/types/core/components/flow/ConditionFlowNode.d.ts +5 -0
  71. package/dist/types/core/components/flow/CreateConditionFlowNode.d.ts +14 -0
  72. package/dist/types/core/components/flow/CreateHavingFlowNode.d.ts +11 -0
  73. package/dist/types/core/components/flow/DistinctToggle.d.ts +10 -0
  74. package/dist/types/core/components/flow/ExistsFlowNode.d.ts +9 -0
  75. package/dist/types/core/components/flow/FromFlowNode.d.ts +110 -0
  76. package/dist/types/core/components/flow/FunctionArgFlowNode.d.ts +5 -0
  77. package/dist/types/core/components/flow/FunctionCallFlowNode.d.ts +5 -0
  78. package/dist/types/core/components/flow/FunctionSortKeys.d.ts +10 -0
  79. package/dist/types/core/components/flow/GroupBgNode.d.ts +14 -0
  80. package/dist/types/core/components/flow/GroupByFlowNode.d.ts +29 -0
  81. package/dist/types/core/components/flow/IfElseFlowNode.d.ts +5 -0
  82. package/dist/types/core/components/flow/IfFlowNode.d.ts +5 -0
  83. package/dist/types/core/components/flow/IfThenFlowNode.d.ts +5 -0
  84. package/dist/types/core/components/flow/LeafConditionFrame.d.ts +19 -0
  85. package/dist/types/core/components/flow/LogicalFlowNode.d.ts +5 -0
  86. package/dist/types/core/components/flow/MoveTooltip.d.ts +19 -0
  87. package/dist/types/core/components/flow/NotFlowNode.d.ts +5 -0
  88. package/dist/types/core/components/flow/OrderByFlowNode.d.ts +32 -0
  89. package/dist/types/core/components/flow/SectionLabelFlowNode.d.ts +7 -0
  90. package/dist/types/core/components/flow/SelectFlowNode.d.ts +49 -0
  91. package/dist/types/core/components/flow/SharedQueriesFlowNode.d.ts +39 -0
  92. package/dist/types/core/components/flow/SummaryPill.d.ts +12 -0
  93. package/dist/types/core/components/flow/WarningNote.d.ts +9 -0
  94. package/dist/types/core/components/flow/chainSides.d.ts +18 -0
  95. package/dist/types/core/components/flow/dragContext.d.ts +12 -0
  96. package/dist/types/core/components/flow/moveTooltipHysteresis.d.ts +18 -0
  97. package/dist/types/core/components/flow/useRowDrag.d.ts +34 -0
  98. package/dist/types/core/components/flow/useRowReorderFlip.d.ts +30 -0
  99. package/dist/types/core/derivedTables.d.ts +98 -0
  100. package/dist/types/core/distinctSort.d.ts +7 -0
  101. package/dist/types/core/drillPath.d.ts +11 -0
  102. package/dist/types/core/exists.d.ts +7 -0
  103. package/dist/types/core/existsMenu.d.ts +61 -0
  104. package/dist/types/core/expressionFlow.d.ts +428 -0
  105. package/dist/types/core/fanOut.d.ts +58 -0
  106. package/dist/types/core/findParts.d.ts +19 -0
  107. package/dist/types/core/flowTrees.d.ts +20 -0
  108. package/dist/types/core/focusKey.d.ts +10 -0
  109. package/dist/types/core/formula.d.ts +24 -0
  110. package/dist/types/core/formulaPeek.d.ts +16 -0
  111. package/dist/types/core/functionRegistry.d.ts +117 -0
  112. package/dist/types/core/grouping.d.ts +58 -0
  113. package/dist/types/core/history.d.ts +25 -0
  114. package/dist/types/core/i18n/defaultMessages.d.ts +367 -0
  115. package/dist/types/core/i18n/messages.d.ts +273 -0
  116. package/dist/types/core/i18n/relativeDateWords.d.ts +3 -0
  117. package/dist/types/core/id.d.ts +5 -0
  118. package/dist/types/core/issueAnchor.d.ts +29 -0
  119. package/dist/types/core/issueLocation.d.ts +105 -0
  120. package/dist/types/core/limits.d.ts +17 -0
  121. package/dist/types/core/measures.d.ts +51 -0
  122. package/dist/types/core/params.d.ts +30 -0
  123. package/dist/types/core/pipelineAnchor.d.ts +118 -0
  124. package/dist/types/core/pipelineFlow.d.ts +271 -0
  125. package/dist/types/core/queryAst.d.ts +201 -0
  126. package/dist/types/core/queryHelpers.d.ts +113 -0
  127. package/dist/types/core/queryValidation.d.ts +206 -0
  128. package/dist/types/core/relativeDates.d.ts +11 -0
  129. package/dist/types/core/resolveNames.d.ts +17 -0
  130. package/dist/types/core/rowRange.d.ts +3 -0
  131. package/dist/types/core/schema.d.ts +119 -0
  132. package/dist/types/core/scopeQuery.d.ts +45 -0
  133. package/dist/types/core/selectColumns.d.ts +23 -0
  134. package/dist/types/core/settleQuery.d.ts +11 -0
  135. package/dist/types/core/sharedQueries.d.ts +66 -0
  136. package/dist/types/core/sqlGen.d.ts +102 -0
  137. package/dist/types/core/sqlOffsets.d.ts +5 -0
  138. package/dist/types/core/sqlSpans.d.ts +33 -0
  139. package/dist/types/core/storedQuery.d.ts +43 -0
  140. package/dist/types/core/summarize.d.ts +3 -0
  141. package/dist/types/core/theme/tokens.d.ts +74 -0
  142. package/dist/types/core/ui/UIContext.d.ts +6 -0
  143. package/dist/types/core/ui/index.d.ts +12 -0
  144. package/dist/types/core/ui/types.d.ts +264 -0
  145. package/dist/types/core/unionTables.d.ts +121 -0
  146. package/dist/types/core/useValueTypes.d.ts +12 -0
  147. package/dist/types/core/valueTypes.d.ts +54 -0
  148. package/dist/types/core-api.d.ts +20 -0
  149. package/dist/types/features/queryEditor/ExpressionFlowCanvas.d.ts +10 -0
  150. package/dist/types/features/queryEditor/FindBox.d.ts +12 -0
  151. package/dist/types/features/queryEditor/FlowCanvas.d.ts +96 -0
  152. package/dist/types/features/queryEditor/FocusPulse.d.ts +10 -0
  153. package/dist/types/features/queryEditor/IssuesButton.d.ts +16 -0
  154. package/dist/types/features/queryEditor/PipelineEditor.d.ts +210 -0
  155. package/dist/types/features/queryEditor/QueryOutline.d.ts +16 -0
  156. package/dist/types/features/queryEditor/ResultsPanel.d.ts +11 -0
  157. package/dist/types/features/queryEditor/RunButton.d.ts +11 -0
  158. package/dist/types/features/queryEditor/SubFlowPanel.d.ts +24 -0
  159. package/dist/types/features/queryEditor/UndoRedoToast.d.ts +6 -0
  160. package/dist/types/features/queryEditor/canvasPositioning.d.ts +81 -0
  161. package/dist/types/features/queryEditor/findKeys.d.ts +3 -0
  162. package/dist/types/features/queryEditor/flowDragUtils.d.ts +16 -0
  163. package/dist/types/features/queryEditor/focusContext.d.ts +24 -0
  164. package/dist/types/features/queryEditor/hoveredPart.d.ts +32 -0
  165. package/dist/types/features/queryEditor/issueFocusParts.d.ts +9 -0
  166. package/dist/types/features/queryEditor/issueLocationText.d.ts +7 -0
  167. package/dist/types/features/queryEditor/issueText.d.ts +11 -0
  168. package/dist/types/features/queryEditor/outlineSections.d.ts +23 -0
  169. package/dist/types/features/queryEditor/run.d.ts +36 -0
  170. package/dist/types/features/queryEditor/sectionLabels.d.ts +15 -0
  171. package/dist/types/features/queryEditor/treeScopeContext.d.ts +14 -0
  172. package/dist/types/features/queryEditor/useRemeasureOnDirectionChange.d.ts +7 -0
  173. package/dist/types/features/queryEditor/useRevealNewNodes.d.ts +35 -0
  174. package/dist/types/features/queryEditor/withTreeScope.d.ts +10 -0
  175. package/dist/types/fixtures.d.ts +44 -0
  176. package/dist/types/index.d.ts +13 -0
  177. package/dist/types/mui-date-pickers.d.ts +3 -0
  178. package/dist/types/mui.d.ts +2 -0
  179. package/dist/types/sql-import.d.ts +3 -0
  180. package/dist/types/sqlImport/context.d.ts +71 -0
  181. package/dist/types/sqlImport/expressions.d.ts +11 -0
  182. package/dist/types/sqlImport/importSql.d.ts +28 -0
  183. package/dist/types/sqlImport/parse.d.ts +6 -0
  184. package/dist/types/sqlImport/syntax.d.ts +245 -0
  185. package/dist/types/sqlImport/tokenize.d.ts +26 -0
  186. package/package.json +164 -3
@@ -0,0 +1,1052 @@
1
+ var Et = Object.defineProperty;
2
+ var Tt = (t, e, r) => e in t ? Et(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
3
+ var b = (t, e, r) => Tt(t, typeof e != "symbol" ? e + "" : e, r);
4
+ import { B as x, q as d, F as yt, g as F, d as H, t as Q, h as pt, w as k, o as X, H as At, k as mt, b as gt, i as Dt } from "./schema-z95dxLxu.js";
5
+ import { ag as D, aA as V, aB as Nt, aC as Ot, aD as ht, aj as Rt, V as St, ap as It, aE as y, al as bt, a7 as Ct, aF as Lt, aG as W, $ as Mt } from "./issueLocation-Cw5sttQL.js";
6
+ import { s as J } from "./calendarDate-CYlr9TvX.js";
7
+ class wt extends Error {
8
+ constructor(r, n, s) {
9
+ super(`scopeQuery: the query at ${r.length ? r.join(".") : "the top"} reads "${n}" but can't reach "${s}", which the condition names`);
10
+ /** Where the body is, as keys into the query (validateQuery's
11
+ * `pathSegments` style). */
12
+ b(this, "path");
13
+ /** The table it reads that needs scope. */
14
+ b(this, "table");
15
+ this.name = "ScopeError", this.path = r, this.table = n;
16
+ }
17
+ }
18
+ const K = (t) => Object.prototype.toString.call(t) === "[object Object]", Ft = (t) => Array.isArray(t.joins) && K(t.from);
19
+ function C(t, e, r) {
20
+ if (Array.isArray(t)) {
21
+ const a = t.map((o, f) => C(o, [...e, f], r));
22
+ return a.every((o, f) => o === t[f]) ? t : a;
23
+ }
24
+ if (!K(t)) return t;
25
+ let n = !1;
26
+ const s = Object.entries(t).map(([a, o]) => {
27
+ const f = C(o, [...e, a], r);
28
+ return f !== o && (n = !0), [a, f];
29
+ }), i = n ? Object.fromEntries(s) : t;
30
+ return Ft(i) ? r(i, e) : i;
31
+ }
32
+ const z = (t, e) => x(t).find(e.requires);
33
+ function Z(t, e) {
34
+ return t ? F(t, e) ? !0 : t.type === "logical" && t.operator === "AND" && t.operands.some((r) => F(r, e)) : !1;
35
+ }
36
+ function j(t, e, r, n) {
37
+ const s = z(e, r);
38
+ if (!s || Z(e.where, r.condition)) return e;
39
+ const i = e, a = x(i), o = d(i).flatMap(($) => $.alias ? [$.alias] : []), f = V(r.condition).find(($) => !o.includes($) && yt(t, a, $) === void 0);
40
+ if (f) throw new wt(n, s, f);
41
+ const { joins: c } = Nt(
42
+ t,
43
+ {
44
+ id: "",
45
+ from: e.from,
46
+ joins: e.joins,
47
+ select: []
48
+ },
49
+ r.condition
50
+ ), { where: u } = e;
51
+ let l = r.condition;
52
+ return (u == null ? void 0 : u.type) === "logical" && u.operator === "AND" ? l = { ...u, operands: [...u.operands, r.condition] } : u && (l = { type: "logical", operator: "AND", operands: [u, r.condition] }), { ...e, joins: c, where: l };
53
+ }
54
+ function le(t, e, r) {
55
+ const n = j(t, e, r, []), s = D(t, e, n), i = C(s, [], (a, o) => o.length === 0 ? a : j(t, a, r, o));
56
+ return D(t, s, i);
57
+ }
58
+ function $e(t, e) {
59
+ const r = [];
60
+ return C(t, [], (n, s) => {
61
+ const i = z(n, e);
62
+ return i && !Z(n.where, e.condition) && r.push({ path: s, table: i }), n;
63
+ }), r;
64
+ }
65
+ const qt = (t) => typeof t == "object" && t !== null && !(t instanceof Date), Y = {
66
+ /** A column: `expr.field('orders', 'status')`. */
67
+ field: (t, e) => ({ type: "field", table: t, column: e }),
68
+ /** A literal value, written into the SQL (as a bound parameter by
69
+ * astToParameterizedSql). `''` is marked as the empty text (see
70
+ * LiteralNode's `empty`), since code means it. */
71
+ value: (t) => t === "" ? { type: "literal", value: t, empty: !0 } : { type: "literal", value: t },
72
+ /** A named value the application supplies when generating the SQL
73
+ * (astToParameterizedSql's `values`). With `relative`, a date relative
74
+ * to when the query runs, which the application computes (issue 140):
75
+ * `expr.param('sale_from', { relative: { unit: 'day', offset: -30 } })`. */
76
+ param: (t, e = {}) => e.relative ? { type: "param", name: t, relative: e.relative } : { type: "param", name: t },
77
+ /** `left <operator> right`. */
78
+ compare: (t, e, r) => ({
79
+ type: "binary",
80
+ operator: e,
81
+ left: t,
82
+ right: r
83
+ }),
84
+ /** `operand IS NULL`. */
85
+ isNull: (t) => ({
86
+ type: "binary",
87
+ operator: "IS NULL",
88
+ left: t
89
+ }),
90
+ /** `operand IS NOT NULL`. */
91
+ isNotNull: (t) => ({
92
+ type: "binary",
93
+ operator: "IS NOT NULL",
94
+ left: t
95
+ }),
96
+ /** `left = right`. */
97
+ eq: (t, e) => ({
98
+ type: "binary",
99
+ operator: "=",
100
+ left: t,
101
+ right: e
102
+ }),
103
+ and: (...t) => ({
104
+ type: "logical",
105
+ operator: "AND",
106
+ operands: t
107
+ }),
108
+ or: (...t) => ({
109
+ type: "logical",
110
+ operator: "OR",
111
+ operands: t
112
+ }),
113
+ not: (t) => ({ type: "not", operand: t }),
114
+ /** A function call: `expr.fn('LOWER', expr.field('users', 'email'))`. */
115
+ fn: (t, ...e) => ({
116
+ type: "function",
117
+ name: t,
118
+ args: e
119
+ }),
120
+ /** Whether the outer row has related rows: `EXISTS (SELECT 1 FROM …
121
+ * WHERE <link> AND <where>)`. `link` matches them to the outer row;
122
+ * `where` names the subquery's own tables only. NOT EXISTS:
123
+ * `expr.not(expr.exists(…))`. */
124
+ exists: (t, e) => ({ type: "exists", query: { joins: [], ...t }, link: e }),
125
+ /** `left IN (…)`: the values (`[1, 2, 3]`, or a list of expressions
126
+ * such as params: `expr.list(…)`), or a sub query (`expr.subquery`).
127
+ * NOT IN: `expr.not(expr.in(…))`. */
128
+ in: (t, e) => ({
129
+ type: "binary",
130
+ operator: "IN",
131
+ left: t,
132
+ right: Array.isArray(e) ? Y.list(...e) : e
133
+ }),
134
+ /** `left BETWEEN low AND high` (issue 169), both bounds included: each a
135
+ * value or an expression (a param, a relative date). NOT BETWEEN:
136
+ * `expr.not(expr.between(…))`. */
137
+ between: (t, e, r) => ({
138
+ type: "binary",
139
+ operator: "BETWEEN",
140
+ left: t,
141
+ right: Y.list(e, r)
142
+ }),
143
+ /** IN's values: each a value (`expr.list(1, 2)`) or an expression
144
+ * (`expr.list(expr.param('a'), expr.param('b'))`). */
145
+ list: (...t) => ({
146
+ type: "list",
147
+ items: t.map((e) => qt(e) ? e : { type: "literal", value: e })
148
+ }),
149
+ /** A query of its own for IN to compare with, selecting `select` — one
150
+ * column. Its tables are its own: it sees nothing of the query around
151
+ * it. `expr.in(expr.field('customer', 'id'), expr.subquery({ from: {
152
+ * table: 'sale_transaction' }, select: expr.field('sale_transaction',
153
+ * 'customer_id') }))`. */
154
+ subquery: ({ select: t, ...e }) => ({
155
+ type: "subquery",
156
+ id: H(),
157
+ query: { joins: [], ...e, select: [{ id: H(), expression: t }] }
158
+ })
159
+ };
160
+ function Ee(t, e, r) {
161
+ return y(t, e, { type: "setBaseTable", table: r });
162
+ }
163
+ function Te(t, e, r, n = {}) {
164
+ const s = { type: "addJoin", table: r, ...n };
165
+ return y(t, e, s);
166
+ }
167
+ function ye(t, e, r) {
168
+ return y(t, e, { type: "removeJoin", joinId: r });
169
+ }
170
+ function Ut(t, e, r, n = {}) {
171
+ const s = Ot(e), i = V(r);
172
+ if (s && i.some((c) => c !== s.alias)) {
173
+ if (i.includes(s.alias))
174
+ throw new Error("addCondition: a condition names both the union and tables of its branches: add it in two parts");
175
+ return s.query.union.forEach((c) => {
176
+ const u = c.from.table, l = new Set(d(c).map(Q)), $ = ht(t, u), p = i.find((A) => !l.has(A) && !$.has(A));
177
+ if (p)
178
+ throw new Error(`addCondition: "${p}" can't be reached from "${u}", one of the union's tables: a condition must reach every branch`);
179
+ }), s.query.union.reduce((c, u, l) => Rt(
180
+ c,
181
+ [St(s.id, l)],
182
+ ($) => Ut(t, $, r, n)
183
+ ), e);
184
+ }
185
+ const a = n.operator ?? "AND", { where: o } = e;
186
+ let f;
187
+ return o ? o.type === "logical" && o.operator === a ? f = { ...o, operands: [...o.operands, r] } : f = { type: "logical", operator: a, operands: [o, r] } : f = r, D(t, e, It(t, e, f));
188
+ }
189
+ function pe(t, e, r, n) {
190
+ const s = y(t, e, { type: "addSelectItem" }), i = s.select[s.select.length - 1].id, a = y(t, s, {
191
+ type: "setSelectExpression",
192
+ selectId: i,
193
+ expression: r
194
+ }), o = n === void 0 ? a : y(t, a, { type: "setSelectAlias", selectId: i, alias: n });
195
+ return D(t, e, o);
196
+ }
197
+ function Ae(t, e, r) {
198
+ const n = y(t, e, { type: "addGroupByItem" }), { id: s } = n.groupBy[n.groupBy.length - 1], i = y(t, n, {
199
+ type: "setGroupByExpression",
200
+ groupById: s,
201
+ expression: r
202
+ });
203
+ return D(t, e, i);
204
+ }
205
+ function me(t, e, r) {
206
+ return D(t, e, bt(t, e, r));
207
+ }
208
+ function ge(t, e, r, n = "asc") {
209
+ const s = y(t, e, { type: "addOrderByItem" }), { id: i } = s.orderBy[s.orderBy.length - 1], a = y(t, s, {
210
+ type: "setOrderByExpression",
211
+ orderById: i,
212
+ expression: r
213
+ }), o = y(t, a, {
214
+ type: "setOrderByDirection",
215
+ orderById: i,
216
+ direction: n
217
+ });
218
+ return D(t, e, o);
219
+ }
220
+ function De(t, e, r) {
221
+ let n = e;
222
+ return "limit" in r && (n = y(t, n, { type: "setLimit", limit: r.limit })), "offset" in r && (n = y(t, n, { type: "setOffset", offset: r.offset })), n;
223
+ }
224
+ function Ne(t, e, r) {
225
+ return y(t, e, { type: "setDistinct", distinct: r });
226
+ }
227
+ function Oe(t) {
228
+ if (!pt(t)) throw new Error(`query "${t.id}" has no base table yet`);
229
+ return t;
230
+ }
231
+ const q = 4;
232
+ class h extends Error {
233
+ constructor(r, n) {
234
+ super(n);
235
+ b(this, "kind");
236
+ this.name = "QueryFormatError", this.kind = r;
237
+ }
238
+ }
239
+ const I = (t) => typeof t == "object" && t !== null && !Array.isArray(t);
240
+ function vt(t) {
241
+ const e = [];
242
+ let r = 0;
243
+ for (; r < t.length; ) {
244
+ for (; t[r] === " "; ) r += 1;
245
+ if (t[r] === "'") {
246
+ let n = "";
247
+ for (r += 1; r < t.length && !(t[r] === "'" && t[r + 1] !== "'"); )
248
+ n += t[r], r += t[r] === "'" ? 2 : 1;
249
+ e.push(n);
250
+ const s = t.indexOf(",", r);
251
+ r = s === -1 ? t.length : s + 1;
252
+ } else {
253
+ const n = t.indexOf(",", r), s = t.slice(r, n === -1 ? void 0 : n).trim();
254
+ s !== "" && e.push(/^-?\d+(\.\d+)?$/.test(s) ? Number(s) : s), r = n === -1 ? t.length : n + 1;
255
+ }
256
+ }
257
+ return e;
258
+ }
259
+ function Bt(t) {
260
+ const e = (r) => {
261
+ if (Array.isArray(r)) return r.map(e);
262
+ if (!I(r)) return r;
263
+ const n = Object.fromEntries(Object.entries(r).map(([a, o]) => [a, e(o)])), { right: s } = n;
264
+ if (n.type !== "binary" || n.operator !== "IN" || !I(s) || s.type === "subquery" || s.type === "list") return n;
265
+ const i = s.type === "literal" && typeof s.value == "string" ? vt(s.value).map((a) => ({ type: "literal", value: a })) : [s];
266
+ return { ...n, right: { type: "list", items: i } };
267
+ };
268
+ return e(t);
269
+ }
270
+ const dt = (t) => t, _t = (t) => t, Ht = [Bt, dt, _t];
271
+ function jt(t, e, r) {
272
+ return r.slice(e - 1).reduce((n, s) => s(n), t);
273
+ }
274
+ function L(t, e) {
275
+ return Array.isArray(t) ? t.map((r) => L(r, e)) : I(t) ? t.type === "literal" ? e(t) : Object.fromEntries(Object.entries(t).map(([r, n]) => [r, L(n, e)])) : t;
276
+ }
277
+ function Yt(t) {
278
+ return t.value instanceof Date ? { ...t, value: t.value.toISOString(), valueType: "date" } : typeof t.value == "bigint" ? { ...t, value: String(t.value), valueType: "bigint" } : t;
279
+ }
280
+ function Pt(t) {
281
+ if (t.valueType === void 0) return t;
282
+ const { valueType: e, ...r } = t, n = String(r.value);
283
+ let s;
284
+ if (e === "date") {
285
+ if (s = new Date(n), Number.isNaN(s.getTime()))
286
+ throw new h("invalid", `not a date: ${JSON.stringify(n)}`);
287
+ } else if (e === "bigint" && /^-?\d+$/.test(n))
288
+ s = BigInt(n);
289
+ else {
290
+ const i = String(e);
291
+ throw new h("invalid", `can't read a ${i} from ${JSON.stringify(n)}`);
292
+ }
293
+ return { ...r, value: s };
294
+ }
295
+ function he(t) {
296
+ return {
297
+ version: q,
298
+ query: L(t, Yt)
299
+ };
300
+ }
301
+ function Re(t) {
302
+ if (!I(t))
303
+ throw new h("invalid", "a stored query is an object");
304
+ const { version: e } = t;
305
+ if (typeof e != "number" || !Number.isInteger(e) || e < 1)
306
+ throw new h("invalid", "a stored query has a whole-number version from 1");
307
+ if (e > q)
308
+ throw new h(
309
+ "newerVersion",
310
+ `stored in format ${e}; this version reads up to ${q}`
311
+ );
312
+ const r = jt(t.query, e, Ht);
313
+ if (!I(r) || typeof r.id != "string")
314
+ throw new h("invalid", "a stored query has a query with a string id");
315
+ return L(r, Pt);
316
+ }
317
+ function U(t, e) {
318
+ const r = new Map(e == null ? void 0 : e.tableOf), n = new Set(e == null ? void 0 : e.aliases), s = new Set(e == null ? void 0 : e.derived);
319
+ return t.forEach(({ table: i, alias: a }) => {
320
+ if (i === void 0) {
321
+ a && s.add(a);
322
+ return;
323
+ }
324
+ r.set(i, i), n.delete(i), s.delete(i), a && (r.set(a, i), n.add(a), s.delete(a));
325
+ }), { tableOf: r, aliases: n, derived: s };
326
+ }
327
+ function Gt(t, e, r) {
328
+ const n = t.on && S(t.on, e, r);
329
+ return t.query ? { ...t, on: n, query: At(t.query, (s) => M(s, r)) } : t.shared !== void 0 ? { ...t, on: n } : { ...t, on: n, table: r(t.table) };
330
+ }
331
+ function S(t, e, r) {
332
+ if (t.type === "field") {
333
+ if (!t.table || e.derived.has(t.table)) return t;
334
+ const n = e.tableOf.get(t.table) ?? t.table;
335
+ return {
336
+ ...t,
337
+ table: e.aliases.has(t.table) ? t.table : r(n),
338
+ ...t.column ? { column: r(n, t.column) } : {}
339
+ };
340
+ }
341
+ if (t.type === "subquery") return { ...t, query: M(t.query, r) };
342
+ if (t.type === "exists") {
343
+ const { query: n } = t, s = [n.from, ...n.joins], i = U(s), a = U(s, e);
344
+ return {
345
+ ...t,
346
+ link: S(t.link, a, r),
347
+ query: {
348
+ ...n,
349
+ from: { ...n.from, table: r(n.from.table) },
350
+ joins: n.joins.map((o) => Gt(o, i, r)),
351
+ ...n.where ? { where: S(n.where, i, r) } : {}
352
+ }
353
+ };
354
+ }
355
+ return X(t, (n) => S(n, e, r));
356
+ }
357
+ function M(t, e) {
358
+ const r = U([t.from, ...t.joins]), n = k(
359
+ t,
360
+ (s) => S(s, r, e),
361
+ (s) => M(s, e)
362
+ );
363
+ return {
364
+ ...n,
365
+ from: n.from.table === void 0 ? n.from : { ...n.from, table: e(n.from.table) },
366
+ joins: n.joins.map((s) => s.table === void 0 ? s : { ...s, table: e(s.table) })
367
+ };
368
+ }
369
+ function v(t, e) {
370
+ if (Array.isArray(t)) return t.map((s) => v(s, e));
371
+ if (typeof t != "object" || t === null || t instanceof Date) return t;
372
+ const r = Object.fromEntries(Object.entries(t).map(
373
+ ([s, i]) => [s, v(i, e)]
374
+ ));
375
+ if (!("from" in r) || !Array.isArray(r.joins)) return r;
376
+ const n = (s) => s.table !== void 0 && !s.alias && e(s.table) !== s.table ? { ...s, alias: s.table } : s;
377
+ return {
378
+ ...r,
379
+ from: n(r.from),
380
+ joins: r.joins.map(n)
381
+ };
382
+ }
383
+ function xt(t, e) {
384
+ return M(v(t, e), e);
385
+ }
386
+ const Qt = /^(\d{2}):(\d{2})(?::(\d{2}))?$/, P = /YYYY|MM|DD|HH|mm|ss/g, O = (t, e = 2) => String(t).padStart(e, "0");
387
+ function tt(t, e) {
388
+ let r;
389
+ const n = typeof t == "string" ? Qt.exec(t.trim()) : null;
390
+ if (n)
391
+ r = { HH: n[1], mm: n[2], ss: n[3] ?? "00" };
392
+ else {
393
+ const a = typeof t == "string" ? Ct(t, "dateTime") : t;
394
+ a instanceof Date && (r = {
395
+ YYYY: O(a.getUTCFullYear(), 4),
396
+ MM: O(a.getUTCMonth() + 1),
397
+ DD: O(a.getUTCDate()),
398
+ HH: O(a.getUTCHours()),
399
+ mm: O(a.getUTCMinutes()),
400
+ ss: O(a.getUTCSeconds())
401
+ });
402
+ }
403
+ if (!r) return t;
404
+ const s = r;
405
+ return (e.match(P) ?? []).some((a) => s[a] === void 0) ? t : e.replace(P, (a) => s[a]);
406
+ }
407
+ function et(t, e) {
408
+ const r = /* @__PURE__ */ new Map(), n = (s) => {
409
+ const i = /* @__PURE__ */ new Map();
410
+ d(s).forEach((c) => i.set(Q(c), c.table));
411
+ const a = (c) => {
412
+ if ((c == null ? void 0 : c.type) !== "field" || !c.table || !c.column) return;
413
+ const u = i.has(c.table) ? i.get(c.table) : c.table, l = u === void 0 ? void 0 : mt(e, u), $ = l == null ? void 0 : l.columns.find((p) => p.name === c.column);
414
+ return $ == null ? void 0 : $.format;
415
+ }, o = (c, u) => {
416
+ switch (c.type) {
417
+ case "literal":
418
+ return { ...c, value: tt(c.value, u) };
419
+ case "list":
420
+ return { ...c, items: c.items.map((l) => o(l, u)) };
421
+ case "param":
422
+ return r.has(c.name) || r.set(c.name, u), c;
423
+ default:
424
+ return c;
425
+ }
426
+ }, f = (c) => {
427
+ if (c.type === "subquery") return { ...c, query: n(c.query) };
428
+ const u = X(c, f);
429
+ if (u.type !== "binary" || !u.right) return u;
430
+ const l = a(u.left), $ = a(u.right);
431
+ return {
432
+ ...u,
433
+ left: $ ? o(u.left, $) : u.left,
434
+ right: l ? o(u.right, l) : u.right
435
+ };
436
+ };
437
+ return k(s, f, (c) => n(c));
438
+ };
439
+ return { query: n(t), params: r };
440
+ }
441
+ const Se = ["mysql", "mssql", "postgres"], Ie = {
442
+ mysql: "MySQL",
443
+ mssql: "SQL Server",
444
+ postgres: "PostgreSQL"
445
+ };
446
+ function m(t, e) {
447
+ const r = t.replace(/[\uE000-\uE003]/g, "");
448
+ switch (e) {
449
+ case "mysql":
450
+ return `\`${r.replace(/`/g, "``")}\``;
451
+ case "mssql":
452
+ return `[${r.replace(/]/g, "]]")}]`;
453
+ case "postgres":
454
+ return `"${r.replace(/"/g, '""')}"`;
455
+ default:
456
+ return `"${r.replace(/"/g, '""')}"`;
457
+ }
458
+ }
459
+ const kt = /^[A-Za-z_][A-Za-z0-9_]*$/, rt = (t) => `${t}`, Xt = /\uE000(\d+)\uE000/g;
460
+ let N;
461
+ function be(t, e) {
462
+ N = { ...t, writing: [] };
463
+ try {
464
+ return e();
465
+ } finally {
466
+ N = void 0;
467
+ }
468
+ }
469
+ function nt(t, e, r) {
470
+ if (typeof t != "object" || t === null || t instanceof Date) return;
471
+ let n;
472
+ return Object.entries(t).some(([s, i]) => {
473
+ const a = [...r, Array.isArray(t) ? Number(s) : s];
474
+ return n = i === e ? a : nt(i, e, a), n !== void 0;
475
+ }), n;
476
+ }
477
+ function T(t, e) {
478
+ if (!N) return e();
479
+ const { writing: r, paths: n } = N, s = r[r.length - 1], i = typeof t == "string" ? [t] : nt(s.value, t, s.path);
480
+ if (!i) return e();
481
+ r.push({ value: t, path: i });
482
+ try {
483
+ return `${n.push(i) - 1}${e()}`;
484
+ } finally {
485
+ r.pop();
486
+ }
487
+ }
488
+ const Vt = {
489
+ mysql: {
490
+ text: "CHAR",
491
+ integer: "SIGNED",
492
+ number: "DECIMAL(38, 10)",
493
+ date: "DATE",
494
+ dateTime: "DATETIME",
495
+ time: "TIME",
496
+ boolean: "SIGNED"
497
+ },
498
+ mssql: {
499
+ text: "NVARCHAR(MAX)",
500
+ integer: "BIGINT",
501
+ number: "DECIMAL(38, 10)",
502
+ date: "DATE",
503
+ dateTime: "DATETIME2",
504
+ time: "TIME",
505
+ boolean: "BIT"
506
+ },
507
+ postgres: {
508
+ text: "text",
509
+ integer: "bigint",
510
+ number: "numeric",
511
+ date: "date",
512
+ dateTime: "timestamp",
513
+ time: "time",
514
+ boolean: "boolean"
515
+ }
516
+ };
517
+ function Wt(t, e) {
518
+ var n;
519
+ const r = (n = Vt[e]) == null ? void 0 : n[t];
520
+ return r ? e === "postgres" ? `NULL::${r}` : `CAST(NULL AS ${r})` : "NULL";
521
+ }
522
+ function st(t, e, r) {
523
+ if (t == null) return "NULL";
524
+ if (r)
525
+ return r.values.push(t), rt(r.values.length - 1);
526
+ if (typeof t == "boolean")
527
+ return e === "mssql" ? t ? "1" : "0" : t ? "TRUE" : "FALSE";
528
+ if (typeof t == "string") {
529
+ const n = N ? t.replace(/[\uE001-\uE003]/g, "") : t;
530
+ return n === "" ? "''" : `'${n.replace(/'/g, "''")}'`;
531
+ }
532
+ return typeof t == "number" || typeof t == "bigint" ? String(t) : t instanceof Date ? `'${J(t)}'` : String(t);
533
+ }
534
+ function Jt(t, e) {
535
+ switch (t) {
536
+ case "!=":
537
+ return e === "mssql" ? "<>" : "!=";
538
+ case "REGEXP":
539
+ if (e === "postgres") return "~";
540
+ if (e === "mssql") throw new Error("REGEXP isn't available in SQL Server");
541
+ return "REGEXP";
542
+ default:
543
+ return t;
544
+ }
545
+ }
546
+ function g(t) {
547
+ return (t == null ? void 0 : t.type) === "literal" && typeof t.value == "string" && /^[A-Za-z_]+$/.test(t.value) ? t.value.toUpperCase() : "DAY";
548
+ }
549
+ const w = {
550
+ YEAR: "year",
551
+ QUARTER: "quarter",
552
+ MONTH: "month",
553
+ WEEK: "week",
554
+ DAY: "day",
555
+ HOUR: "hour",
556
+ MINUTE: "minute",
557
+ SECOND: "second",
558
+ MILLISECOND: "millisecond"
559
+ }, Kt = {
560
+ // ---- Date arithmetic ----
561
+ DATE_ADD: ([t, e], r, n, s) => {
562
+ var a;
563
+ const i = g(r[2]);
564
+ switch (n) {
565
+ case "mysql":
566
+ return i === "MILLISECOND" ? `DATE_ADD(${t}, INTERVAL (${e}) * 1000 MICROSECOND)` : `DATE_ADD(${t}, INTERVAL ${e} ${i})`;
567
+ case "postgres": {
568
+ const o = w[i] ?? i.toLowerCase();
569
+ return !s && ((a = r[1]) == null ? void 0 : a.type) === "literal" && typeof r[1].value == "number" ? `(${t} + INTERVAL '${r[1].value} ${o}')` : `(${t} + (${e} * INTERVAL '1 ${o}'))`;
570
+ }
571
+ case "mssql":
572
+ return `DATEADD(${i}, ${e}, ${t})`;
573
+ default:
574
+ return `DATE_ADD(${t}, ${e}, ${g(r[2])})`;
575
+ }
576
+ },
577
+ DATE_SUB: ([t, e], r, n, s) => {
578
+ var a;
579
+ const i = g(r[2]);
580
+ switch (n) {
581
+ case "mysql":
582
+ return i === "MILLISECOND" ? `DATE_SUB(${t}, INTERVAL (${e}) * 1000 MICROSECOND)` : `DATE_SUB(${t}, INTERVAL ${e} ${i})`;
583
+ case "postgres": {
584
+ const o = w[i] ?? i.toLowerCase();
585
+ return !s && ((a = r[1]) == null ? void 0 : a.type) === "literal" && typeof r[1].value == "number" ? `(${t} - INTERVAL '${r[1].value} ${o}')` : `(${t} - (${e} * INTERVAL '1 ${o}'))`;
586
+ }
587
+ case "mssql":
588
+ return `DATEADD(${i}, -(${e}), ${t})`;
589
+ default:
590
+ return `DATE_SUB(${t}, ${e}, ${g(r[2])})`;
591
+ }
592
+ },
593
+ // ---- Date diff ----
594
+ DATEDIFF: ([t, e], r, n) => {
595
+ const s = g(r[2]);
596
+ switch (n) {
597
+ case "mysql":
598
+ return `TIMESTAMPDIFF(${s}, ${t}, ${e})`;
599
+ case "mssql":
600
+ return `DATEDIFF(${s}, ${t}, ${e})`;
601
+ case "postgres":
602
+ switch (s) {
603
+ case "YEAR":
604
+ return `EXTRACT(YEAR FROM age(${e}, ${t}))::integer`;
605
+ case "QUARTER": {
606
+ const i = `EXTRACT(YEAR FROM age(${e}, ${t}))`, a = `EXTRACT(MONTH FROM age(${e}, ${t}))`;
607
+ return `FLOOR((${i} * 12 + ${a}) / 3)::integer`;
608
+ }
609
+ case "MONTH": {
610
+ const i = `EXTRACT(YEAR FROM age(${e}, ${t}))`, a = `EXTRACT(MONTH FROM age(${e}, ${t}))`;
611
+ return `(${i} * 12 + ${a})::integer`;
612
+ }
613
+ case "WEEK":
614
+ return `FLOOR((${e}::date - ${t}::date) / 7)`;
615
+ case "DAY":
616
+ return `(${e}::date - ${t}::date)`;
617
+ case "HOUR":
618
+ return `FLOOR(EXTRACT(EPOCH FROM (${e} - ${t})) / 3600)::integer`;
619
+ case "MINUTE":
620
+ return `FLOOR(EXTRACT(EPOCH FROM (${e} - ${t})) / 60)::integer`;
621
+ case "SECOND":
622
+ return `FLOOR(EXTRACT(EPOCH FROM (${e} - ${t})))::integer`;
623
+ case "MILLISECOND":
624
+ return `FLOOR(EXTRACT(EPOCH FROM (${e} - ${t})) * 1000)::integer`;
625
+ default:
626
+ return `/* unknown unit: ${s} */`;
627
+ }
628
+ default:
629
+ return `DATEDIFF(${t}, ${e}, ${s})`;
630
+ }
631
+ },
632
+ // ---- Date extract ----
633
+ EXTRACT: ([t], e, r) => {
634
+ const n = g(e[1]);
635
+ switch (r) {
636
+ case "mysql":
637
+ return n === "MILLISECOND" ? `FLOOR(MICROSECOND(${t}) / 1000)` : `EXTRACT(${n} FROM ${t})`;
638
+ case "postgres":
639
+ return n === "MILLISECOND" ? `EXTRACT(MILLISECONDS FROM ${t})::integer` : `EXTRACT(${n} FROM ${t})`;
640
+ case "mssql":
641
+ return `DATEPART(${n}, ${t})`;
642
+ default:
643
+ return `EXTRACT(${t}, ${n})`;
644
+ }
645
+ },
646
+ // ---- Date truncation ----
647
+ DATE_TRUNC: ([t], e, r) => {
648
+ const n = g(e[1]);
649
+ switch (r) {
650
+ case "mysql":
651
+ switch (n) {
652
+ case "YEAR":
653
+ return `DATE_FORMAT(${t}, '%Y-01-01')`;
654
+ case "QUARTER":
655
+ return `MAKEDATE(YEAR(${t}), 1) + INTERVAL (QUARTER(${t}) - 1) QUARTER`;
656
+ case "MONTH":
657
+ return `DATE_FORMAT(${t}, '%Y-%m-01')`;
658
+ case "WEEK":
659
+ return `DATE_SUB(DATE(${t}), INTERVAL WEEKDAY(${t}) DAY)`;
660
+ case "DAY":
661
+ return `DATE(${t})`;
662
+ case "HOUR":
663
+ return `DATE_FORMAT(${t}, '%Y-%m-%d %H:00:00')`;
664
+ case "MINUTE":
665
+ return `DATE_FORMAT(${t}, '%Y-%m-%d %H:%i:00')`;
666
+ case "SECOND":
667
+ return `DATE_FORMAT(${t}, '%Y-%m-%d %H:%i:%s')`;
668
+ case "MILLISECOND":
669
+ return `DATE_FORMAT(${t}, '%Y-%m-%d %H:%i:%s.000')`;
670
+ default:
671
+ return `/* unknown unit: ${n} */`;
672
+ }
673
+ case "postgres":
674
+ return `DATE_TRUNC('${w[n] ?? n.toLowerCase()}', ${t})`;
675
+ case "mssql":
676
+ switch (n) {
677
+ case "YEAR":
678
+ return `DATEFROMPARTS(YEAR(${t}), 1, 1)`;
679
+ case "QUARTER":
680
+ return `DATEFROMPARTS(YEAR(${t}), (DATEPART(QUARTER, ${t}) - 1) * 3 + 1, 1)`;
681
+ case "MONTH":
682
+ return `DATEFROMPARTS(YEAR(${t}), MONTH(${t}), 1)`;
683
+ case "WEEK": {
684
+ const s = `CAST(${t} AS DATE)`;
685
+ return `DATEADD(DAY, -(DATEDIFF(DAY, 0, ${s}) % 7), ${s})`;
686
+ }
687
+ case "DAY":
688
+ return `CAST(${t} AS DATE)`;
689
+ case "HOUR":
690
+ return `DATEADD(HOUR, DATEDIFF(HOUR, 0, ${t}), 0)`;
691
+ case "MINUTE":
692
+ return `DATEADD(MINUTE, DATEDIFF(MINUTE, 0, ${t}), 0)`;
693
+ case "SECOND":
694
+ return `DATEADD(SECOND, DATEDIFF(SECOND, '2000-01-01', ${t}), '2000-01-01')`;
695
+ case "MILLISECOND": {
696
+ const s = `CAST(${t} AS DATE)`;
697
+ return `DATEADD(MILLISECOND, DATEDIFF(MILLISECOND, ${s}, ${t}), ${s})`;
698
+ }
699
+ default:
700
+ return `/* unknown unit: ${n} */`;
701
+ }
702
+ default:
703
+ return `DATE_TRUNC(${t}, ${n})`;
704
+ }
705
+ },
706
+ // ---- Type cast ----
707
+ /**
708
+ * CAST(expr, type_name) — type_name is stored as a string literal.
709
+ * Renders as CAST(expr AS type_name) for all dialects.
710
+ */
711
+ CAST: ([t], e) => {
712
+ const r = e[1], n = (r == null ? void 0 : r.type) === "literal" && typeof r.value == "string" && /^[A-Za-z][A-Za-z0-9_ ]*(\(\s*\d+\s*(,\s*\d+\s*)?\))?$/.test(r.value) ? r.value : "??";
713
+ return `CAST(${t} AS ${n})`;
714
+ },
715
+ // ---- String aggregation (issue 137) ----
716
+ // The separator goes into the SQL as a literal even in parameterized SQL:
717
+ // MySQL's SEPARATOR takes nothing else.
718
+ STRING_AGG: ([t = "??"], e, r, n, s, i) => {
719
+ const a = e[1] ?? { type: "literal", value: ", " }, o = a.type === "literal" && typeof a.value == "string" ? st(a.value, r) : "??", f = s.distinct ? "DISTINCT " : "", c = ($) => {
720
+ var p;
721
+ return (p = s.orderBy) != null && p.length ? `ORDER BY ${s.orderBy.map((A) => `${$(A)} ${A.direction === "desc" ? "DESC" : "ASC"}`).join(", ")}` : "";
722
+ }, u = ($) => i($.expression), l = ($) => $ ? ` ${$}` : "";
723
+ switch (r) {
724
+ case "mysql":
725
+ return `GROUP_CONCAT(${f}${t}${l(c(u))} SEPARATOR ${o})`;
726
+ case "postgres": {
727
+ const $ = `CAST(${t} AS TEXT)`, p = c((A) => {
728
+ if (!s.distinct) return u(A);
729
+ if (F(A.expression, e[0])) return $;
730
+ throw new Error("PostgreSQL orders STRING_AGG of different values by the value only");
731
+ });
732
+ return `STRING_AGG(${f}${$}, ${o}${l(p)})`;
733
+ }
734
+ case "mssql": {
735
+ if (s.distinct)
736
+ throw new Error("SQL Server's STRING_AGG can't join only different values");
737
+ const $ = c(u), p = $ ? ` WITHIN GROUP (${$})` : "";
738
+ return `STRING_AGG(CAST(${t} AS NVARCHAR(MAX)), ${o})${p}`;
739
+ }
740
+ default:
741
+ return `STRING_AGG(${f}${t}, ${o}${l(c(u))})`;
742
+ }
743
+ }
744
+ };
745
+ function R(t) {
746
+ return t.type === "binary" || t.type === "logical" || t.type === "if" || t.type === "case";
747
+ }
748
+ function E(t, e, r, n) {
749
+ return T(t, () => zt(t, e, r, n));
750
+ }
751
+ function G(t, e, r, n) {
752
+ const s = (i) => {
753
+ if (!i) return "??";
754
+ const a = E(i, e, r, n);
755
+ return R(i) ? `(${a})` : a;
756
+ };
757
+ return T(t, () => {
758
+ const [i, a] = t.type === "list" ? t.items : [t];
759
+ return `${s(i)} AND ${s(a)}`;
760
+ });
761
+ }
762
+ function zt(t, e, r, n) {
763
+ var a;
764
+ const s = " ".repeat(r), i = " ".repeat(r + 1);
765
+ switch (t.type) {
766
+ case "literal":
767
+ return t.value === "" && !t.empty ? "??" : t.value === null && t.as ? Wt(t.as, e) : st(t.value, e, n);
768
+ case "param": {
769
+ if (!n) return kt.test(t.name) ? `:${t.name}` : "??";
770
+ if (!n.named.has(t.name))
771
+ throw new Error(`no value for parameter "${t.name}"`);
772
+ return n.values.push(n.named.get(t.name)), rt(n.values.length - 1);
773
+ }
774
+ case "field": {
775
+ if (!t.column) return "??";
776
+ const o = m(t.column, e);
777
+ return t.table ? `${m(t.table, e)}.${o}` : o;
778
+ }
779
+ case "function": {
780
+ const o = t.args.map((l) => E(l, e, r, n)), f = Kt[t.name.toUpperCase()];
781
+ if (f)
782
+ return f(
783
+ o,
784
+ t.args,
785
+ e,
786
+ n !== void 0,
787
+ t,
788
+ (l) => E(l, e, r, n)
789
+ );
790
+ const c = /^[A-Za-z_][A-Za-z0-9_.]*$/.test(t.name) || t.name === "" ? t.name : "??";
791
+ if (o.length === 0 && c.toUpperCase() === "COUNT") return `${c}(*)`;
792
+ const u = t.distinct && o.length > 0 ? "DISTINCT " : "";
793
+ return `${c}(${u}${o.join(", ")})`;
794
+ }
795
+ case "binary": {
796
+ const o = t.operator ? Jt(t.operator, e) : "=", f = E(t.left, e, r, n), c = R(t.left) ? `(${f})` : f;
797
+ if (Mt(t.operator)) return `${c} ${o}`;
798
+ if (!t.right) return `${c} ${o} ??`;
799
+ if (o === "BETWEEN")
800
+ return `${c} BETWEEN ${G(t.right, e, r, n)}`;
801
+ if (o === "IN")
802
+ return t.right.type === "list" ? `${c} IN ${E(t.right, e, r, n)}` : `${c} IN (${E(t.right, e, r, n)})`;
803
+ const u = E(t.right, e, r, n), l = R(t.right) ? `(${u})` : u;
804
+ return `${c} ${o} ${l}`;
805
+ }
806
+ case "logical": {
807
+ if (t.operands.length === 0) return "/* empty */";
808
+ if (t.operands.length === 1)
809
+ return E(t.operands[0], e, r, n);
810
+ const o = `
811
+ ${s}${t.operator} `;
812
+ return t.operands.map((f) => {
813
+ if (f.type === "logical") {
814
+ const c = E(f, e, r + 1, n);
815
+ return `(
816
+ ${i}${c}
817
+ ${s})`;
818
+ }
819
+ return E(f, e, r, n);
820
+ }).join(o);
821
+ }
822
+ case "not": {
823
+ const { operand: o } = t;
824
+ if (o.type === "binary" && o.operator === "IN" && ((a = o.right) == null ? void 0 : a.type) === "subquery") {
825
+ const f = E(o.left, e, r, n);
826
+ return `${R(o.left) ? `(${f})` : f} NOT IN (${E(o.right, e, r, n)})`;
827
+ }
828
+ if (o.type === "binary" && o.operator === "BETWEEN" && o.right) {
829
+ const f = E(o.left, e, r, n);
830
+ return `${R(o.left) ? `(${f})` : f} NOT BETWEEN ${G(o.right, e, r, n)}`;
831
+ }
832
+ if (o.type === "logical" || o.type === "not") {
833
+ const f = E(o, e, r + 1, n);
834
+ return `NOT (
835
+ ${i}${f}
836
+ ${s})`;
837
+ }
838
+ return `NOT ${E(o, e, r, n)}`;
839
+ }
840
+ case "if": {
841
+ const o = t.condition ? E(t.condition, e, r, n) : "??", f = t.then ? E(t.then, e, r, n) : "??", c = t.else ? E(t.else, e, r, n) : "NULL";
842
+ return e === "mysql" ? `IF(${o}, ${f}, ${c})` : e === "mssql" ? `IIF(${o}, ${f}, ${c})` : `CASE WHEN ${o} THEN ${f} ELSE ${c} END`;
843
+ }
844
+ case "case": {
845
+ const o = t.subject ? ` ${E(t.subject, e, r, n)}` : "", f = t.branches.map((u) => {
846
+ const l = E(u.when, e, r + 1, n), $ = E(u.then, e, r + 1, n);
847
+ return `${i}WHEN ${l} THEN ${$}`;
848
+ }).join(`
849
+ `), c = t.else ? `
850
+ ${i}ELSE ${E(t.else, e, r + 1, n)}` : "";
851
+ return `CASE${o}
852
+ ${f}${c}
853
+ ${s}END`;
854
+ }
855
+ // EXISTS (SELECT 1 FROM … WHERE <link> AND <where>): the subquery written
856
+ // in place, one level in, so its params fall in reading order.
857
+ case "exists": {
858
+ const { query: o, link: f } = t, c = ($) => $.type === "logical" && $.operator === "AND" ? $.operands : [$], u = o.where ? { type: "logical", operator: "AND", operands: [...c(f), ...c(o.where)] } : f;
859
+ return `EXISTS (
860
+ ${[
861
+ "SELECT 1",
862
+ // The clauses below write their expressions with formatNode.
863
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
864
+ ut(o.from, e),
865
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
866
+ ...o.joins.map(($) => ft($, e, n)),
867
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
868
+ it(u, e, n)
869
+ ].join(`
870
+ `).replace(/^/gm, i)}
871
+ ${s})`;
872
+ }
873
+ // IN's right side (issue 122): its query, on lines of its own, inside the
874
+ // parentheses IN writes around it.
875
+ // An empty list is unfinished, like a value not filled in.
876
+ case "list":
877
+ return `(${t.items.map((o) => E(o, e, r, n)).join(", ") || "??"})`;
878
+ case "subquery":
879
+ return `
880
+ ${_(t.query, e, n).join(`
881
+ `).replace(/^/gm, i)}
882
+ ${s}`;
883
+ default:
884
+ return "/* unknown */";
885
+ }
886
+ }
887
+ function it(t, e, r) {
888
+ return `WHERE
889
+ ${E(t, e, 1, r)}`;
890
+ }
891
+ const Zt = {
892
+ inner: "INNER JOIN",
893
+ left: "LEFT JOIN",
894
+ right: "RIGHT JOIN",
895
+ full: "FULL JOIN",
896
+ cross: "CROSS JOIN"
897
+ };
898
+ let ot = /* @__PURE__ */ new Map();
899
+ function at(t, e, r) {
900
+ return t.shared !== void 0 ? m(ot.get(t.shared) ?? "??", e) : t.query ? `(
901
+ ${ct(t.query, e, r).replace(/^/gm, " ")}
902
+ )` : m(t.table, e);
903
+ }
904
+ function ct(t, e, r) {
905
+ return gt(t).map((n) => _(n, e, r).join(`
906
+ `)).join(Dt(t) && !t.all ? `
907
+ UNION
908
+ ` : `
909
+ UNION ALL
910
+ `);
911
+ }
912
+ function te(t, e, r) {
913
+ return t.length === 0 ? [] : [`WITH
914
+ ${t.map((s) => T(s, () => {
915
+ const i = ct(s.query, e, r).replace(/^/gm, " ");
916
+ return ` ${m(s.name, e)} AS (
917
+ ${i}
918
+ )`;
919
+ })).join(`,
920
+ `)}`];
921
+ }
922
+ function ut(t, e, r) {
923
+ const n = t.alias ? ` AS ${m(t.alias, e)}` : "";
924
+ return `FROM ${T(t, () => `${at(t, e, r)}${n}`)}`;
925
+ }
926
+ function ft(t, e, r) {
927
+ return T(t, () => {
928
+ const n = at(t, e, r), s = t.alias ? ` AS ${m(t.alias, e)}` : "";
929
+ if (t.joinType === "cross") return `CROSS JOIN ${n}${s}`;
930
+ const i = t.on ? E(t.on, e, 1, r) : "/* unconfigured */";
931
+ return `${Zt[t.joinType]} ${n}${s}
932
+ ON ${i}`;
933
+ });
934
+ }
935
+ function ee(t, e, r, n = "SELECT") {
936
+ if (t.length === 0) return `${n} ${T(t, () => "*")}`;
937
+ const s = t.map((i) => T(i, () => {
938
+ const a = E(i.expression, e, 1, r), o = i.alias ? ` AS ${m(i.alias, e)}` : "";
939
+ return `${a}${o}`;
940
+ }));
941
+ return `${n}
942
+ ${s.join(`,
943
+ `)}`;
944
+ }
945
+ function re(t, e, r) {
946
+ return `GROUP BY
947
+ ${t.map((s) => T(
948
+ s,
949
+ () => E(s.expression, e, 1, r)
950
+ )).join(`,
951
+ `)}`;
952
+ }
953
+ function ne(t, e, r) {
954
+ return `HAVING
955
+ ${E(t, e, 1, r)}`;
956
+ }
957
+ function se(t, e, r, n) {
958
+ return `ORDER BY
959
+ ${t.map((i) => T(i, () => `${E(n(i.expression), e, 1, r)} ${i.direction === "desc" ? "DESC" : "ASC"}`)).join(`,
960
+ `)}`;
961
+ }
962
+ const B = (t) => t !== void 0 && Number.isInteger(t) && t >= 0 ? t : void 0;
963
+ function lt(t, e) {
964
+ const r = e.resolveName ? xt(t, e.resolveName) : t;
965
+ return e.defaultLimit !== void 0 && B(r.limit) === void 0 ? { ...r, limit: e.defaultLimit } : r;
966
+ }
967
+ const ie = "18446744073709551615";
968
+ function _(t, e, r, n = `SELECT${t.distinct ? " DISTINCT" : ""}`) {
969
+ const s = [
970
+ ee(t.select, e, r, n),
971
+ ut(t.from, e, r),
972
+ ...t.joins.map((a) => ft(a, e, r))
973
+ ];
974
+ t.where && s.push(it(t.where, e, r));
975
+ const i = t.groupBy ?? [];
976
+ if (i.length > 0 && s.push(re(i, e, r)), t.having) {
977
+ const a = e === "mysql" ? W(t.having, t) : t.having;
978
+ s.push(ne(a, e, r));
979
+ }
980
+ return s;
981
+ }
982
+ function $t(t, e, r) {
983
+ N && (N.writing = [{ value: t, path: [] }]), ot = new Map((t.shared ?? []).map((u) => [u.id, u.name]));
984
+ const n = te(t.shared ?? [], e, r), s = B(t.limit), i = B(t.offset) || void 0, a = t.orderBy ?? [], o = e === "mssql" && s !== void 0 && i === void 0, f = `SELECT${t.distinct ? " DISTINCT" : ""}${o ? ` ${T("limit", () => `TOP (${s})`)}` : ""}`, c = _(t, e, r, f);
985
+ if (a.length > 0 && c.push(se(a, e, r, (u) => e === "mysql" ? W(u, t) : u)), e === "mssql") {
986
+ if (i !== void 0) {
987
+ a.length === 0 && c.push("ORDER BY (SELECT NULL)");
988
+ const u = s !== void 0 ? ` ${T("limit", () => `FETCH NEXT ${s} ROWS ONLY`)}` : "";
989
+ c.push(`${T("offset", () => `OFFSET ${i} ROWS`)}${u}`);
990
+ }
991
+ } else if (s !== void 0 || i !== void 0) {
992
+ const u = s !== void 0 || e === "mysql" ? T(s !== void 0 ? "limit" : {}, () => `LIMIT ${s ?? ie}`) : "", l = i !== void 0 ? T("offset", () => `OFFSET ${i}`) : "";
993
+ c.push([u, l].filter(Boolean).join(" "));
994
+ }
995
+ return [...n, ...c].join(`
996
+ `);
997
+ }
998
+ function Ce(t, e, r = {}) {
999
+ const n = r.values ? Lt(t, r.values) : t, s = r.schema ? et(n, r.schema).query : n;
1000
+ return $t(lt(s, r), e);
1001
+ }
1002
+ function oe(t, e) {
1003
+ switch (t) {
1004
+ case "mysql":
1005
+ return "?";
1006
+ case "mssql":
1007
+ return `@p${e}`;
1008
+ case "postgres":
1009
+ return `$${e}`;
1010
+ default:
1011
+ return "?";
1012
+ }
1013
+ }
1014
+ function Le(t, e, r = {}) {
1015
+ const n = r.schema ? et(t, r.schema) : { query: t, params: /* @__PURE__ */ new Map() }, s = {
1016
+ values: [],
1017
+ named: new Map(Object.entries(r.values ?? {}).map(([c, u]) => {
1018
+ const l = n.params.get(c);
1019
+ return [c, l ? tt(u, l) : u];
1020
+ }))
1021
+ }, i = lt(n.query, r), a = $t(i, e, s), o = [];
1022
+ return { sql: a.replace(Xt, (c, u) => {
1023
+ const l = s.values[Number(u)];
1024
+ return o.push(l instanceof Date ? J(l) : l), oe(e, o.length);
1025
+ }), params: o };
1026
+ }
1027
+ export {
1028
+ Se as D,
1029
+ q as Q,
1030
+ wt as S,
1031
+ Le as a,
1032
+ Ce as b,
1033
+ Ut as c,
1034
+ Ae as d,
1035
+ Te as e,
1036
+ ge as f,
1037
+ pe as g,
1038
+ Y as h,
1039
+ Oe as i,
1040
+ Ee as j,
1041
+ Ne as k,
1042
+ me as l,
1043
+ De as m,
1044
+ h as n,
1045
+ Re as o,
1046
+ he as p,
1047
+ Ie as q,
1048
+ ye as r,
1049
+ le as s,
1050
+ $e as u,
1051
+ be as w
1052
+ };