@nongt/visql-core 0.7.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.
@@ -1,1141 +0,0 @@
1
- var qt = Object.defineProperty;
2
- var Ut = (t, e, r) => e in t ? qt(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
3
- var M = (t, e, r) => Ut(t, typeof e != "symbol" ? e + "" : e, r);
4
- import { q as U, g as B, F as vt, G as Bt, o as K, d as nt, t as ft, h as jt, w as lt, H as _t, k as Ht, b as Yt, i as Pt } from "./schema-DFC26AhZ.js";
5
- import { aj as R, aD as k, aE as Gt, aF as xt, aG as kt, am as Qt, V as Xt, as as Jt, aH as A, ao as Vt, a8 as Wt, aI as Kt, aJ as $t, $ as zt } from "./issueLocation-732-e0B8.js";
6
- import { s as Et } from "./calendarDate-CYlr9TvX.js";
7
- class Zt extends Error {
8
- constructor(r, n, s, o) {
9
- const a = o ? `"${n}" (as "${o}")` : `"${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
- M(this, "path");
14
- /** The table it reads that needs scope. */
15
- M(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
- M(this, "alias");
19
- this.name = "ScopeError", this.path = r, this.table = n, o && (this.alias = o);
20
- }
21
- }
22
- const H = (t) => Object.prototype.toString.call(t) === "[object Object]", yt = (t) => Array.isArray(t.joins) && H(t.from);
23
- function j(t, e, r) {
24
- if (Array.isArray(t)) {
25
- const a = t.map((i, c) => j(i, [...e, c], r));
26
- return a.every((i, c) => i === t[c]) ? t : a;
27
- }
28
- if (!H(t)) return t;
29
- let n = !1;
30
- const s = Object.entries(t).map(([a, i]) => {
31
- const c = j(i, [...e, a], r);
32
- return c !== i && (n = !0), [a, c];
33
- }), o = n ? Object.fromEntries(s) : t;
34
- return yt(o) ? r(o, e) : o;
35
- }
36
- const pt = (t, e) => U(t).flatMap((r) => r.table !== void 0 && e.requires(r.table) ? [{ table: r.table, ...r.alias ? { alias: r.alias } : {}, ref: r.alias ?? r.table }] : []), Tt = (t) => U(t).flatMap((e) => {
37
- const r = e.alias ?? e.table;
38
- return r === void 0 ? [] : [r];
39
- });
40
- function Q(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 K(t, (r) => Q(r, e));
46
- }
47
- const At = (t) => t ? t.type === "logical" && t.operator === "AND" ? t.operands : [t] : [], te = (t) => t.joinType === "inner" || t.joinType === "left";
48
- function ee(t, e, r, n, s) {
49
- const o = 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((i) => {
51
- const c = i.alias ?? i.table;
52
- if (c !== r && c !== n || !te(i) || !At(i.on).some((f) => B(f, e) || B(f, o))) return;
53
- const u = i.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 st = (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 mt(t, e, r, n, s = new Set(Tt(e))) {
59
- const o = k(n.condition), a = U(e), i = (c) => {
60
- const u = /* @__PURE__ */ new Map([[r.table, r.ref]]), f = /* @__PURE__ */ new Map(), l = [], $ = new Set(s), p = (m) => {
61
- const O = f.get(m);
62
- return O ? [...p(O.ref), O.tie] : [];
63
- }, g = (m, O, P) => {
64
- if (O === m.length) return st(p(u.get(P)));
65
- const h = m[O], L = Bt(t, [...u.keys()], h);
66
- if (!L) return !1;
67
- const Z = u.get(k(L.on).find((y) => y !== h)), tt = (y) => Q(L.on, new Map([...u, [h, y]])), et = o.includes(h), rt = (y, S) => {
68
- u.set(h, y), f.set(y, { ref: Z, tie: S });
69
- }, Ft = (y, S) => (rt(y, S), st(p(y)) && g(m, O + 1, P) ? !0 : (u.delete(h), f.delete(y), !1));
70
- if (a.some((y) => {
71
- if (y.table !== h) return !1;
72
- const S = y.alias ?? h, G = ee(e, tt(S), Z, S, et);
73
- return (G.forward || G.back) && Ft(S, G);
74
- })) return !0;
75
- if (!c) return !1;
76
- let N = h;
77
- for (let y = 2; $.has(N); y += 1) N = `${h}_${y}`;
78
- return $.add(N), rt(N, { back: !0, forward: L.joinType === "inner" || et }), l.push({
79
- id: Gt(),
80
- table: h,
81
- ...N !== h ? { alias: N } : {},
82
- joinType: L.joinType,
83
- on: tt(N)
84
- }), g(m, O + 1, P);
85
- };
86
- let v;
87
- if (o.every((m) => {
88
- if (v || u.has(m)) return !0;
89
- const O = vt(t, [...u.keys()], m);
90
- return O ? g(O, 0, m) : (v = m, !0);
91
- }))
92
- return $.forEach((m) => s.add(m)), { joins: l, condition: Q(n.condition, u), ...v ? { missing: v } : {} };
93
- };
94
- return i(!1) ?? i(!0);
95
- }
96
- function gt(t, e) {
97
- return At(t).some((r) => B(r, e));
98
- }
99
- function re(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 ot(t, e, r, n, s) {
103
- return pt(e, r).reduce((o, a) => {
104
- const i = mt(t, o, a, r, s);
105
- if (i.missing) throw new Zt(n, a.table, i.missing, a.alias);
106
- const c = gt(o.where, i.condition);
107
- return i.joins.length === 0 && c ? o : {
108
- ...o,
109
- joins: [...o.joins, ...i.joins],
110
- where: c ? o.where : re(o.where, i.condition)
111
- };
112
- }, e);
113
- }
114
- function it(t) {
115
- const e = /* @__PURE__ */ new Map(), r = (n, s, o, a) => {
116
- if (Array.isArray(n)) {
117
- n.forEach((c, u) => r(c, [...s, u], void 0, a));
118
- return;
119
- }
120
- if (!H(n)) return;
121
- let i = a;
122
- yt(n) && (i = o ?? /* @__PURE__ */ new Set(), e.set(JSON.stringify(s), i), Tt(n).forEach((c) => i.add(c))), Object.entries(n).forEach(([c, u]) => r(
123
- u,
124
- [...s, c],
125
- n.type === "exists" && c === "query" ? i : void 0,
126
- i
127
- ));
128
- };
129
- return r(t, [], void 0, /* @__PURE__ */ new Set()), e;
130
- }
131
- function ve(t, e, r) {
132
- const n = ot(
133
- t,
134
- e,
135
- r,
136
- [],
137
- it(e).get("[]")
138
- ), s = R(t, e, n), o = it(s), a = j(s, [], (i, c) => c.length === 0 ? i : ot(t, i, r, c, o.get(JSON.stringify(c))));
139
- return R(t, s, a);
140
- }
141
- function Be(t, e, r) {
142
- if (!H(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, o) => (pt(s, r).forEach((a) => {
146
- const i = mt(t, s, a, r);
147
- (i.missing || i.joins.length > 0 || !gt(s.where, i.condition)) && n.push({ path: o, table: a.table, ...a.alias ? { alias: a.alias } : {} });
148
- }), s)), n;
149
- }
150
- const ne = (t) => typeof t == "object" && t !== null && !(t instanceof Date), at = {
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) ? at.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: at.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) => ne(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: nt(),
242
- query: { joins: [], ...e, select: [{ id: nt(), expression: t }] }
243
- })
244
- };
245
- function je(t, e, r) {
246
- return A(t, e, { type: "setBaseTable", table: r });
247
- }
248
- function _e(t, e, r, n = {}) {
249
- const s = { type: "addJoin", table: r, ...n };
250
- return A(t, e, s);
251
- }
252
- function He(t, e, r) {
253
- return A(t, e, { type: "removeJoin", joinId: r });
254
- }
255
- function se(t, e, r, n = {}) {
256
- const s = xt(e), o = k(r);
257
- if (s && o.some((u) => u !== s.alias)) {
258
- if (o.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(U(u).map(ft)), $ = kt(t, f), p = o.find((g) => !l.has(g) && !$.has(g));
262
- if (p)
263
- throw new Error(`addCondition: "${p}" 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) => Qt(
265
- u,
266
- [Xt(s.id, l)],
267
- ($) => se(t, $, r, n)
268
- ), e);
269
- }
270
- const a = n.operator ?? "AND", { where: i } = e;
271
- let c;
272
- return i ? i.type === "logical" && i.operator === a ? c = { ...i, operands: [...i.operands, r] } : c = { type: "logical", operator: a, operands: [i, r] } : c = r, R(t, e, Jt(t, e, c));
273
- }
274
- function Ye(t, e, r, n) {
275
- const s = A(t, e, { type: "addSelectItem" }), o = s.select[s.select.length - 1].id, a = A(t, s, {
276
- type: "setSelectExpression",
277
- selectId: o,
278
- expression: r
279
- }), i = n === void 0 ? a : A(t, a, { type: "setSelectAlias", selectId: o, alias: n });
280
- return R(t, e, i);
281
- }
282
- function Pe(t, e, r) {
283
- const n = A(t, e, { type: "addGroupByItem" }), { id: s } = n.groupBy[n.groupBy.length - 1], o = A(t, n, {
284
- type: "setGroupByExpression",
285
- groupById: s,
286
- expression: r
287
- });
288
- return R(t, e, o);
289
- }
290
- function Ge(t, e, r) {
291
- return R(t, e, Vt(t, e, r));
292
- }
293
- function xe(t, e, r, n = "asc") {
294
- const s = A(t, e, { type: "addOrderByItem" }), { id: o } = s.orderBy[s.orderBy.length - 1], a = A(t, s, {
295
- type: "setOrderByExpression",
296
- orderById: o,
297
- expression: r
298
- }), i = A(t, a, {
299
- type: "setOrderByDirection",
300
- orderById: o,
301
- direction: n
302
- });
303
- return R(t, e, i);
304
- }
305
- function ke(t, e, r) {
306
- let n = e;
307
- return "limit" in r && (n = A(t, n, { type: "setLimit", limit: r.limit })), "offset" in r && (n = A(t, n, { type: "setOffset", offset: r.offset })), n;
308
- }
309
- function Qe(t, e, r) {
310
- return A(t, e, { type: "setDistinct", distinct: r });
311
- }
312
- function Xe(t) {
313
- if (!jt(t)) throw new Error(`query "${t.id}" has no base table yet`);
314
- return t;
315
- }
316
- const X = 4;
317
- class w extends Error {
318
- constructor(r, n) {
319
- super(n);
320
- M(this, "kind");
321
- this.name = "QueryFormatError", this.kind = r;
322
- }
323
- }
324
- const q = (t) => typeof t == "object" && t !== null && !Array.isArray(t);
325
- function oe(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 ie(t) {
345
- const e = (r) => {
346
- if (Array.isArray(r)) return r.map(e);
347
- if (!q(r)) return r;
348
- const n = Object.fromEntries(Object.entries(r).map(([a, i]) => [a, e(i)])), { right: s } = n;
349
- if (n.type !== "binary" || n.operator !== "IN" || !q(s) || s.type === "subquery" || s.type === "list") return n;
350
- const o = s.type === "literal" && typeof s.value == "string" ? oe(s.value).map((a) => ({ type: "literal", value: a })) : [s];
351
- return { ...n, right: { type: "list", items: o } };
352
- };
353
- return e(t);
354
- }
355
- const ae = (t) => t, ue = (t) => t, ce = [ie, ae, ue];
356
- function fe(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)) : q(t) ? t.type === "literal" ? e(t) : Object.fromEntries(Object.entries(t).map(([r, n]) => [r, _(n, e)])) : t;
361
- }
362
- function le(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 $e(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 w("invalid", `not a date: ${JSON.stringify(n)}`);
372
- } else if (e === "bigint" && /^-?\d+$/.test(n))
373
- s = BigInt(n);
374
- else {
375
- const o = String(e);
376
- throw new w("invalid", `can't read a ${o} from ${JSON.stringify(n)}`);
377
- }
378
- return { ...r, value: s };
379
- }
380
- function Je(t) {
381
- return {
382
- version: X,
383
- query: _(t, le)
384
- };
385
- }
386
- function Ve(t) {
387
- if (!q(t))
388
- throw new w("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 w("invalid", "a stored query has a whole-number version from 1");
392
- if (e > X)
393
- throw new w(
394
- "newerVersion",
395
- `stored in format ${e}; this version reads up to ${X}`
396
- );
397
- const r = fe(t.query, e, ce);
398
- if (!q(r) || typeof r.id != "string")
399
- throw new w("invalid", "a stored query has a query with a string id");
400
- return _(r, $e);
401
- }
402
- function J(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: o, alias: a }) => {
405
- if (o === void 0) {
406
- a && s.add(a);
407
- return;
408
- }
409
- if (r.set(o, o), a) {
410
- r.set(a, o), n.add(a), s.delete(a);
411
- return;
412
- }
413
- n.delete(o), s.delete(o);
414
- }), { tableOf: r, aliases: n, derived: s };
415
- }
416
- function Ee(t, e, r) {
417
- const n = t.on && F(t.on, e, r);
418
- return t.query ? { ...t, on: n, query: _t(t.query, (s) => Y(s, r)) } : t.shared !== void 0 ? { ...t, on: n } : { ...t, on: n, table: r(t.table) };
419
- }
420
- function F(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: Y(t.query, r) };
431
- if (t.type === "exists") {
432
- const { query: n } = t, s = [n.from, ...n.joins], o = J(s), a = J(s, e);
433
- return {
434
- ...t,
435
- link: F(t.link, a, r),
436
- query: {
437
- ...n,
438
- from: { ...n.from, table: r(n.from.table) },
439
- joins: n.joins.map((i) => Ee(i, o, r)),
440
- ...n.where ? { where: F(n.where, o, r) } : {}
441
- }
442
- };
443
- }
444
- return K(t, (n) => F(n, e, r));
445
- }
446
- function Y(t, e) {
447
- const r = J([t.from, ...t.joins]), n = lt(
448
- t,
449
- (s) => F(s, r, e),
450
- (s) => Y(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, o]) => [s, V(o, 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 ye(t, e) {
473
- return Y(V(t, e), e);
474
- }
475
- const pe = /^(\d{2}):(\d{2})(?::(\d{2}))?$/, ut = /YYYY|MM|DD|HH|mm|ss/g, C = (t, e = 2) => String(t).padStart(e, "0");
476
- function ht(t, e) {
477
- let r;
478
- const n = typeof t == "string" ? pe.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" ? Wt(t, "dateTime") : t;
483
- a instanceof Date && (r = {
484
- YYYY: C(a.getUTCFullYear(), 4),
485
- MM: C(a.getUTCMonth() + 1),
486
- DD: C(a.getUTCDate()),
487
- HH: C(a.getUTCHours()),
488
- mm: C(a.getUTCMinutes()),
489
- ss: C(a.getUTCSeconds())
490
- });
491
- }
492
- if (!r) return t;
493
- const s = r;
494
- return (e.match(ut) ?? []).some((a) => s[a] === void 0) ? t : e.replace(ut, (a) => s[a]);
495
- }
496
- function Ot(t, e) {
497
- const r = /* @__PURE__ */ new Map(), n = (s) => {
498
- const o = /* @__PURE__ */ new Map();
499
- U(s).forEach((u) => o.set(ft(u), u.table));
500
- const a = (u) => {
501
- if ((u == null ? void 0 : u.type) !== "field" || !u.table || !u.column) return;
502
- const f = o.has(u.table) ? o.get(u.table) : u.table, l = f === void 0 ? void 0 : Ht(e, f), $ = l == null ? void 0 : l.columns.find((p) => p.name === u.column);
503
- return $ == null ? void 0 : $.format;
504
- }, i = (u, f) => {
505
- switch (u.type) {
506
- case "literal":
507
- return { ...u, value: ht(u.value, f) };
508
- case "list":
509
- return { ...u, items: u.items.map((l) => i(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 = K(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: $ ? i(f.left, $) : f.left,
523
- right: l ? i(f.right, l) : f.right
524
- };
525
- };
526
- return lt(s, c, (u) => n(u));
527
- };
528
- return { query: n(t), params: r };
529
- }
530
- const We = ["mysql", "mssql", "postgres"], Ke = {
531
- mysql: "MySQL",
532
- mssql: "SQL Server",
533
- postgres: "PostgreSQL"
534
- };
535
- function D(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 Te = /^[A-Za-z_][A-Za-z0-9_]*$/, Dt = (t) => `${t}`, Ae = /\uE000(\d+)\uE000/g;
549
- let I;
550
- function ze(t, e) {
551
- I = { ...t, writing: [] };
552
- try {
553
- return e();
554
- } finally {
555
- I = void 0;
556
- }
557
- }
558
- function Nt(t, e, r) {
559
- if (typeof t != "object" || t === null || t instanceof Date) return;
560
- let n;
561
- return Object.entries(t).some(([s, o]) => {
562
- const a = [...r, Array.isArray(t) ? Number(s) : s];
563
- return n = o === e ? a : Nt(o, e, a), n !== void 0;
564
- }), n;
565
- }
566
- function T(t, e) {
567
- if (!I) return e();
568
- const { writing: r, paths: n } = I, s = r[r.length - 1], o = typeof t == "string" ? [t] : Nt(s.value, t, s.path);
569
- if (!o) return e();
570
- r.push({ value: t, path: o });
571
- try {
572
- return `${n.push(o) - 1}${e()}`;
573
- } finally {
574
- r.pop();
575
- }
576
- }
577
- const me = {
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 ge(t, e) {
607
- var n;
608
- const r = (n = me[e]) == null ? void 0 : n[t];
609
- return r ? e === "postgres" ? `NULL::${r}` : `CAST(NULL AS ${r})` : "NULL";
610
- }
611
- function St(t, e, r) {
612
- if (t == null) return "NULL";
613
- if (r)
614
- return r.values.push(t), Dt(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 = I ? 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 ? `'${Et(t)}'` : String(t);
622
- }
623
- function he(t, e) {
624
- switch (t) {
625
- case "!=":
626
- return e === "mssql" ? "<>" : "!=";
627
- case "REGEXP":
628
- if (e === "postgres") return "~";
629
- if (e === "mssql") throw new Error("REGEXP isn't available in SQL Server");
630
- return "REGEXP";
631
- default:
632
- return t;
633
- }
634
- }
635
- function b(t) {
636
- return (t == null ? void 0 : t.type) === "literal" && typeof t.value == "string" && /^[A-Za-z_]+$/.test(t.value) ? t.value.toUpperCase() : "DAY";
637
- }
638
- const x = {
639
- YEAR: "year",
640
- QUARTER: "quarter",
641
- MONTH: "month",
642
- WEEK: "week",
643
- DAY: "day",
644
- HOUR: "hour",
645
- MINUTE: "minute",
646
- SECOND: "second",
647
- MILLISECOND: "millisecond"
648
- }, Oe = {
649
- // ---- Date arithmetic ----
650
- DATE_ADD: ([t, e], r, n, s) => {
651
- var a;
652
- const o = b(r[2]);
653
- switch (n) {
654
- case "mysql":
655
- return o === "MILLISECOND" ? `DATE_ADD(${t}, INTERVAL (${e}) * 1000 MICROSECOND)` : `DATE_ADD(${t}, INTERVAL ${e} ${o})`;
656
- case "postgres": {
657
- const i = x[o] ?? o.toLowerCase();
658
- return !s && ((a = r[1]) == null ? void 0 : a.type) === "literal" && typeof r[1].value == "number" ? `(${t} + INTERVAL '${r[1].value} ${i}')` : `(${t} + (${e} * INTERVAL '1 ${i}'))`;
659
- }
660
- case "mssql":
661
- return `DATEADD(${o}, ${e}, ${t})`;
662
- default:
663
- return `DATE_ADD(${t}, ${e}, ${b(r[2])})`;
664
- }
665
- },
666
- DATE_SUB: ([t, e], r, n, s) => {
667
- var a;
668
- const o = b(r[2]);
669
- switch (n) {
670
- case "mysql":
671
- return o === "MILLISECOND" ? `DATE_SUB(${t}, INTERVAL (${e}) * 1000 MICROSECOND)` : `DATE_SUB(${t}, INTERVAL ${e} ${o})`;
672
- case "postgres": {
673
- const i = x[o] ?? o.toLowerCase();
674
- return !s && ((a = r[1]) == null ? void 0 : a.type) === "literal" && typeof r[1].value == "number" ? `(${t} - INTERVAL '${r[1].value} ${i}')` : `(${t} - (${e} * INTERVAL '1 ${i}'))`;
675
- }
676
- case "mssql":
677
- return `DATEADD(${o}, -(${e}), ${t})`;
678
- default:
679
- return `DATE_SUB(${t}, ${e}, ${b(r[2])})`;
680
- }
681
- },
682
- // ---- Date diff ----
683
- DATEDIFF: ([t, e], r, n) => {
684
- const s = b(r[2]);
685
- switch (n) {
686
- case "mysql":
687
- return `TIMESTAMPDIFF(${s}, ${t}, ${e})`;
688
- case "mssql":
689
- return `DATEDIFF(${s}, ${t}, ${e})`;
690
- case "postgres":
691
- switch (s) {
692
- case "YEAR":
693
- return `EXTRACT(YEAR FROM age(${e}, ${t}))::integer`;
694
- case "QUARTER": {
695
- const o = `EXTRACT(YEAR FROM age(${e}, ${t}))`, a = `EXTRACT(MONTH FROM age(${e}, ${t}))`;
696
- return `FLOOR((${o} * 12 + ${a}) / 3)::integer`;
697
- }
698
- case "MONTH": {
699
- const o = `EXTRACT(YEAR FROM age(${e}, ${t}))`, a = `EXTRACT(MONTH FROM age(${e}, ${t}))`;
700
- return `(${o} * 12 + ${a})::integer`;
701
- }
702
- case "WEEK":
703
- return `FLOOR((${e}::date - ${t}::date) / 7)`;
704
- case "DAY":
705
- return `(${e}::date - ${t}::date)`;
706
- case "HOUR":
707
- return `FLOOR(EXTRACT(EPOCH FROM (${e} - ${t})) / 3600)::integer`;
708
- case "MINUTE":
709
- return `FLOOR(EXTRACT(EPOCH FROM (${e} - ${t})) / 60)::integer`;
710
- case "SECOND":
711
- return `FLOOR(EXTRACT(EPOCH FROM (${e} - ${t})))::integer`;
712
- case "MILLISECOND":
713
- return `FLOOR(EXTRACT(EPOCH FROM (${e} - ${t})) * 1000)::integer`;
714
- default:
715
- return `/* unknown unit: ${s} */`;
716
- }
717
- default:
718
- return `DATEDIFF(${t}, ${e}, ${s})`;
719
- }
720
- },
721
- // ---- Date extract ----
722
- EXTRACT: ([t], e, r) => {
723
- const n = b(e[1]);
724
- switch (r) {
725
- case "mysql":
726
- return n === "MILLISECOND" ? `FLOOR(MICROSECOND(${t}) / 1000)` : `EXTRACT(${n} FROM ${t})`;
727
- case "postgres":
728
- return n === "MILLISECOND" ? `EXTRACT(MILLISECONDS FROM ${t})::integer` : `EXTRACT(${n} FROM ${t})`;
729
- case "mssql":
730
- return `DATEPART(${n}, ${t})`;
731
- default:
732
- return `EXTRACT(${t}, ${n})`;
733
- }
734
- },
735
- // ---- Date truncation ----
736
- DATE_TRUNC: ([t], e, r) => {
737
- const n = b(e[1]);
738
- switch (r) {
739
- case "mysql":
740
- switch (n) {
741
- case "YEAR":
742
- return `DATE_FORMAT(${t}, '%Y-01-01')`;
743
- case "QUARTER":
744
- return `MAKEDATE(YEAR(${t}), 1) + INTERVAL (QUARTER(${t}) - 1) QUARTER`;
745
- case "MONTH":
746
- return `DATE_FORMAT(${t}, '%Y-%m-01')`;
747
- case "WEEK":
748
- return `DATE_SUB(DATE(${t}), INTERVAL WEEKDAY(${t}) DAY)`;
749
- case "DAY":
750
- return `DATE(${t})`;
751
- case "HOUR":
752
- return `DATE_FORMAT(${t}, '%Y-%m-%d %H:00:00')`;
753
- case "MINUTE":
754
- return `DATE_FORMAT(${t}, '%Y-%m-%d %H:%i:00')`;
755
- case "SECOND":
756
- return `DATE_FORMAT(${t}, '%Y-%m-%d %H:%i:%s')`;
757
- case "MILLISECOND":
758
- return `DATE_FORMAT(${t}, '%Y-%m-%d %H:%i:%s.000')`;
759
- default:
760
- return `/* unknown unit: ${n} */`;
761
- }
762
- case "postgres":
763
- return `DATE_TRUNC('${x[n] ?? n.toLowerCase()}', ${t})`;
764
- case "mssql":
765
- switch (n) {
766
- case "YEAR":
767
- return `DATEFROMPARTS(YEAR(${t}), 1, 1)`;
768
- case "QUARTER":
769
- return `DATEFROMPARTS(YEAR(${t}), (DATEPART(QUARTER, ${t}) - 1) * 3 + 1, 1)`;
770
- case "MONTH":
771
- return `DATEFROMPARTS(YEAR(${t}), MONTH(${t}), 1)`;
772
- case "WEEK": {
773
- const s = `CAST(${t} AS DATE)`;
774
- return `DATEADD(DAY, -(DATEDIFF(DAY, 0, ${s}) % 7), ${s})`;
775
- }
776
- case "DAY":
777
- return `CAST(${t} AS DATE)`;
778
- case "HOUR":
779
- return `DATEADD(HOUR, DATEDIFF(HOUR, 0, ${t}), 0)`;
780
- case "MINUTE":
781
- return `DATEADD(MINUTE, DATEDIFF(MINUTE, 0, ${t}), 0)`;
782
- case "SECOND":
783
- return `DATEADD(SECOND, DATEDIFF(SECOND, '2000-01-01', ${t}), '2000-01-01')`;
784
- case "MILLISECOND": {
785
- const s = `CAST(${t} AS DATE)`;
786
- return `DATEADD(MILLISECOND, DATEDIFF(MILLISECOND, ${s}, ${t}), ${s})`;
787
- }
788
- default:
789
- return `/* unknown unit: ${n} */`;
790
- }
791
- default:
792
- return `DATE_TRUNC(${t}, ${n})`;
793
- }
794
- },
795
- // ---- Type cast ----
796
- /**
797
- * CAST(expr, type_name) — type_name is stored as a string literal.
798
- * Renders as CAST(expr AS type_name) for all dialects.
799
- */
800
- CAST: ([t], e) => {
801
- 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 : "??";
802
- return `CAST(${t} AS ${n})`;
803
- },
804
- // ---- String aggregation (issue 137) ----
805
- // The separator goes into the SQL as a literal even in parameterized SQL:
806
- // MySQL's SEPARATOR takes nothing else.
807
- STRING_AGG: ([t = "??"], e, r, n, s, o) => {
808
- const a = e[1] ?? { type: "literal", value: ", " }, i = a.type === "literal" && typeof a.value == "string" ? St(a.value, r) : "??", c = s.distinct ? "DISTINCT " : "", u = ($) => {
809
- var p;
810
- return (p = s.orderBy) != null && p.length ? `ORDER BY ${s.orderBy.map((g) => `${$(g)} ${g.direction === "desc" ? "DESC" : "ASC"}`).join(", ")}` : "";
811
- }, f = ($) => o($.expression), l = ($) => $ ? ` ${$}` : "";
812
- switch (r) {
813
- case "mysql":
814
- return `GROUP_CONCAT(${c}${t}${l(u(f))} SEPARATOR ${i})`;
815
- case "postgres": {
816
- const $ = `CAST(${t} AS TEXT)`, p = u((g) => {
817
- if (!s.distinct) return f(g);
818
- if (B(g.expression, e[0])) return $;
819
- throw new Error("PostgreSQL orders STRING_AGG of different values by the value only");
820
- });
821
- return `STRING_AGG(${c}${$}, ${i}${l(p)})`;
822
- }
823
- case "mssql": {
824
- if (s.distinct)
825
- throw new Error("SQL Server's STRING_AGG can't join only different values");
826
- const $ = u(f), p = $ ? ` WITHIN GROUP (${$})` : "";
827
- return `STRING_AGG(CAST(${t} AS NVARCHAR(MAX)), ${i})${p}`;
828
- }
829
- default:
830
- return `STRING_AGG(${c}${t}, ${i}${l(u(f))})`;
831
- }
832
- }
833
- };
834
- function d(t) {
835
- return t.type === "binary" || t.type === "logical" || t.type === "if" || t.type === "case";
836
- }
837
- function E(t, e, r, n) {
838
- return T(t, () => De(t, e, r, n));
839
- }
840
- function ct(t, e, r, n) {
841
- const s = (o) => {
842
- if (!o) return "??";
843
- const a = E(o, e, r, n);
844
- return d(o) ? `(${a})` : a;
845
- };
846
- return T(t, () => {
847
- const [o, a] = t.type === "list" ? t.items : [t];
848
- return `${s(o)} AND ${s(a)}`;
849
- });
850
- }
851
- function De(t, e, r, n) {
852
- var a;
853
- const s = " ".repeat(r), o = " ".repeat(r + 1);
854
- switch (t.type) {
855
- case "literal":
856
- return t.value === "" && !t.empty ? "??" : t.value === null && t.as ? ge(t.as, e) : St(t.value, e, n);
857
- case "param": {
858
- if (!n) return Te.test(t.name) ? `:${t.name}` : "??";
859
- if (!n.named.has(t.name))
860
- throw new Error(`no value for parameter "${t.name}"`);
861
- return n.values.push(n.named.get(t.name)), Dt(n.values.length - 1);
862
- }
863
- case "field": {
864
- if (!t.column) return "??";
865
- const i = D(t.column, e);
866
- return t.table ? `${D(t.table, e)}.${i}` : i;
867
- }
868
- case "function": {
869
- const i = t.args.map((l) => E(l, e, r, n)), c = Oe[t.name.toUpperCase()];
870
- if (c)
871
- return c(
872
- i,
873
- t.args,
874
- e,
875
- n !== void 0,
876
- t,
877
- (l) => E(l, e, r, n)
878
- );
879
- const u = /^[A-Za-z_][A-Za-z0-9_.]*$/.test(t.name) || t.name === "" ? t.name : "??";
880
- if (i.length === 0 && u.toUpperCase() === "COUNT") return `${u}(*)`;
881
- const f = t.distinct && i.length > 0 ? "DISTINCT " : "";
882
- return `${u}(${f}${i.join(", ")})`;
883
- }
884
- case "binary": {
885
- const i = t.operator ? he(t.operator, e) : "=", c = E(t.left, e, r, n), u = d(t.left) ? `(${c})` : c;
886
- if (zt(t.operator)) return `${u} ${i}`;
887
- if (!t.right) return `${u} ${i} ??`;
888
- if (i === "BETWEEN")
889
- return `${u} BETWEEN ${ct(t.right, e, r, n)}`;
890
- if (i === "IN")
891
- return t.right.type === "list" ? `${u} IN ${E(t.right, e, r, n)}` : `${u} IN (${E(t.right, e, r, n)})`;
892
- const f = E(t.right, e, r, n), l = d(t.right) ? `(${f})` : f;
893
- return `${u} ${i} ${l}`;
894
- }
895
- case "logical": {
896
- if (t.operands.length === 0) return "/* empty */";
897
- if (t.operands.length === 1)
898
- return E(t.operands[0], e, r, n);
899
- const i = `
900
- ${s}${t.operator} `;
901
- return t.operands.map((c) => {
902
- if (c.type === "logical") {
903
- const u = E(c, e, r + 1, n);
904
- return `(
905
- ${o}${u}
906
- ${s})`;
907
- }
908
- return E(c, e, r, n);
909
- }).join(i);
910
- }
911
- case "not": {
912
- const { operand: i } = t;
913
- if (i.type === "binary" && i.operator === "IN" && ((a = i.right) == null ? void 0 : a.type) === "subquery") {
914
- const c = E(i.left, e, r, n);
915
- return `${d(i.left) ? `(${c})` : c} NOT IN (${E(i.right, e, r, n)})`;
916
- }
917
- if (i.type === "binary" && i.operator === "BETWEEN" && i.right) {
918
- const c = E(i.left, e, r, n);
919
- return `${d(i.left) ? `(${c})` : c} NOT BETWEEN ${ct(i.right, e, r, n)}`;
920
- }
921
- if (i.type === "logical" || i.type === "not") {
922
- const c = E(i, e, r + 1, n);
923
- return `NOT (
924
- ${o}${c}
925
- ${s})`;
926
- }
927
- return `NOT ${E(i, e, r, n)}`;
928
- }
929
- case "if": {
930
- const i = 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";
931
- return e === "mysql" ? `IF(${i}, ${c}, ${u})` : e === "mssql" ? `IIF(${i}, ${c}, ${u})` : `CASE WHEN ${i} THEN ${c} ELSE ${u} END`;
932
- }
933
- case "case": {
934
- const i = t.subject ? ` ${E(t.subject, e, r, n)}` : "", c = t.branches.map((f) => {
935
- const l = E(f.when, e, r + 1, n), $ = E(f.then, e, r + 1, n);
936
- return `${o}WHEN ${l} THEN ${$}`;
937
- }).join(`
938
- `), u = t.else ? `
939
- ${o}ELSE ${E(t.else, e, r + 1, n)}` : "";
940
- return `CASE${i}
941
- ${c}${u}
942
- ${s}END`;
943
- }
944
- // EXISTS (SELECT 1 FROM … WHERE <link> AND <where>): the subquery written
945
- // in place, one level in, so its params fall in reading order.
946
- case "exists": {
947
- const { query: i, link: c } = t, u = ($) => $.type === "logical" && $.operator === "AND" ? $.operands : [$], f = i.where ? { type: "logical", operator: "AND", operands: [...u(c), ...u(i.where)] } : c;
948
- return `EXISTS (
949
- ${[
950
- "SELECT 1",
951
- // The clauses below write their expressions with formatNode.
952
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
953
- wt(i.from, e),
954
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
955
- ...i.joins.map(($) => Lt($, e, n)),
956
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
957
- bt(f, e, n)
958
- ].join(`
959
- `).replace(/^/gm, o)}
960
- ${s})`;
961
- }
962
- // IN's right side (issue 122): its query, on lines of its own, inside the
963
- // parentheses IN writes around it.
964
- // An empty list is unfinished, like a value not filled in.
965
- case "list":
966
- return `(${t.items.map((i) => E(i, e, r, n)).join(", ") || "??"})`;
967
- case "subquery":
968
- return `
969
- ${z(t.query, e, n).join(`
970
- `).replace(/^/gm, o)}
971
- ${s}`;
972
- default:
973
- return "/* unknown */";
974
- }
975
- }
976
- function bt(t, e, r) {
977
- return `WHERE
978
- ${E(t, e, 1, r)}`;
979
- }
980
- const Ne = {
981
- inner: "INNER JOIN",
982
- left: "LEFT JOIN",
983
- right: "RIGHT JOIN",
984
- full: "FULL JOIN",
985
- cross: "CROSS JOIN"
986
- };
987
- let Rt = /* @__PURE__ */ new Map();
988
- function It(t, e, r) {
989
- return t.shared !== void 0 ? D(Rt.get(t.shared) ?? "??", e) : t.query ? `(
990
- ${Ct(t.query, e, r).replace(/^/gm, " ")}
991
- )` : D(t.table, e);
992
- }
993
- function Ct(t, e, r) {
994
- return Yt(t).map((n) => z(n, e, r).join(`
995
- `)).join(Pt(t) && !t.all ? `
996
- UNION
997
- ` : `
998
- UNION ALL
999
- `);
1000
- }
1001
- function Se(t, e, r) {
1002
- return t.length === 0 ? [] : [`WITH
1003
- ${t.map((s) => T(s, () => {
1004
- const o = Ct(s.query, e, r).replace(/^/gm, " ");
1005
- return ` ${D(s.name, e)} AS (
1006
- ${o}
1007
- )`;
1008
- })).join(`,
1009
- `)}`];
1010
- }
1011
- function wt(t, e, r) {
1012
- const n = t.alias ? ` AS ${D(t.alias, e)}` : "";
1013
- return `FROM ${T(t, () => `${It(t, e, r)}${n}`)}`;
1014
- }
1015
- function Lt(t, e, r) {
1016
- return T(t, () => {
1017
- const n = It(t, e, r), s = t.alias ? ` AS ${D(t.alias, e)}` : "";
1018
- if (t.joinType === "cross") return `CROSS JOIN ${n}${s}`;
1019
- const o = t.on ? E(t.on, e, 1, r) : "/* unconfigured */";
1020
- return `${Ne[t.joinType]} ${n}${s}
1021
- ON ${o}`;
1022
- });
1023
- }
1024
- function be(t, e, r, n = "SELECT") {
1025
- if (t.length === 0) return `${n} ${T(t, () => "*")}`;
1026
- const s = t.map((o) => T(o, () => {
1027
- const a = E(o.expression, e, 1, r), i = o.alias ? ` AS ${D(o.alias, e)}` : "";
1028
- return `${a}${i}`;
1029
- }));
1030
- return `${n}
1031
- ${s.join(`,
1032
- `)}`;
1033
- }
1034
- function Re(t, e, r) {
1035
- return `GROUP BY
1036
- ${t.map((s) => T(
1037
- s,
1038
- () => E(s.expression, e, 1, r)
1039
- )).join(`,
1040
- `)}`;
1041
- }
1042
- function Ie(t, e, r) {
1043
- return `HAVING
1044
- ${E(t, e, 1, r)}`;
1045
- }
1046
- function Ce(t, e, r, n) {
1047
- return `ORDER BY
1048
- ${t.map((o) => T(o, () => `${E(n(o.expression), e, 1, r)} ${o.direction === "desc" ? "DESC" : "ASC"}`)).join(`,
1049
- `)}`;
1050
- }
1051
- const W = (t) => t !== void 0 && Number.isInteger(t) && t >= 0 ? t : void 0;
1052
- function Mt(t, e) {
1053
- const r = e.resolveName ? ye(t, e.resolveName) : t;
1054
- return e.defaultLimit !== void 0 && W(r.limit) === void 0 ? { ...r, limit: e.defaultLimit } : r;
1055
- }
1056
- const we = "18446744073709551615";
1057
- function z(t, e, r, n = `SELECT${t.distinct ? " DISTINCT" : ""}`) {
1058
- const s = [
1059
- be(t.select, e, r, n),
1060
- wt(t.from, e, r),
1061
- ...t.joins.map((a) => Lt(a, e, r))
1062
- ];
1063
- t.where && s.push(bt(t.where, e, r));
1064
- const o = t.groupBy ?? [];
1065
- if (o.length > 0 && s.push(Re(o, e, r)), t.having) {
1066
- const a = e === "mysql" ? $t(t.having, t) : t.having;
1067
- s.push(Ie(a, e, r));
1068
- }
1069
- return s;
1070
- }
1071
- function dt(t, e, r) {
1072
- I && (I.writing = [{ value: t, path: [] }]), Rt = new Map((t.shared ?? []).map((f) => [f.id, f.name]));
1073
- const n = Se(t.shared ?? [], e, r), s = W(t.limit), o = W(t.offset) || void 0, a = t.orderBy ?? [], i = e === "mssql" && s !== void 0 && o === void 0, c = `SELECT${t.distinct ? " DISTINCT" : ""}${i ? ` ${T("limit", () => `TOP (${s})`)}` : ""}`, u = z(t, e, r, c);
1074
- if (a.length > 0 && u.push(Ce(a, e, r, (f) => e === "mysql" ? $t(f, t) : f)), e === "mssql") {
1075
- if (o !== void 0) {
1076
- a.length === 0 && u.push("ORDER BY (SELECT NULL)");
1077
- const f = s !== void 0 ? ` ${T("limit", () => `FETCH NEXT ${s} ROWS ONLY`)}` : "";
1078
- u.push(`${T("offset", () => `OFFSET ${o} ROWS`)}${f}`);
1079
- }
1080
- } else if (s !== void 0 || o !== void 0) {
1081
- const f = s !== void 0 || e === "mysql" ? T(s !== void 0 ? "limit" : {}, () => `LIMIT ${s ?? we}`) : "", l = o !== void 0 ? T("offset", () => `OFFSET ${o}`) : "";
1082
- u.push([f, l].filter(Boolean).join(" "));
1083
- }
1084
- return [...n, ...u].join(`
1085
- `);
1086
- }
1087
- function Ze(t, e, r = {}) {
1088
- const n = r.values ? Kt(t, r.values) : t, s = r.schema ? Ot(n, r.schema).query : n;
1089
- return dt(Mt(s, r), e);
1090
- }
1091
- function Le(t, e) {
1092
- switch (t) {
1093
- case "mysql":
1094
- return "?";
1095
- case "mssql":
1096
- return `@p${e}`;
1097
- case "postgres":
1098
- return `$${e}`;
1099
- default:
1100
- return "?";
1101
- }
1102
- }
1103
- function tr(t, e, r = {}) {
1104
- const n = r.schema ? Ot(t, r.schema) : { query: t, params: /* @__PURE__ */ new Map() }, s = {
1105
- values: [],
1106
- named: new Map(Object.entries(r.values ?? {}).map(([u, f]) => {
1107
- const l = n.params.get(u);
1108
- return [u, l ? ht(f, l) : f];
1109
- }))
1110
- }, o = Mt(n.query, r), a = dt(o, e, s), i = [];
1111
- return { sql: a.replace(Ae, (u, f) => {
1112
- const l = s.values[Number(f)];
1113
- return i.push(l instanceof Date ? Et(l) : l), Le(e, i.length);
1114
- }), params: i };
1115
- }
1116
- export {
1117
- We as D,
1118
- X as Q,
1119
- Zt as S,
1120
- tr as a,
1121
- Ze as b,
1122
- se as c,
1123
- Pe as d,
1124
- _e as e,
1125
- xe as f,
1126
- Ye as g,
1127
- at as h,
1128
- Xe as i,
1129
- je as j,
1130
- Qe as k,
1131
- Ge as l,
1132
- ke as m,
1133
- w as n,
1134
- Ve as o,
1135
- Je as p,
1136
- Ke as q,
1137
- He as r,
1138
- ve as s,
1139
- Be as u,
1140
- ze as w
1141
- };