@nongt/visql-core 0.10.1 → 0.12.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.
@@ -0,0 +1,941 @@
1
+ var qt = Object.defineProperty;
2
+ var Ut = (t, r, e) => r in t ? qt(t, r, { enumerable: !0, configurable: !0, writable: !0, value: e }) : t[r] = e;
3
+ var w = (t, r, e) => Ut(t, typeof r != "symbol" ? r + "" : r, e);
4
+ import { q as Y, d as F, a as Yt, s as _t, m as W, e as at, g as jt, t as Ht, j as vt, b as Bt, i as Pt } from "./schema-DsMO9oFE.js";
5
+ import { p as d, t as tt, v as Gt, w as xt, x as Xt, y as ft, z as kt, A as Vt } from "./params-Btjlj45_.js";
6
+ import { s as $t } from "./calendarDate-CYlr9TvX.js";
7
+ class Wt extends Error {
8
+ constructor(e, n, s, o) {
9
+ const u = o ? `"${n}" (as "${o}")` : `"${n}"`;
10
+ super(`scopeQuery: the query at ${e.length ? e.join(".") : "the top"} reads ${u} 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
+ w(this, "path");
14
+ /** The table it reads that needs scope. */
15
+ w(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
+ w(this, "alias");
19
+ this.name = "ScopeError", this.path = e, this.table = n, o && (this.alias = o);
20
+ }
21
+ }
22
+ const _ = (t) => Object.prototype.toString.call(t) === "[object Object]", lt = (t) => Array.isArray(t.joins) && _(t.from);
23
+ function q(t, r, e) {
24
+ if (Array.isArray(t)) {
25
+ const u = t.map((i, a) => q(i, [...r, a], e));
26
+ return u.every((i, a) => i === t[a]) ? t : u;
27
+ }
28
+ if (!_(t)) return t;
29
+ let n = !1;
30
+ const s = Object.entries(t).map(([u, i]) => {
31
+ const a = q(i, [...r, u], e);
32
+ return a !== i && (n = !0), [u, a];
33
+ }), o = n ? Object.fromEntries(s) : t;
34
+ return lt(o) ? e(o, r) : o;
35
+ }
36
+ const Et = (t, r) => Y(t).flatMap((e) => e.table !== void 0 && r.requires(e.table) ? [{ table: e.table, ...e.alias ? { alias: e.alias } : {}, ref: e.alias ?? e.table }] : []), Tt = (t) => Y(t).flatMap((r) => {
37
+ const e = r.alias ?? r.table;
38
+ return e === void 0 ? [] : [e];
39
+ });
40
+ function P(t, r) {
41
+ if (t.type === "field") {
42
+ const e = t.table && r.get(t.table);
43
+ return e ? { ...t, table: e } : t;
44
+ }
45
+ return W(t, (e) => P(e, r));
46
+ }
47
+ const At = (t) => t ? t.type === "logical" && t.operator === "AND" ? t.operands : [t] : [], Qt = (t) => t.joinType === "inner" || t.joinType === "left";
48
+ function Jt(t, r, e, n, s) {
49
+ const o = r.type === "binary" && r.left && r.right ? { ...r, left: r.right, right: r.left } : r, u = { forward: !1, back: !1 };
50
+ return t.joins.forEach((i) => {
51
+ const a = i.alias ?? i.table;
52
+ if (a !== e && a !== n || !Qt(i) || !At(i.on).some((f) => F(f, r) || F(f, o))) return;
53
+ const c = i.joinType === "inner";
54
+ a === e ? (u.forward = !0, u.back || (u.back = c)) : (u.back = !0, u.forward || (u.forward = c || s));
55
+ }), u;
56
+ }
57
+ const rt = (t) => t.some((r, e) => t.slice(0, e).every((n) => n.forward) && t.slice(e).every((n) => n.back)) || t.every((r) => r.forward);
58
+ function mt(t, r, e, n, s = new Set(Tt(r))) {
59
+ const o = tt(n.condition), u = Y(r), i = (a) => {
60
+ const c = /* @__PURE__ */ new Map([[e.table, e.ref]]), f = /* @__PURE__ */ new Map(), E = [], $ = new Set(s), A = (g) => {
61
+ const O = f.get(g);
62
+ return O ? [...A(O.ref), O.tie] : [];
63
+ }, y = (g, O, H) => {
64
+ if (O === g.length) return rt(A(c.get(H)));
65
+ const D = g[O], L = _t(t, [...c.keys()], D, { anyShape: !0 });
66
+ if (!L) return !1;
67
+ const J = c.get(tt(L.on).find((T) => T !== D)), z = (T) => P(L.on, new Map([...c, [D, T]])), K = o.includes(D), Z = (T, h) => {
68
+ c.set(D, T), f.set(T, { ref: J, tie: h });
69
+ }, Ft = (T, h) => (Z(T, h), rt(A(T)) && y(g, O + 1, H) ? !0 : (c.delete(D), f.delete(T), !1));
70
+ if (u.some((T) => {
71
+ if (T.table !== D) return !1;
72
+ const h = T.alias ?? D, v = Jt(r, z(h), J, h, K);
73
+ return (v.forward || v.back) && Ft(h, v);
74
+ })) return !0;
75
+ if (!a) return !1;
76
+ let p = D;
77
+ for (let T = 2; $.has(p); T += 1) p = `${D}_${T}`;
78
+ return $.add(p), Z(p, { back: !0, forward: L.joinType === "inner" || K }), E.push({
79
+ id: Gt(),
80
+ table: D,
81
+ ...p !== D ? { alias: p } : {},
82
+ joinType: L.joinType,
83
+ on: z(p)
84
+ }), y(g, O + 1, H);
85
+ };
86
+ let R;
87
+ if (o.every((g) => {
88
+ if (R || c.has(g)) return !0;
89
+ const O = Yt(t, [...c.keys()], g, { anyShape: !0 });
90
+ return O ? y(O, 0, g) : (R = g, !0);
91
+ }))
92
+ return $.forEach((g) => s.add(g)), { joins: E, condition: P(n.condition, c), ...R ? { missing: R } : {} };
93
+ };
94
+ return i(!1) ?? i(!0);
95
+ }
96
+ function gt(t, r) {
97
+ return At(t).some((e) => F(e, r));
98
+ }
99
+ function zt(t, r) {
100
+ return (t == null ? void 0 : t.type) === "logical" && t.operator === "AND" ? { ...t, operands: [...t.operands, r] } : t ? { type: "logical", operator: "AND", operands: [t, r] } : r;
101
+ }
102
+ function et(t, r, e, n, s) {
103
+ return Et(r, e).reduce((o, u) => {
104
+ const i = mt(t, o, u, e, s);
105
+ if (i.missing) throw new Wt(n, u.table, i.missing, u.alias);
106
+ const a = gt(o.where, i.condition);
107
+ return i.joins.length === 0 && a ? o : {
108
+ ...o,
109
+ joins: [...o.joins, ...i.joins],
110
+ where: a ? o.where : zt(o.where, i.condition)
111
+ };
112
+ }, r);
113
+ }
114
+ function nt(t) {
115
+ const r = /* @__PURE__ */ new Map(), e = (n, s, o, u) => {
116
+ if (Array.isArray(n)) {
117
+ n.forEach((a, c) => e(a, [...s, c], void 0, u));
118
+ return;
119
+ }
120
+ if (!_(n)) return;
121
+ let i = u;
122
+ lt(n) && (i = o ?? /* @__PURE__ */ new Set(), r.set(JSON.stringify(s), i), Tt(n).forEach((a) => i.add(a))), Object.entries(n).forEach(([a, c]) => e(
123
+ c,
124
+ [...s, a],
125
+ n.type === "exists" && a === "query" ? i : void 0,
126
+ i
127
+ ));
128
+ };
129
+ return e(t, [], void 0, /* @__PURE__ */ new Set()), r;
130
+ }
131
+ function Rr(t, r, e) {
132
+ const n = et(
133
+ t,
134
+ r,
135
+ e,
136
+ [],
137
+ nt(r).get("[]")
138
+ ), s = d(t, r, n), o = nt(s), u = q(s, [], (i, a) => a.length === 0 ? i : et(t, i, e, a, o.get(JSON.stringify(a))));
139
+ return d(t, s, u);
140
+ }
141
+ function pr(t, r, e) {
142
+ if (!_(t) || !Array.isArray(t.tables))
143
+ throw new TypeError("unscopedBodies takes (schema, query, rule) since 0.4.0");
144
+ const n = [];
145
+ return q(r, [], (s, o) => (Et(s, e).forEach((u) => {
146
+ const i = mt(t, s, u, e);
147
+ (i.missing || i.joins.length > 0 || !gt(s.where, i.condition)) && n.push({ path: o, table: u.table, ...u.alias ? { alias: u.alias } : {} });
148
+ }), s)), n;
149
+ }
150
+ function G(t, r) {
151
+ const e = new Map(r == null ? void 0 : r.tableOf), n = new Set(r == null ? void 0 : r.aliases), s = new Set(r == null ? void 0 : r.derived);
152
+ return t.forEach(({ table: o, alias: u }) => {
153
+ if (o === void 0) {
154
+ u && s.add(u);
155
+ return;
156
+ }
157
+ if (e.set(o, o), u) {
158
+ e.set(u, o), n.add(u), s.delete(u);
159
+ return;
160
+ }
161
+ n.delete(o), s.delete(o);
162
+ }), { tableOf: e, aliases: n, derived: s };
163
+ }
164
+ function Kt(t, r, e) {
165
+ const n = t.on && M(t.on, r, e);
166
+ return t.query ? { ...t, on: n, query: jt(t.query, (s) => j(s, e)) } : t.shared !== void 0 ? { ...t, on: n } : { ...t, on: n, table: e(t.table) };
167
+ }
168
+ function M(t, r, e) {
169
+ if (t.type === "field") {
170
+ if (!t.table || r.derived.has(t.table)) return t;
171
+ const n = r.tableOf.get(t.table) ?? t.table;
172
+ return {
173
+ ...t,
174
+ table: r.aliases.has(t.table) ? t.table : e(n),
175
+ ...t.column ? { column: e(n, t.column) } : {}
176
+ };
177
+ }
178
+ if (t.type === "subquery") return { ...t, query: j(t.query, e) };
179
+ if (t.type === "exists") {
180
+ const { query: n } = t, s = [n.from, ...n.joins], o = G(s), u = G(s, r);
181
+ return {
182
+ ...t,
183
+ link: M(t.link, u, e),
184
+ query: {
185
+ ...n,
186
+ from: { ...n.from, table: e(n.from.table) },
187
+ joins: n.joins.map((i) => Kt(i, o, e)),
188
+ ...n.where ? { where: M(n.where, o, e) } : {}
189
+ }
190
+ };
191
+ }
192
+ return W(t, (n) => M(n, r, e));
193
+ }
194
+ function j(t, r) {
195
+ const e = G([t.from, ...t.joins]), n = at(
196
+ t,
197
+ (s) => M(s, e, r),
198
+ (s) => j(s, r)
199
+ );
200
+ return {
201
+ ...n,
202
+ from: n.from.table === void 0 ? n.from : { ...n.from, table: r(n.from.table) },
203
+ joins: n.joins.map((s) => s.table === void 0 ? s : { ...s, table: r(s.table) })
204
+ };
205
+ }
206
+ function x(t, r) {
207
+ if (Array.isArray(t)) return t.map((s) => x(s, r));
208
+ if (typeof t != "object" || t === null || t instanceof Date) return t;
209
+ const e = Object.fromEntries(Object.entries(t).map(
210
+ ([s, o]) => [s, x(o, r)]
211
+ ));
212
+ if (!("from" in e) || !Array.isArray(e.joins)) return e;
213
+ const n = (s) => s.table !== void 0 && !s.alias && r(s.table) !== s.table ? { ...s, alias: s.table } : s;
214
+ return {
215
+ ...e,
216
+ from: n(e.from),
217
+ joins: e.joins.map(n)
218
+ };
219
+ }
220
+ function Zt(t, r) {
221
+ return j(x(t, r), r);
222
+ }
223
+ const dt = /^(\d{2}):(\d{2})(?::(\d{2}))?$/, st = /YYYY|MM|DD|HH|mm|ss/g, b = (t, r = 2) => String(t).padStart(r, "0");
224
+ function yt(t, r) {
225
+ let e;
226
+ const n = typeof t == "string" ? dt.exec(t.trim()) : null;
227
+ if (n)
228
+ e = { HH: n[1], mm: n[2], ss: n[3] ?? "00" };
229
+ else {
230
+ const u = typeof t == "string" ? xt(t, "dateTime") : t;
231
+ u instanceof Date && (e = {
232
+ YYYY: b(u.getUTCFullYear(), 4),
233
+ MM: b(u.getUTCMonth() + 1),
234
+ DD: b(u.getUTCDate()),
235
+ HH: b(u.getUTCHours()),
236
+ mm: b(u.getUTCMinutes()),
237
+ ss: b(u.getUTCSeconds())
238
+ });
239
+ }
240
+ if (!e) return t;
241
+ const s = e;
242
+ return (r.match(st) ?? []).some((u) => s[u] === void 0) ? t : r.replace(st, (u) => s[u]);
243
+ }
244
+ function Dt(t, r) {
245
+ const e = /* @__PURE__ */ new Map(), n = (s) => {
246
+ const o = /* @__PURE__ */ new Map();
247
+ Y(s).forEach((c) => o.set(Ht(c), c.table));
248
+ const u = (c) => {
249
+ if ((c == null ? void 0 : c.type) !== "field" || !c.table || !c.column) return;
250
+ const f = o.has(c.table) ? o.get(c.table) : c.table, E = f === void 0 ? void 0 : vt(r, f), $ = E == null ? void 0 : E.columns.find((A) => A.name === c.column);
251
+ return $ == null ? void 0 : $.format;
252
+ }, i = (c, f) => {
253
+ switch (c.type) {
254
+ case "literal":
255
+ return { ...c, value: yt(c.value, f) };
256
+ case "list":
257
+ return { ...c, items: c.items.map((E) => i(E, f)) };
258
+ case "param":
259
+ return e.has(c.name) || e.set(c.name, f), c;
260
+ default:
261
+ return c;
262
+ }
263
+ }, a = (c) => {
264
+ if (c.type === "subquery") return { ...c, query: n(c.query) };
265
+ const f = W(c, a);
266
+ if (f.type !== "binary" || !f.right) return f;
267
+ const E = u(f.left), $ = u(f.right);
268
+ return {
269
+ ...f,
270
+ left: $ ? i(f.left, $) : f.left,
271
+ right: E ? i(f.right, E) : f.right
272
+ };
273
+ };
274
+ return at(s, a, (c) => n(c));
275
+ };
276
+ return { query: n(t), params: e };
277
+ }
278
+ const hr = ["mysql", "mssql", "postgres"], Ir = {
279
+ mysql: "MySQL",
280
+ mssql: "SQL Server",
281
+ postgres: "PostgreSQL"
282
+ };
283
+ function N(t, r) {
284
+ const e = t.replace(/[\uE000-\uE003]/g, "");
285
+ switch (r) {
286
+ case "mysql":
287
+ return `\`${e.replace(/`/g, "``")}\``;
288
+ case "mssql":
289
+ return `[${e.replace(/]/g, "]]")}]`;
290
+ case "postgres":
291
+ return `"${e.replace(/"/g, '""')}"`;
292
+ default:
293
+ return `"${e.replace(/"/g, '""')}"`;
294
+ }
295
+ }
296
+ const tr = /^[A-Za-z_][A-Za-z0-9_]*$/, Ot = (t) => `${t}`, rr = /\uE000(\d+)\uE000/g;
297
+ let C;
298
+ function Cr(t, r) {
299
+ C = { ...t, writing: [] };
300
+ try {
301
+ return r();
302
+ } finally {
303
+ C = void 0;
304
+ }
305
+ }
306
+ function St(t, r, e) {
307
+ if (typeof t != "object" || t === null || t instanceof Date) return;
308
+ let n;
309
+ return Object.entries(t).some(([s, o]) => {
310
+ const u = [...e, Array.isArray(t) ? Number(s) : s];
311
+ return n = o === r ? u : St(o, r, u), n !== void 0;
312
+ }), n;
313
+ }
314
+ function m(t, r) {
315
+ if (!C) return r();
316
+ const { writing: e, paths: n } = C, s = e[e.length - 1], o = typeof t == "string" ? [t] : St(s.value, t, s.path);
317
+ if (!o) return r();
318
+ e.push({ value: t, path: o });
319
+ try {
320
+ return `${n.push(o) - 1}${r()}`;
321
+ } finally {
322
+ e.pop();
323
+ }
324
+ }
325
+ const er = {
326
+ mysql: {
327
+ text: "CHAR",
328
+ integer: "SIGNED",
329
+ number: "DECIMAL(38, 10)",
330
+ date: "DATE",
331
+ dateTime: "DATETIME",
332
+ time: "TIME",
333
+ boolean: "SIGNED"
334
+ },
335
+ mssql: {
336
+ text: "NVARCHAR(MAX)",
337
+ integer: "BIGINT",
338
+ number: "DECIMAL(38, 10)",
339
+ date: "DATE",
340
+ dateTime: "DATETIME2",
341
+ time: "TIME",
342
+ boolean: "BIT"
343
+ },
344
+ postgres: {
345
+ text: "text",
346
+ integer: "bigint",
347
+ number: "numeric",
348
+ date: "date",
349
+ dateTime: "timestamp",
350
+ time: "time",
351
+ boolean: "boolean"
352
+ }
353
+ };
354
+ function nr(t, r) {
355
+ var n;
356
+ const e = (n = er[r]) == null ? void 0 : n[t];
357
+ return e ? r === "postgres" ? `NULL::${e}` : `CAST(NULL AS ${e})` : "NULL";
358
+ }
359
+ function Nt(t, r, e) {
360
+ if (t == null) return "NULL";
361
+ if (e)
362
+ return e.values.push(t), Ot(e.values.length - 1);
363
+ if (typeof t == "boolean")
364
+ return r === "mssql" ? t ? "1" : "0" : t ? "TRUE" : "FALSE";
365
+ if (typeof t == "string") {
366
+ const n = C ? t.replace(/[\uE001-\uE003]/g, "") : t;
367
+ return n === "" ? "''" : `'${n.replace(/'/g, "''")}'`;
368
+ }
369
+ return typeof t == "number" || typeof t == "bigint" ? String(t) : t instanceof Date ? `'${$t(t)}'` : String(t);
370
+ }
371
+ let U = "native", X = "decimal";
372
+ function Rt(t, r) {
373
+ U = t.nullSafeEqual ?? "native", X = t.division ?? "decimal";
374
+ try {
375
+ return r();
376
+ } finally {
377
+ U = "native", X = "decimal";
378
+ }
379
+ }
380
+ function sr(t, r) {
381
+ switch (t) {
382
+ case "!=":
383
+ return r === "mssql" ? "<>" : "!=";
384
+ case "IS NOT DISTINCT FROM":
385
+ return r === "mysql" ? "<=>" : t;
386
+ case "REGEXP":
387
+ if (r === "postgres") return "~";
388
+ if (r === "mssql") throw new Error("REGEXP isn't available in SQL Server");
389
+ return "REGEXP";
390
+ default:
391
+ if (!Vt.includes(t))
392
+ throw new Error(`unknown operator ${JSON.stringify(t)}`);
393
+ return t;
394
+ }
395
+ }
396
+ function I(t) {
397
+ return (t == null ? void 0 : t.type) === "literal" && typeof t.value == "string" && /^[A-Za-z_]+$/.test(t.value) ? t.value.toUpperCase() : "DAY";
398
+ }
399
+ const B = {
400
+ YEAR: "year",
401
+ QUARTER: "quarter",
402
+ MONTH: "month",
403
+ WEEK: "week",
404
+ DAY: "day",
405
+ HOUR: "hour",
406
+ MINUTE: "minute",
407
+ SECOND: "second",
408
+ MILLISECOND: "millisecond"
409
+ };
410
+ function S(t) {
411
+ return t.type === "binary" || t.type === "logical" || t.type === "if" || t.type === "case";
412
+ }
413
+ const ot = (t, r) => (r == null ? void 0 : r.type) === "arithmetic" || r && S(r) ? `(${t})` : t;
414
+ function it(t, [r = "??", , e], n) {
415
+ if (n.length < 2) return `${t}(${r})`;
416
+ const s = n[1], o = s.type === "literal" && Number.isInteger(s.value) && s.value >= 0 ? String(s.value) : "??";
417
+ return `${t}(${r}, ${o}${e === void 0 ? "" : `, ${e}`})`;
418
+ }
419
+ const or = {
420
+ // SQL Server has no MOD(), only `%`.
421
+ MOD: ([t = "??", r = "??"], e, n) => n === "mssql" ? `(${ot(t, e[0])} % ${ot(r, e[1])})` : `MOD(${t}, ${r})`,
422
+ // ---- Date arithmetic ----
423
+ DATE_ADD: ([t, r], e, n, s) => {
424
+ var u;
425
+ const o = I(e[2]);
426
+ switch (n) {
427
+ case "mysql":
428
+ return o === "MILLISECOND" ? `DATE_ADD(${t}, INTERVAL (${r}) * 1000 MICROSECOND)` : `DATE_ADD(${t}, INTERVAL ${r} ${o})`;
429
+ case "postgres": {
430
+ const i = B[o] ?? o.toLowerCase();
431
+ return !s && ((u = e[1]) == null ? void 0 : u.type) === "literal" && typeof e[1].value == "number" ? `(${t} + INTERVAL '${e[1].value} ${i}')` : `(${t} + (${r} * INTERVAL '1 ${i}'))`;
432
+ }
433
+ case "mssql":
434
+ return `DATEADD(${o}, ${r}, ${t})`;
435
+ default:
436
+ return `DATE_ADD(${t}, ${r}, ${I(e[2])})`;
437
+ }
438
+ },
439
+ DATE_SUB: ([t, r], e, n, s) => {
440
+ var u;
441
+ const o = I(e[2]);
442
+ switch (n) {
443
+ case "mysql":
444
+ return o === "MILLISECOND" ? `DATE_SUB(${t}, INTERVAL (${r}) * 1000 MICROSECOND)` : `DATE_SUB(${t}, INTERVAL ${r} ${o})`;
445
+ case "postgres": {
446
+ const i = B[o] ?? o.toLowerCase();
447
+ return !s && ((u = e[1]) == null ? void 0 : u.type) === "literal" && typeof e[1].value == "number" ? `(${t} - INTERVAL '${e[1].value} ${i}')` : `(${t} - (${r} * INTERVAL '1 ${i}'))`;
448
+ }
449
+ case "mssql":
450
+ return `DATEADD(${o}, -(${r}), ${t})`;
451
+ default:
452
+ return `DATE_SUB(${t}, ${r}, ${I(e[2])})`;
453
+ }
454
+ },
455
+ // ---- Date diff ----
456
+ DATEDIFF: ([t, r], e, n) => {
457
+ const s = I(e[2]);
458
+ switch (n) {
459
+ case "mysql":
460
+ return `TIMESTAMPDIFF(${s}, ${t}, ${r})`;
461
+ case "mssql":
462
+ return `DATEDIFF(${s}, ${t}, ${r})`;
463
+ case "postgres":
464
+ switch (s) {
465
+ case "YEAR":
466
+ return `EXTRACT(YEAR FROM age(${r}, ${t}))::integer`;
467
+ case "QUARTER": {
468
+ const o = `EXTRACT(YEAR FROM age(${r}, ${t}))`, u = `EXTRACT(MONTH FROM age(${r}, ${t}))`;
469
+ return `FLOOR((${o} * 12 + ${u}) / 3)::integer`;
470
+ }
471
+ case "MONTH": {
472
+ const o = `EXTRACT(YEAR FROM age(${r}, ${t}))`, u = `EXTRACT(MONTH FROM age(${r}, ${t}))`;
473
+ return `(${o} * 12 + ${u})::integer`;
474
+ }
475
+ case "WEEK":
476
+ return `FLOOR((${r}::date - ${t}::date) / 7)`;
477
+ case "DAY":
478
+ return `(${r}::date - ${t}::date)`;
479
+ case "HOUR":
480
+ return `FLOOR(EXTRACT(EPOCH FROM (${r} - ${t})) / 3600)::integer`;
481
+ case "MINUTE":
482
+ return `FLOOR(EXTRACT(EPOCH FROM (${r} - ${t})) / 60)::integer`;
483
+ case "SECOND":
484
+ return `FLOOR(EXTRACT(EPOCH FROM (${r} - ${t})))::integer`;
485
+ case "MILLISECOND":
486
+ return `FLOOR(EXTRACT(EPOCH FROM (${r} - ${t})) * 1000)::integer`;
487
+ default:
488
+ return `/* unknown unit: ${s} */`;
489
+ }
490
+ default:
491
+ return `DATEDIFF(${t}, ${r}, ${s})`;
492
+ }
493
+ },
494
+ // ---- Date extract ----
495
+ EXTRACT: ([t], r, e) => {
496
+ const n = I(r[1]);
497
+ switch (e) {
498
+ case "mysql":
499
+ return n === "MILLISECOND" ? `FLOOR(MICROSECOND(${t}) / 1000)` : `EXTRACT(${n} FROM ${t})`;
500
+ case "postgres":
501
+ return n === "MILLISECOND" ? `EXTRACT(MILLISECONDS FROM ${t})::integer` : `EXTRACT(${n} FROM ${t})`;
502
+ case "mssql":
503
+ return `DATEPART(${n}, ${t})`;
504
+ default:
505
+ return `EXTRACT(${t}, ${n})`;
506
+ }
507
+ },
508
+ // ---- Date truncation ----
509
+ DATE_TRUNC: ([t], r, e) => {
510
+ const n = I(r[1]);
511
+ switch (e) {
512
+ case "mysql":
513
+ switch (n) {
514
+ case "YEAR":
515
+ return `DATE_FORMAT(${t}, '%Y-01-01')`;
516
+ case "QUARTER":
517
+ return `MAKEDATE(YEAR(${t}), 1) + INTERVAL (QUARTER(${t}) - 1) QUARTER`;
518
+ case "MONTH":
519
+ return `DATE_FORMAT(${t}, '%Y-%m-01')`;
520
+ case "WEEK":
521
+ return `DATE_SUB(DATE(${t}), INTERVAL WEEKDAY(${t}) DAY)`;
522
+ case "DAY":
523
+ return `DATE(${t})`;
524
+ case "HOUR":
525
+ return `DATE_FORMAT(${t}, '%Y-%m-%d %H:00:00')`;
526
+ case "MINUTE":
527
+ return `DATE_FORMAT(${t}, '%Y-%m-%d %H:%i:00')`;
528
+ case "SECOND":
529
+ return `DATE_FORMAT(${t}, '%Y-%m-%d %H:%i:%s')`;
530
+ case "MILLISECOND":
531
+ return `DATE_FORMAT(${t}, '%Y-%m-%d %H:%i:%s.000')`;
532
+ default:
533
+ return `/* unknown unit: ${n} */`;
534
+ }
535
+ case "postgres":
536
+ return `DATE_TRUNC('${B[n] ?? n.toLowerCase()}', ${t})`;
537
+ case "mssql":
538
+ switch (n) {
539
+ case "YEAR":
540
+ return `DATEFROMPARTS(YEAR(${t}), 1, 1)`;
541
+ case "QUARTER":
542
+ return `DATEFROMPARTS(YEAR(${t}), (DATEPART(QUARTER, ${t}) - 1) * 3 + 1, 1)`;
543
+ case "MONTH":
544
+ return `DATEFROMPARTS(YEAR(${t}), MONTH(${t}), 1)`;
545
+ case "WEEK": {
546
+ const s = `CAST(${t} AS DATE)`;
547
+ return `DATEADD(DAY, -(DATEDIFF(DAY, 0, ${s}) % 7), ${s})`;
548
+ }
549
+ case "DAY":
550
+ return `CAST(${t} AS DATE)`;
551
+ case "HOUR":
552
+ return `DATEADD(HOUR, DATEDIFF(HOUR, 0, ${t}), 0)`;
553
+ case "MINUTE":
554
+ return `DATEADD(MINUTE, DATEDIFF(MINUTE, 0, ${t}), 0)`;
555
+ case "SECOND":
556
+ return `DATEADD(SECOND, DATEDIFF(SECOND, '2000-01-01', ${t}), '2000-01-01')`;
557
+ case "MILLISECOND": {
558
+ const s = `CAST(${t} AS DATE)`;
559
+ return `DATEADD(MILLISECOND, DATEDIFF(MILLISECOND, ${s}, ${t}), ${s})`;
560
+ }
561
+ default:
562
+ return `/* unknown unit: ${n} */`;
563
+ }
564
+ default:
565
+ return `DATE_TRUNC(${t}, ${n})`;
566
+ }
567
+ },
568
+ // ---- Type cast ----
569
+ /**
570
+ * CAST(expr, type_name) — type_name is stored as a string literal.
571
+ * Renders as CAST(expr AS type_name) for all dialects.
572
+ */
573
+ CAST: ([t], r) => {
574
+ const e = r[1], n = (e == null ? void 0 : e.type) === "literal" && typeof e.value == "string" && /^[A-Za-z][A-Za-z0-9_ ]*(\(\s*\d+\s*(,\s*\d+\s*)?\))?$/.test(e.value) ? e.value : "??";
575
+ return `CAST(${t} AS ${n})`;
576
+ },
577
+ // ---- Window functions (issue 20) ----
578
+ // The offset goes into the SQL as a whole number even in parameterized
579
+ // SQL: MySQL takes nothing else there. OVER is added by formatNode.
580
+ LAG: (t, r) => it("LAG", t, r),
581
+ LEAD: (t, r) => it("LEAD", t, r),
582
+ // ---- String aggregation (issue 137) ----
583
+ // The separator goes into the SQL as a literal even in parameterized SQL:
584
+ // MySQL's SEPARATOR takes nothing else.
585
+ STRING_AGG: ([t = "??"], r, e, n, s, o) => {
586
+ const u = r[1] ?? { type: "literal", value: ", " }, i = u.type === "literal" && typeof u.value == "string" ? Nt(u.value, e) : "??", a = s.distinct ? "DISTINCT " : "", c = ($) => {
587
+ var A;
588
+ return (A = s.orderBy) != null && A.length ? `ORDER BY ${s.orderBy.map((y) => `${$(y)} ${y.direction === "desc" ? "DESC" : "ASC"}`).join(", ")}` : "";
589
+ }, f = ($) => o($.expression), E = ($) => $ ? ` ${$}` : "";
590
+ switch (e) {
591
+ case "mysql":
592
+ return `GROUP_CONCAT(${a}${t}${E(c(f))} SEPARATOR ${i})`;
593
+ case "postgres": {
594
+ const $ = `CAST(${t} AS TEXT)`, A = c((y) => {
595
+ if (!s.distinct) return f(y);
596
+ if (F(y.expression, r[0])) return $;
597
+ throw new Error("PostgreSQL orders STRING_AGG of different values by the value only");
598
+ });
599
+ return `STRING_AGG(${a}${$}, ${i}${E(A)})`;
600
+ }
601
+ case "mssql": {
602
+ if (s.distinct)
603
+ throw new Error("SQL Server's STRING_AGG can't join only different values");
604
+ const $ = c(f), A = $ ? ` WITHIN GROUP (${$})` : "";
605
+ return `STRING_AGG(CAST(${t} AS NVARCHAR(MAX)), ${i})${A}`;
606
+ }
607
+ default:
608
+ return `STRING_AGG(${a}${t}, ${i}${E(c(f))})`;
609
+ }
610
+ }
611
+ };
612
+ function ir(t, r) {
613
+ var n, s;
614
+ return `OVER (${[
615
+ ...(n = t.partitionBy) != null && n.length ? [`PARTITION BY ${t.partitionBy.map(r).join(", ")}`] : [],
616
+ ...(s = t.orderBy) != null && s.length ? [`ORDER BY ${t.orderBy.map((o) => `${r(o.expression)} ${o.direction === "desc" ? "DESC" : "ASC"}`).join(", ")}`] : []
617
+ ].join(" ")})`;
618
+ }
619
+ function l(t, r, e, n) {
620
+ return m(t, () => ar(t, r, e, n));
621
+ }
622
+ function ur(t, r, e, n) {
623
+ const s = t.args.map((a) => l(a, r, e, n)), o = or[t.name.toUpperCase()];
624
+ if (o)
625
+ return o(
626
+ s,
627
+ t.args,
628
+ r,
629
+ n !== void 0,
630
+ t,
631
+ (a) => l(a, r, e, n)
632
+ );
633
+ const u = /^[A-Za-z_][A-Za-z0-9_.]*$/.test(t.name) || t.name === "" ? t.name : "??";
634
+ if (s.length === 0 && u.toUpperCase() === "COUNT") return `${u}(*)`;
635
+ const i = t.distinct && s.length > 0 ? "DISTINCT " : "";
636
+ return `${u}(${i}${s.join(", ")})`;
637
+ }
638
+ function ut(t, r, e, n) {
639
+ const s = (o) => {
640
+ if (!o) return "??";
641
+ const u = l(o, r, e, n);
642
+ return S(o) ? `(${u})` : u;
643
+ };
644
+ return m(t, () => {
645
+ const [o, u] = t.type === "list" ? t.items : [t];
646
+ return `${s(o)} AND ${s(u)}`;
647
+ });
648
+ }
649
+ const k = {
650
+ "+": 1,
651
+ "-": 1,
652
+ "*": 2,
653
+ "/": 2
654
+ };
655
+ function ct(t, r, e, n, s, o) {
656
+ const u = l(t, n, s, o);
657
+ return t.type === "arithmetic" && (k[t.operator] < r || e && k[t.operator] === r) || S(t) ? `(${u})` : u;
658
+ }
659
+ function cr(t, r, e, n) {
660
+ const s = k[t.operator], o = ct(t.left, s, !1, r, e, n), u = ct(t.right, s, !0, r, e, n);
661
+ return t.operator === "/" && X === "decimal" && r !== "mysql" ? `${o} * 1.0 / ${u}` : `${o} ${t.operator} ${u}`;
662
+ }
663
+ function ar(t, r, e, n) {
664
+ var u;
665
+ const s = " ".repeat(e), o = " ".repeat(e + 1);
666
+ switch (t.type) {
667
+ case "literal":
668
+ return t.value === "" && !t.empty ? "??" : t.value === null && t.as ? nr(t.as, r) : Nt(t.value, r, n);
669
+ case "param": {
670
+ if (!n) return tr.test(t.name) ? `:${t.name}` : "??";
671
+ if (!n.named.has(t.name))
672
+ throw new Error(`no value for parameter "${t.name}"`);
673
+ return n.values.push(n.named.get(t.name)), Ot(n.values.length - 1);
674
+ }
675
+ case "field": {
676
+ if (!t.column) return "??";
677
+ const i = N(t.column, r);
678
+ return t.table ? `${N(t.table, r)}.${i}` : i;
679
+ }
680
+ case "function": {
681
+ const i = ur(t, r, e, n);
682
+ return t.over ? `${i} ${ir(t, (a) => l(a, r, e, n))}` : i;
683
+ }
684
+ case "binary": {
685
+ const i = t.operator ? sr(t.operator, r) : "=", a = l(t.left, r, e, n), c = S(t.left) ? `(${a})` : a;
686
+ if (kt(t.operator)) return `${c} ${i}`;
687
+ if (!t.right) return `${c} ${i} ??`;
688
+ if (i === "BETWEEN")
689
+ return `${c} BETWEEN ${ut(t.right, r, e, n)}`;
690
+ if (i === "IN")
691
+ return t.right.type === "list" ? `${c} IN ${l(t.right, r, e, n)}` : `${c} IN (${l(t.right, r, e, n)})`;
692
+ const f = l(t.right, r, e, n), E = S(t.right) ? `(${f})` : f;
693
+ if (t.operator === "IS NOT DISTINCT FROM" && U === "expanded") {
694
+ const $ = (y) => {
695
+ const R = l(y, r, e, n);
696
+ return S(y) ? `(${R})` : R;
697
+ }, A = `${$(t.left)} IS NULL AND ${$(t.right)} IS NULL`;
698
+ return `(${c} = ${E} OR (${A}))`;
699
+ }
700
+ return `${c} ${i} ${E}`;
701
+ }
702
+ case "arithmetic":
703
+ return cr(t, r, e, n);
704
+ case "logical": {
705
+ if (t.operands.length === 0) return "/* empty */";
706
+ if (t.operands.length === 1)
707
+ return l(t.operands[0], r, e, n);
708
+ if (t.operator !== "AND" && t.operator !== "OR")
709
+ throw new Error(`unknown operator ${JSON.stringify(t.operator)}`);
710
+ const i = `
711
+ ${s}${t.operator} `;
712
+ return t.operands.map((a) => {
713
+ if (a.type === "logical") {
714
+ const c = l(a, r, e + 1, n);
715
+ return `(
716
+ ${o}${c}
717
+ ${s})`;
718
+ }
719
+ return l(a, r, e, n);
720
+ }).join(i);
721
+ }
722
+ case "not": {
723
+ const { operand: i } = t;
724
+ if (i.type === "binary" && i.operator === "IN" && ((u = i.right) == null ? void 0 : u.type) === "subquery") {
725
+ const a = l(i.left, r, e, n);
726
+ return `${S(i.left) ? `(${a})` : a} NOT IN (${l(i.right, r, e, n)})`;
727
+ }
728
+ if (i.type === "binary" && i.operator === "BETWEEN" && i.right) {
729
+ const a = l(i.left, r, e, n);
730
+ return `${S(i.left) ? `(${a})` : a} NOT BETWEEN ${ut(i.right, r, e, n)}`;
731
+ }
732
+ if (i.type === "binary" && i.operator === "IS NOT DISTINCT FROM" && i.right && U === "native") {
733
+ if (r === "mysql") return `NOT (${l(i, r, e, n)})`;
734
+ const a = l(i.left, r, e, n), c = S(i.left) ? `(${a})` : a, f = l(i.right, r, e, n), E = S(i.right) ? `(${f})` : f;
735
+ return `${c} IS DISTINCT FROM ${E}`;
736
+ }
737
+ if (i.type === "logical" || i.type === "not") {
738
+ const a = l(i, r, e + 1, n);
739
+ return `NOT (
740
+ ${o}${a}
741
+ ${s})`;
742
+ }
743
+ return `NOT ${l(i, r, e, n)}`;
744
+ }
745
+ case "if": {
746
+ const i = t.condition ? l(t.condition, r, e, n) : "??", a = t.then ? l(t.then, r, e, n) : "??", c = t.else ? l(t.else, r, e, n) : "NULL";
747
+ return r === "mysql" ? `IF(${i}, ${a}, ${c})` : r === "mssql" ? `IIF(${i}, ${a}, ${c})` : `CASE WHEN ${i} THEN ${a} ELSE ${c} END`;
748
+ }
749
+ case "case": {
750
+ const i = t.subject ? ` ${l(t.subject, r, e, n)}` : "", a = t.branches.map((f) => {
751
+ const E = l(f.when, r, e + 1, n), $ = l(f.then, r, e + 1, n);
752
+ return `${o}WHEN ${E} THEN ${$}`;
753
+ }).join(`
754
+ `), c = t.else ? `
755
+ ${o}ELSE ${l(t.else, r, e + 1, n)}` : "";
756
+ return `CASE${i}
757
+ ${a}${c}
758
+ ${s}END`;
759
+ }
760
+ // EXISTS (SELECT 1 FROM … WHERE <link> AND <where>): the subquery written
761
+ // in place, one level in, so its params fall in reading order.
762
+ case "exists": {
763
+ const { query: i, link: a } = t, c = ($) => $.type === "logical" && $.operator === "AND" ? $.operands : [$], f = i.where ? { type: "logical", operator: "AND", operands: [...c(a), ...c(i.where)] } : a;
764
+ return `EXISTS (
765
+ ${[
766
+ "SELECT 1",
767
+ // The clauses below write their expressions with formatNode.
768
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
769
+ bt(i.from, r),
770
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
771
+ ...i.joins.map(($) => Lt($, r, n)),
772
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
773
+ pt(f, r, n)
774
+ ].join(`
775
+ `).replace(/^/gm, o)}
776
+ ${s})`;
777
+ }
778
+ // IN's right side (issue 122): its query, on lines of its own, inside the
779
+ // parentheses IN writes around it.
780
+ // An empty list is unfinished, like a value not filled in.
781
+ case "list":
782
+ return `(${t.items.map((i) => l(i, r, e, n)).join(", ") || "??"})`;
783
+ case "subquery":
784
+ return `
785
+ ${Q(t.query, r, n).join(`
786
+ `).replace(/^/gm, o)}
787
+ ${s}`;
788
+ default:
789
+ return "/* unknown */";
790
+ }
791
+ }
792
+ function pt(t, r, e) {
793
+ return `WHERE
794
+ ${l(t, r, 1, e)}`;
795
+ }
796
+ const fr = {
797
+ inner: "INNER JOIN",
798
+ left: "LEFT JOIN",
799
+ right: "RIGHT JOIN",
800
+ full: "FULL JOIN",
801
+ cross: "CROSS JOIN"
802
+ };
803
+ let ht = /* @__PURE__ */ new Map();
804
+ function It(t, r, e) {
805
+ return t.shared !== void 0 ? N(ht.get(t.shared) ?? "??", r) : t.query ? `(
806
+ ${Ct(t.query, r, e).replace(/^/gm, " ")}
807
+ )` : N(t.table, r);
808
+ }
809
+ function Ct(t, r, e) {
810
+ return Bt(t).map((n) => Q(n, r, e).join(`
811
+ `)).join(Pt(t) && !t.all ? `
812
+ UNION
813
+ ` : `
814
+ UNION ALL
815
+ `);
816
+ }
817
+ function $r(t, r, e) {
818
+ return t.length === 0 ? [] : [`WITH
819
+ ${t.map((s) => m(s, () => {
820
+ const o = Ct(s.query, r, e).replace(/^/gm, " ");
821
+ return ` ${N(s.name, r)} AS (
822
+ ${o}
823
+ )`;
824
+ })).join(`,
825
+ `)}`];
826
+ }
827
+ function bt(t, r, e) {
828
+ const n = t.alias ? ` AS ${N(t.alias, r)}` : "";
829
+ return `FROM ${m(t, () => `${It(t, r, e)}${n}`)}`;
830
+ }
831
+ function Lt(t, r, e) {
832
+ return m(t, () => {
833
+ const n = It(t, r, e), s = t.alias ? ` AS ${N(t.alias, r)}` : "";
834
+ if (t.joinType === "cross") return `CROSS JOIN ${n}${s}`;
835
+ const o = t.on ? l(t.on, r, 1, e) : "/* unconfigured */";
836
+ return `${fr[t.joinType]} ${n}${s}
837
+ ON ${o}`;
838
+ });
839
+ }
840
+ function lr(t, r, e, n = "SELECT") {
841
+ if (t.length === 0) return `${n} ${m(t, () => "*")}`;
842
+ const s = t.map((o) => m(o, () => {
843
+ const u = l(o.expression, r, 1, e), i = o.alias ? ` AS ${N(o.alias, r)}` : "";
844
+ return `${u}${i}`;
845
+ }));
846
+ return `${n}
847
+ ${s.join(`,
848
+ `)}`;
849
+ }
850
+ function Er(t, r, e) {
851
+ return `GROUP BY
852
+ ${t.map((s) => m(
853
+ s,
854
+ () => l(s.expression, r, 1, e)
855
+ )).join(`,
856
+ `)}`;
857
+ }
858
+ function Tr(t, r, e) {
859
+ return `HAVING
860
+ ${l(t, r, 1, e)}`;
861
+ }
862
+ function Ar(t, r, e, n) {
863
+ return `ORDER BY
864
+ ${t.map((o) => m(o, () => `${l(n(o.expression), r, 1, e)} ${o.direction === "desc" ? "DESC" : "ASC"}`)).join(`,
865
+ `)}`;
866
+ }
867
+ const V = (t) => t !== void 0 && Number.isInteger(t) && t >= 0 ? t : void 0;
868
+ function Mt(t, r) {
869
+ const e = r.resolveName ? Zt(t, r.resolveName) : t;
870
+ return r.defaultLimit !== void 0 && V(e.limit) === void 0 ? { ...e, limit: r.defaultLimit } : e;
871
+ }
872
+ const mr = "18446744073709551615";
873
+ function Q(t, r, e, n = `SELECT${t.distinct ? " DISTINCT" : ""}`) {
874
+ const s = [
875
+ lr(t.select, r, e, n),
876
+ bt(t.from, r, e),
877
+ ...t.joins.map((u) => Lt(u, r, e))
878
+ ];
879
+ t.where && s.push(pt(t.where, r, e));
880
+ const o = t.groupBy ?? [];
881
+ if (o.length > 0 && s.push(Er(o, r, e)), t.having) {
882
+ const u = r === "mysql" ? ft(t.having, t) : t.having;
883
+ s.push(Tr(u, r, e));
884
+ }
885
+ return s;
886
+ }
887
+ function wt(t, r, e) {
888
+ C && (C.writing = [{ value: t, path: [] }]), ht = new Map((t.shared ?? []).map((f) => [f.id, f.name]));
889
+ const n = $r(t.shared ?? [], r, e), s = V(t.limit), o = V(t.offset) || void 0, u = t.orderBy ?? [], i = r === "mssql" && s !== void 0 && o === void 0, a = `SELECT${t.distinct ? " DISTINCT" : ""}${i ? ` ${m("limit", () => `TOP (${s})`)}` : ""}`, c = Q(t, r, e, a);
890
+ if (u.length > 0 && c.push(Ar(u, r, e, (f) => r === "mysql" ? ft(f, t) : f)), r === "mssql") {
891
+ if (o !== void 0) {
892
+ u.length === 0 && c.push("ORDER BY (SELECT NULL)");
893
+ const f = s !== void 0 ? ` ${m("limit", () => `FETCH NEXT ${s} ROWS ONLY`)}` : "";
894
+ c.push(`${m("offset", () => `OFFSET ${o} ROWS`)}${f}`);
895
+ }
896
+ } else if (s !== void 0 || o !== void 0) {
897
+ const f = s !== void 0 || r === "mysql" ? m(s !== void 0 ? "limit" : {}, () => `LIMIT ${s ?? mr}`) : "", E = o !== void 0 ? m("offset", () => `OFFSET ${o}`) : "";
898
+ c.push([f, E].filter(Boolean).join(" "));
899
+ }
900
+ return [...n, ...c].join(`
901
+ `);
902
+ }
903
+ function br(t, r, e = {}) {
904
+ const n = e.values ? Xt(t, e.values) : t, s = e.schema ? Dt(n, e.schema).query : n, o = Mt(s, e);
905
+ return Rt(e, () => wt(o, r));
906
+ }
907
+ function gr(t, r) {
908
+ switch (t) {
909
+ case "mysql":
910
+ return "?";
911
+ case "mssql":
912
+ return `@p${r}`;
913
+ case "postgres":
914
+ return `$${r}`;
915
+ default:
916
+ return "?";
917
+ }
918
+ }
919
+ function Lr(t, r, e = {}) {
920
+ const n = e.schema ? Dt(t, e.schema) : { query: t, params: /* @__PURE__ */ new Map() }, s = {
921
+ values: [],
922
+ named: new Map(Object.entries(e.values ?? {}).map(([c, f]) => {
923
+ const E = n.params.get(c);
924
+ return [c, E ? yt(f, E) : f];
925
+ }))
926
+ }, o = Mt(n.query, e), u = Rt(e, () => wt(o, r, s)), i = [];
927
+ return { sql: u.replace(rr, (c, f) => {
928
+ const E = s.values[Number(f)];
929
+ return i.push(E instanceof Date ? $t(E) : E), gr(r, i.length);
930
+ }), params: i };
931
+ }
932
+ export {
933
+ hr as D,
934
+ Wt as S,
935
+ Lr as a,
936
+ br as b,
937
+ Ir as c,
938
+ Rr as s,
939
+ pr as u,
940
+ Cr as w
941
+ };