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