@nongt/visql-core 0.10.0 → 0.11.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,1108 +0,0 @@
1
- import { l as fe, z as Je, q as be, t as X, i as $e, y as ve, d as re, o as ye, b as Ue, j as he, f as Pe, A as He, D as Ke, B as Be, C as Oe, M as K, F as We, G as ce, u as oe, H as ze, I as Ve } from "./schema-KDJ1rpG5.js";
2
- import { C as Ye, E as Ze, F as er, G as Ge, H as Le, I as rr, J as _e, K as nr, L as tr, N as sr, t as ir, O as ar, P as or, A as lr, z as cr, b as ur, Q as je, M as fr, a as dr, R as Me, S as mr, w as yr, T as hr, U as gr } from "./params-kc6eNrpu.js";
3
- const we = (n) => typeof n == "object" && n !== null && !Array.isArray(n) && !(n instanceof Date), Se = (n) => typeof n.shared == "string";
4
- function ue(n, a) {
5
- if (Array.isArray(n)) {
6
- let r = !1;
7
- const b = n.flatMap((v) => {
8
- const l = ue(v, a);
9
- return l !== v && (r = !0), l === void 0 ? [] : [l];
10
- });
11
- return r ? b : n;
12
- }
13
- if (!we(n)) return n;
14
- if (Se(n)) return a(n);
15
- let c = !1;
16
- const i = Object.entries(n).map(([r, b]) => {
17
- const v = ue(b, a);
18
- return v !== b && (c = !0), [r, v];
19
- });
20
- return c ? Object.fromEntries(i) : n;
21
- }
22
- function Gr(n) {
23
- const a = new Map((n.shared ?? []).map((i) => [i.id, []])), c = (i, r) => {
24
- if (Array.isArray(i)) {
25
- i.forEach((b, v) => c(b, [...r, v]));
26
- return;
27
- }
28
- if (we(i)) {
29
- if (Se(i)) {
30
- const b = i.shared;
31
- a.set(b, [...a.get(b) ?? [], r]);
32
- return;
33
- }
34
- Object.entries(i).forEach(([b, v]) => c(v, [...r, b]));
35
- }
36
- };
37
- return c(n, []), a;
38
- }
39
- function Lr(n, a) {
40
- const c = /* @__PURE__ */ new Set([
41
- ...(a.shared ?? []).map((r) => r.name),
42
- ...Je(n).map((r) => r.name)
43
- ]);
44
- let i = 1;
45
- for (; c.has(`shared_query_${i}`); ) i += 1;
46
- return `shared_query_${i}`;
47
- }
48
- function pr(n, a) {
49
- const c = new Set(be(a).map(X));
50
- let i = n;
51
- for (let r = 2; c.has(i); r += 1) i = `${n}_${r}`;
52
- return i;
53
- }
54
- function br(n, a, c, i = fe(), r) {
55
- const b = n.shared ?? [], v = b.findIndex((d) => d.id === r), l = { id: i, name: a, query: c };
56
- return {
57
- ...n,
58
- shared: v < 0 ? [...b, l] : [...b.slice(0, v), l, ...b.slice(v)]
59
- };
60
- }
61
- const Qe = (n, a) => {
62
- var c;
63
- return (c = n.shared) == null ? void 0 : c.find((i) => i.id === a);
64
- };
65
- function _r(n, a, c, i = {}) {
66
- const r = Qe(n, c);
67
- if (!r) return a;
68
- const b = {
69
- id: i.id ?? fe(),
70
- shared: c,
71
- alias: pr(r.name, a),
72
- joinType: i.joinType ?? "inner",
73
- ...i.on ? { on: i.on } : {}
74
- };
75
- return { ...a, joins: [...a.joins, b] };
76
- }
77
- function Qr(n, a, c) {
78
- const i = Qe(n, c);
79
- return i ? { ...a, from: { shared: c, alias: i.name } } : a;
80
- }
81
- function Rr(n, a, c = fe(), i = []) {
82
- const r = Ye(n, i), b = r && Ze(r).find((f) => f.id === a);
83
- if (!b) return n;
84
- const v = new Set((n.shared ?? []).map((f) => f.name));
85
- let l = b.alias;
86
- for (let f = 2; v.has(l); f += 1) l = `${b.alias}_${f}`;
87
- const d = br(n, l, b.query, c, i[0]);
88
- return er(d, i, (f) => f.from.query && f.from.id === a ? { ...f, from: { shared: c, alias: b.alias } } : {
89
- ...f,
90
- joins: f.joins.map((I) => {
91
- if (I.id !== a || !I.query) return I;
92
- const { query: h, ...w } = I;
93
- return { ...w, shared: c };
94
- })
95
- });
96
- }
97
- function Re(n, a) {
98
- const { shared: c, ...i } = n;
99
- return "joinType" in i ? { ...i, query: a } : { id: fe(), alias: i.alias, query: a };
100
- }
101
- function Dr(n, a) {
102
- const c = new Map((n.shared ?? []).map((r) => [r.id, r.query])), i = a.reduce(
103
- (r, b) => typeof r == "object" && r !== null ? r[b] : void 0,
104
- n
105
- );
106
- return !we(i) || !Se(i) ? n : ue(n, (r) => {
107
- const b = c.get(r.shared);
108
- return r === i && b ? Re(r, b) : r;
109
- });
110
- }
111
- function Fr(n, a, c) {
112
- var i;
113
- return !((i = n.shared) != null && i.some((r) => r.id === a)) || c === "" ? n : {
114
- ...n,
115
- shared: n.shared.map((r) => r.id === a ? { ...r, name: c } : r)
116
- };
117
- }
118
- class $r extends Error {
119
- constructor(a) {
120
- super(`removeSharedQuery: "${a}" is a query's base: make it a sub query there instead`), this.name = "SharedBaseError";
121
- }
122
- }
123
- function qr(n, a, c = "subQueries") {
124
- var d;
125
- const i = (d = n.shared) == null ? void 0 : d.find((f) => f.id === a);
126
- if (!i) return n;
127
- const r = n.shared.filter((f) => f !== i), { shared: b, ...v } = n, l = r.length > 0 ? { ...v, shared: r } : v;
128
- return ue(l, (f) => {
129
- if (f.shared !== a) return f;
130
- if (c === "subQueries") return Re(f, i.query);
131
- if (!("joinType" in f)) throw new $r(i.name);
132
- });
133
- }
134
- const Ce = (n, a) => n.type === "binary" && n.operator === "IS NULL" && re(n.left, a);
135
- function ge(n) {
136
- var a;
137
- if (!n) return [];
138
- if (n.type === "logical" && n.operator === "AND") return n.operands.flatMap(ge);
139
- if (n.type === "binary" && (n.operator ?? "=") === "=" && n.left.type === "field" && ((a = n.right) == null ? void 0 : a.type) === "field")
140
- return [[n.left, n.right]];
141
- if (n.type === "logical" && n.operator === "OR" && n.operands.length === 2) {
142
- const [[c] = [], i] = [ge(n.operands[0]), n.operands[1]];
143
- if (c && i.type === "logical" && i.operator === "AND" && i.operands.length === 2 && Ce(i.operands[0], c[0]) && Ce(i.operands[1], c[1]))
144
- return [c];
145
- }
146
- return [];
147
- }
148
- function vr(n, a) {
149
- const c = n.groupBy ?? [];
150
- return c.length > 0 && c.every((i) => n.select.some((r) => re(r.expression, i.expression) && a.includes(ye(r) ?? "")));
151
- }
152
- function wr(n, a) {
153
- const c = X(n.from), i = /* @__PURE__ */ new Map([[c, n.from.table]]), r = [c], b = n.shared ?? [];
154
- return n.joins.map((v) => {
155
- var w, E;
156
- const { id: l } = v, d = Ge(v, b), f = X(v);
157
- i.set(f, v.table);
158
- const I = ge(v.on).flatMap(([T, O]) => [[T, O], [O, T]]).filter(([T, O]) => T.table === f && r.includes(O.table ?? ""));
159
- if (r.push(f), v.joinType === "cross")
160
- return {
161
- joinId: l,
162
- key: f,
163
- parent: c,
164
- side: d && Le(d) ? "one" : "cross"
165
- };
166
- if (v.table === void 0) {
167
- const T = I.length > 0 && d !== void 0 && !$e(d) && vr(d, I.map(([O]) => O.column));
168
- return {
169
- joinId: l,
170
- key: f,
171
- parent: ((w = I[0]) == null ? void 0 : w[1].table) ?? c,
172
- side: T ? "one" : "unknown"
173
- };
174
- }
175
- return I.map(([T, O]) => {
176
- const C = i.get(O.table), k = (L, F) => a.relations.some((q) => q.fromTable === L[0] && q.fromColumn === L[1].column && q.toTable === F[0] && q.toColumn === F[1].column);
177
- if (k([v.table, T], [C, O]))
178
- return {
179
- joinId: l,
180
- key: f,
181
- parent: O.table,
182
- side: "many"
183
- };
184
- if (k([C, O], [v.table, T]))
185
- return {
186
- joinId: l,
187
- key: f,
188
- parent: O.table,
189
- side: "one"
190
- };
191
- }).find((T) => T !== void 0) ?? {
192
- joinId: l,
193
- key: f,
194
- parent: ((E = I[0]) == null ? void 0 : E[1].table) ?? c,
195
- side: "unknown"
196
- };
197
- });
198
- }
199
- function pe(n, a, c = {}) {
200
- const i = wr(n, a).map((l) => l.side === "unknown" && c.unknown === "repeat" ? { ...l, side: "many" } : l), r = [X(n.from), ...i.map((l) => l.key)], b = (l) => {
201
- const d = /* @__PURE__ */ new Set([l]);
202
- return i.forEach((f) => {
203
- d.has(f.parent) && d.add(f.key);
204
- }), d;
205
- }, v = /* @__PURE__ */ new Set();
206
- return i.forEach((l) => {
207
- const d = b(l.key);
208
- l.side === "many" && r.filter((f) => !d.has(f)).forEach((f) => v.add(f)), l.side === "one" && d.forEach((f) => v.add(f)), l.side === "cross" && r.forEach((f) => v.add(f));
209
- }), v;
210
- }
211
- const Sr = /* @__PURE__ */ new Set(["SUM", "AVG", "COUNT"]);
212
- function Er(n, a) {
213
- return n.type === "field" ? n.table && a.has(n.table) ? [n.table] : [] : [...new Set(ve(n).flatMap((c) => Er(c, a)))];
214
- }
215
- function Xr(n, a) {
216
- const c = X(n.from);
217
- return n.joins.some((r) => r.joinType === "right" || r.joinType === "full") || pe(n, a).has(c) ? "many" : pe(n, a, { unknown: "repeat" }).has(c) ? "unknown" : "one";
218
- }
219
- function De(n, a, c = !1) {
220
- const i = n.type === "function" && Sr.has(n.name.toUpperCase()) && !n.distinct, r = c || i;
221
- return n.type === "field" ? r && n.table && a.has(n.table) ? [n.table] : [] : ve(n).flatMap((b) => De(b, a, r));
222
- }
223
- function kr(n, a) {
224
- const c = pe(n, a), i = /* @__PURE__ */ new Set(), r = (d) => {
225
- const f = d ? De(d, c) : [];
226
- return f.forEach((I) => i.add(I)), f.length > 0;
227
- }, b = n.select.filter((d) => r(d.expression)).map((d) => d.id), v = (n.orderBy ?? []).filter((d) => r(d.expression)).map((d) => d.id), l = r(n.having);
228
- return {
229
- tables: [...i],
230
- select: b,
231
- orderBy: v,
232
- having: l
233
- };
234
- }
235
- function Ar(n) {
236
- return !n.distinct || !n.orderBy ? [] : n.orderBy.filter(({ expression: a }) => !(a.type === "field" && !a.column)).filter(({ expression: a }) => n.select.length === 0 ? a.type !== "field" : !n.select.some((c) => re(c.expression, rr(a)))).map(({ id: a }) => a);
237
- }
238
- function Tr(n, a, c, i) {
239
- const r = new Map(i);
240
- return be(a).forEach((b) => {
241
- var l;
242
- const v = b.table !== void 0 ? (l = he(n, b.table)) == null ? void 0 : l.columns : (() => {
243
- const d = Ge(b, c);
244
- return d && _e(n, d, c);
245
- })();
246
- r.set(X(b), new Set((v ?? []).filter((d) => d.joinOnly).map((d) => d.name)));
247
- }), r;
248
- }
249
- function Nr(n, a) {
250
- const c = [], i = a.shared ?? [], r = (l, d, f, I) => {
251
- var w;
252
- if (Array.isArray(l)) {
253
- l.forEach((E, T) => r(E, [...d, T], f, I));
254
- return;
255
- }
256
- if (typeof l != "object" || l === null || l instanceof Date) return;
257
- const h = l;
258
- if (h.type === "field") {
259
- const { table: E, column: T } = h;
260
- !I && E && T && ((w = f.get(E)) != null && w.has(T)) && c.push(d);
261
- return;
262
- }
263
- if (h.type === "subquery") {
264
- v(h.query, [...d, "query"], !0);
265
- return;
266
- }
267
- if (h.type === "exists") {
268
- const E = h.query;
269
- v(E, [...d, "query"], !1, f);
270
- return;
271
- }
272
- Object.entries(h).forEach(([E, T]) => r(T, [...d, E], f, I));
273
- }, b = (l, d) => {
274
- "union" in l ? Ue(l).forEach((f, I) => v(f, [...d, "union", I], !0)) : v(l, d, !0);
275
- };
276
- function v(l, d, f, I) {
277
- var E, T, O;
278
- const h = Tr(n, l, i, I);
279
- l.from.query && b(l.from.query, [...d, "from", "query"]), l.joins.forEach((C, k) => {
280
- C.query && b(C.query, [...d, "joins", k, "query"]), C.on && r(C.on, [...d, "joins", k, "on"], h, !0);
281
- }), l.where && r(l.where, [...d, "where"], h, !1);
282
- const w = l;
283
- (E = w.select) == null || E.forEach((C, k) => r(
284
- C.expression,
285
- [...d, "select", k, "expression"],
286
- h,
287
- f
288
- )), (T = w.groupBy) == null || T.forEach((C, k) => r(
289
- C.expression,
290
- [...d, "groupBy", k, "expression"],
291
- h,
292
- f
293
- )), w.having && r(w.having, [...d, "having"], h, !1), (O = w.orderBy) == null || O.forEach((C, k) => r(
294
- C.expression,
295
- [...d, "orderBy", k, "expression"],
296
- h,
297
- !1
298
- ));
299
- }
300
- return i.forEach((l, d) => b(l.query, ["shared", d, "query"])), v(a, [], !1), c;
301
- }
302
- function Jr(n, a) {
303
- return !(n === "mssql" && a === "REGEXP");
304
- }
305
- function xr(n, a) {
306
- return !(n === "mysql" && a === "full");
307
- }
308
- const Pr = [
309
- "invalidStructure",
310
- "duplicateId",
311
- "unknownTable",
312
- "unknownColumn",
313
- "tableNotInQuery",
314
- "unqualifiedField",
315
- "incomplete",
316
- "argCount",
317
- "ambiguousTable",
318
- "duplicateTableName",
319
- "derivedColumnName",
320
- "unknownFunction",
321
- "joinOrder",
322
- "distinctSort",
323
- "notGrouped",
324
- "unknownAggregate",
325
- "misplacedAggregate",
326
- "paramConflict",
327
- "fanOut",
328
- "crossJoin",
329
- "unlinkedJoin",
330
- "drillAcrossOutOfStep",
331
- "drillAcrossFilterMixed",
332
- "tooLong",
333
- "dialectUnsupported",
334
- "subqueryColumns",
335
- "notInSubquery",
336
- "noLimit",
337
- "limitTooHigh",
338
- "typeMismatch",
339
- "invalidPattern",
340
- "unionColumns",
341
- "unionTypes",
342
- "sharedOrder",
343
- "unusedShared",
344
- "joinOnlyColumn"
345
- ], Hr = [
346
- "fanOut",
347
- "crossJoin",
348
- "unlinkedJoin",
349
- "drillAcrossFilterMixed",
350
- "notInSubquery",
351
- "noLimit",
352
- "limitTooHigh",
353
- "typeMismatch",
354
- "unknownAggregate",
355
- "unusedShared"
356
- ];
357
- function Ir(n) {
358
- return [...n.matchAll(/([A-Za-z_][A-Za-z0-9_]*)|\[(\d+)\]/g)].map(([, a, c]) => a ?? Number(c));
359
- }
360
- const le = (n) => n === "integer" ? "number" : n === "dateTime" ? "date" : n, z = {
361
- text: "text",
362
- integer: "a whole number",
363
- number: "a number",
364
- date: "a date",
365
- dateTime: "a date and time",
366
- time: "a time of day",
367
- boolean: "yes / no"
368
- }, x = (n) => typeof n == "object" && n !== null && !Array.isArray(n), U = (n) => typeof n == "string", Br = ["day", "week", "month", "year"], Or = (n) => x(n) && Br.includes(n.unit) && Number.isSafeInteger(n.offset) && (n.anchor === void 0 || n.unit !== "day" && (n.anchor === "start" || n.anchor === "end")), Y = (n) => n === void 0 || U(n), jr = (n) => n === null || U(n) || typeof n == "boolean" || typeof n == "bigint" || typeof n == "number" && Number.isFinite(n) || n instanceof Date && !Number.isNaN(n.getTime()), me = (n) => x(n) && n.type === "literal" && n.value === "" && n.empty !== !0;
369
- function Kr(n, a, c = {}) {
370
- var Te, Ne;
371
- const i = [], r = (e, t, o, s = "error") => {
372
- i.push({
373
- kind: e,
374
- severity: s,
375
- path: t,
376
- pathSegments: Ir(t),
377
- message: o
378
- });
379
- };
380
- if (!x(a) || !U(a.id) || a.id === "")
381
- return r("invalidStructure", "", "a query is an object with a non-empty string id"), i;
382
- if (!("from" in a)) return i;
383
- const b = Pe(n, c.tableFilter, c.columnFilter), v = He(c.functions ?? Ke);
384
- let l = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map(), f;
385
- const I = (e, t, o, s) => {
386
- U(e) && e.length > t && r("tooLong", o, `${s} is longer than ${t} characters`);
387
- }, h = /* @__PURE__ */ new Set(), w = x(a) && Array.isArray(a.shared) ? a.shared : [], E = new Set(w.flatMap((e) => x(e) && U(e.id) ? [e.id] : [])), T = /* @__PURE__ */ new Map(), O = /* @__PURE__ */ new Set();
388
- let C;
389
- const k = (e, t) => {
390
- l.has(e) && r("duplicateTableName", t, `two tables named "${e}"`);
391
- }, L = (e, t) => {
392
- Oe.includes(e) && !xr(c.dialect, e) && r("dialectUnsupported", t, `${e.toUpperCase()} JOIN isn't in this database`);
393
- }, F = (e, t, o = !1) => {
394
- if (o && x(e) && e.query !== void 0) {
395
- C(e, t);
396
- return;
397
- }
398
- if (o && x(e) && e.shared !== void 0) {
399
- const { shared: $, alias: u } = e, m = U(u) && u !== "";
400
- if (!U($) || !m || e.table !== void 0) {
401
- r("invalidStructure", t, "a shared query's place has a string `shared` and an `alias`, and no `table`"), m && (k(u, `${t}.alias`), l.set(u, void 0));
402
- return;
403
- }
404
- I(u, K, `${t}.alias`, "an alias"), k(u, `${t}.alias`), O.add($), E.has($) ? T.has($) || r("sharedOrder", `${t}.shared`, "a shared query can use only those before it") : r("unknownTable", `${t}.shared`, `no shared query "${$}"`), l.set(u, T.get($));
405
- return;
406
- }
407
- if (!x(e) || !U(e.table) || !Y(e.alias)) {
408
- r("invalidStructure", t, "a table entry has a string `table` and optional `alias`");
409
- return;
410
- }
411
- I(e.alias, K, `${t}.alias`, "an alias");
412
- const s = b.tables.find(($) => $.name === e.table);
413
- s || r("unknownTable", `${t}.table`, `unknown table "${e.table}"`), U(e.alias) && e.alias !== "" ? (k(e.alias, `${t}.alias`), l.set(e.alias, s), d.set(e.table, e.alias)) : (k(e.table, `${t}.table`), l.set(e.table, s));
414
- }, q = (e, t, o) => {
415
- var g;
416
- if (!e) return;
417
- const { args: s, name: $ } = e, u = s.filter((p) => !p.optional).length, m = (g = s[s.length - 1]) != null && g.variadic ? 1 / 0 : s.length;
418
- t < u ? r("incomplete", o, `${$} needs ${u} argument(s)`) : t > m && r("argCount", o, `${$} takes ${m} argument(s)`);
419
- };
420
- let D, P, ne;
421
- const de = (e) => {
422
- const t = e.table && (l.get(e.table) ?? (f == null ? void 0 : f.get(e.table)));
423
- if (!t || Array.isArray(t)) return;
424
- const o = t.columns.find((s) => s.name === e.column);
425
- return o && hr(o.type);
426
- }, W = (e) => mr(e, de, v), V = c.typeMismatch ?? "warning", Z = (e, t, o) => {
427
- if (e.type === "literal") {
428
- if (e.value === null || e.value === "" && !e.empty || typeof e.value == "number" && !je(e.value) || yr(e.value, t) !== void 0) return;
429
- const u = e.value instanceof Date ? "a date" : JSON.stringify(String(e.value));
430
- r("typeMismatch", o, `${u} isn't ${z[t]}`, V);
431
- return;
432
- }
433
- const s = W(e);
434
- if (s === void 0 || le(s) === le(t)) return;
435
- const $ = `${z[s]} compared with ${z[t]}`;
436
- r("typeMismatch", o, $, V);
437
- }, te = (e) => e && e.type !== "literal" ? W(e) : void 0, Fe = (e, t) => {
438
- const { operator: o, left: s, right: $ } = e;
439
- if (!$) return;
440
- const u = (g, p, N) => {
441
- if (g.type !== "param" || !g.relative) return;
442
- const y = te(p);
443
- if (y === void 0 || y === "date" || y === "dateTime") return;
444
- const A = `a relative date compared with ${z[y]}`;
445
- r("typeMismatch", N, A, V);
446
- };
447
- if (u($, s, `${t}.right`), u(s, $, `${t}.left`), o === "LIKE" || o === "REGEXP") {
448
- const g = te(s);
449
- if (g !== void 0 && g !== "text") {
450
- const p = `${o} matches text, not ${z[g]}`;
451
- r("typeMismatch", `${t}.left`, p, V);
452
- }
453
- if (Z($, "text", `${t}.right`), o === "REGEXP" && $.type === "literal" && U($.value))
454
- try {
455
- new RegExp($.value);
456
- } catch (p) {
457
- const N = `not a regular expression: ${p.message}`;
458
- r("invalidPattern", `${t}.right`, N);
459
- }
460
- return;
461
- }
462
- const m = te(s);
463
- if (o === "IN" || o === "BETWEEN") {
464
- if (m === void 0 || $.type !== "list") return;
465
- $.items.forEach((g, p) => Z(g, m, `${t}.right.items[${p}]`));
466
- return;
467
- }
468
- if (m !== void 0) Z($, m, `${t}.right`);
469
- else {
470
- const g = te($);
471
- g !== void 0 && Z(s, g, `${t}.left`);
472
- }
473
- }, Ee = (e) => {
474
- const t = e.map(([o]) => o.type === "literal" ? Me(o) : W(o)).find((o) => o !== void 0);
475
- t !== void 0 && e.forEach(([o, s]) => Z(o, t, s));
476
- }, R = (e, t, o = !1) => {
477
- if (!x(e) || !U(e.type)) {
478
- r("invalidStructure", t, "an expression is an object with a string `type`");
479
- return;
480
- }
481
- const s = (u) => r("invalidStructure", t, u), $ = (u, m) => {
482
- e[u] !== void 0 && R(e[u], `${t}.${u}`, m);
483
- };
484
- switch (o && e.type === "exists" && s("EXISTS is a condition, not a value"), Y(e.fromSelect) || s("`fromSelect` is a column's id"), e.type) {
485
- case "literal":
486
- if (!jr(e.value))
487
- s("a literal value is a string, number, boolean, date or null");
488
- else if (e.empty !== void 0 && typeof e.empty != "boolean")
489
- s("a literal's `empty` is a boolean");
490
- else if (me(e))
491
- r("incomplete", t, "a value not filled in");
492
- else if (typeof e.value == "number" && !je(e.value)) {
493
- const u = `a number with more than ${fr} significant digits is written as another number`;
494
- r("tooLong", `${t}.value`, u);
495
- } else
496
- I(e.value, dr, `${t}.value`, "a text value");
497
- break;
498
- case "param":
499
- (!U(e.name) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(e.name)) && s("a param has a plain identifier as its `name`"), e.relative !== void 0 && !Or(e.relative) && s("a relative date has a `unit` (day, week, month or year), a whole `offset`, and an `anchor` (start or end) only for a week, month or year"), I(e.name, K, `${t}.name`, "a parameter's name");
500
- break;
501
- case "field":
502
- if (!Y(e.table) || !Y(e.column))
503
- s("a field has string `table` and `column`");
504
- else if (e.column === void 0 || e.column === "")
505
- r("incomplete", t, "a field with no column picked");
506
- else if (e.table === void 0 || e.table === "")
507
- r("unqualifiedField", t, `column "${e.column}" names no table`);
508
- else if (l.has(e.table)) {
509
- const u = l.get(e.table);
510
- if (!(Array.isArray(u) ? u.includes(e.column) : !u || u.columns.some((g) => g.name === e.column))) {
511
- const g = `${e.table}.${e.column}`;
512
- r("unknownColumn", `${t}.column`, `unknown column "${g}"`);
513
- }
514
- } else {
515
- const u = d.get(e.table);
516
- let m = `table "${e.table}" isn't in the query`;
517
- u ? m = `table "${e.table}" is named "${u}" in the query: use that` : f != null && f.has(e.table) && (m = `table "${e.table}" is the outer query's: only the EXISTS link names it`), r("tableNotInQuery", `${t}.table`, m);
518
- }
519
- break;
520
- case "function": {
521
- if (!U(e.name) || !Array.isArray(e.args)) {
522
- s("a function has a string `name` and an `args` array");
523
- break;
524
- }
525
- !c.allowUnknownFunctions && !v[e.name.toUpperCase()] && r("unknownFunction", `${t}.name`, `function "${e.name}" isn't allowed`);
526
- const u = v[e.name.toUpperCase()];
527
- if (c.dialect && (u != null && u.dialects) && !u.dialects.includes(c.dialect) && r("dialectUnsupported", `${t}.name`, `${u.name} isn't in this database`), I(e.name, K, `${t}.name`, "a function's name"), q(u, e.args.length, `${t}.args`), e.distinct !== void 0 && typeof e.distinct != "boolean" && s("a function's `distinct` is a boolean"), e.distinct === !0 && c.dialect === "mssql" && e.name.toUpperCase() === "STRING_AGG" && r("dialectUnsupported", t, "SQL Server's STRING_AGG can't join only different values"), e.args.forEach((m, g) => {
528
- var y, A;
529
- const p = i.length;
530
- R(m, `${t}.args[${g}]`, !0), u && ((y = ce(u, g)) == null ? void 0 : y.kind) === "type-name" && x(m) && I(m.value, ur, `${t}.args[${g}].value`, "a type name"), u && ((A = ce(u, g)) == null ? void 0 : A.kind) === "fixed-text" && x(m) && !(m.type === "literal" && U(m.value)) && s(`${u.name}'s ${ce(u, g).label} is a text value`);
531
- const N = !i.slice(p).some((Q) => Q.kind === "invalidStructure");
532
- u != null && u.aggregate && N && oe(m, v) && r(
533
- "misplacedAggregate",
534
- `${t}.args[${g}]`,
535
- "an aggregate can't be inside another: sum up per group in a sub query first"
536
- );
537
- }), e.orderBy !== void 0) {
538
- if (!Array.isArray(e.orderBy)) {
539
- s("a function's `orderBy` is an array");
540
- break;
541
- }
542
- e.name.toUpperCase() !== "STRING_AGG" && s("only STRING_AGG takes an `orderBy`"), e.orderBy.forEach((m, g) => {
543
- const p = `${t}.orderBy[${g}]`;
544
- if (!x(m) || m.direction !== "asc" && m.direction !== "desc") {
545
- r("invalidStructure", p, "a sort key has an `expression` and a `direction`");
546
- return;
547
- }
548
- const N = i.length;
549
- R(m.expression, `${p}.expression`, !0), !i.slice(N).some((y) => y.kind === "invalidStructure") && (oe(m.expression, v) && r("misplacedAggregate", `${p}.expression`, "an aggregate can't be inside another"), e.distinct === !0 && c.dialect === "postgres" && !re(m.expression, e.args[0]) && r(
550
- "dialectUnsupported",
551
- `${p}.expression`,
552
- "PostgreSQL orders STRING_AGG of different values by the value only"
553
- ));
554
- });
555
- }
556
- break;
557
- }
558
- case "binary": {
559
- e.operator !== void 0 && !lr.includes(e.operator) && s(`unknown operator ${JSON.stringify(e.operator)}`), e.operator === "REGEXP" && c.dialect === "mssql" && r("dialectUnsupported", t, "SQL Server has no REGEXP");
560
- const u = i.length;
561
- R(e.left, `${t}.left`, !0);
562
- const m = i.slice(u).some((g) => g.kind === "incomplete");
563
- if (cr(e.operator))
564
- e.right !== void 0 && s(`${String(e.operator)} takes no right side`);
565
- else if (e.right === void 0)
566
- r("incomplete", `${t}.right`, "a comparison with nothing to compare to");
567
- else if (x(e.right) && e.right.type === "literal" && e.right.value === null && e.operator !== "IS NOT DISTINCT FROM")
568
- r("incomplete", `${t}.right`, "compared with NULL (never true): use IS NULL");
569
- else if (x(e.right) && e.right.type === "subquery")
570
- e.operator === "IN" ? P(e.right, `${t}.right`) : r("invalidStructure", `${t}.right`, "a sub query is only IN's right side");
571
- else if (e.operator === "BETWEEN") {
572
- const { right: g } = e, p = x(g) && g.type === "list" && Array.isArray(g.items) ? g.items : void 0;
573
- (p == null ? void 0 : p.length) !== 2 ? r("invalidStructure", `${t}.right`, "BETWEEN takes its two bounds as a list (expr.between)") : p.forEach((N, y) => {
574
- const A = `${t}.right.items[${y}]`;
575
- x(N) && N.type === "literal" && N.value === null ? r("incomplete", A, "a bound of NULL (never true)") : m && me(N) || R(N, A, !0);
576
- });
577
- } else x(e.right) && e.right.type === "list" ? e.operator === "IN" ? ne(e.right, `${t}.right`) : r("invalidStructure", `${t}.right`, "a list is only IN's or BETWEEN's right side") : e.operator === "IN" ? r("invalidStructure", `${t}.right`, "IN takes a list (expr.list) or a sub query") : m && me(e.right) || R(e.right, `${t}.right`, !0);
578
- i.slice(u).some((g) => g.kind === "invalidStructure") || Fe(e, t);
579
- break;
580
- }
581
- case "logical":
582
- if (e.operator !== "AND" && e.operator !== "OR" && s("a logical operator is AND or OR"), !Array.isArray(e.operands)) {
583
- s("a logical node has an `operands` array");
584
- break;
585
- }
586
- e.operands.length === 0 && r("incomplete", t, "an empty AND/OR group"), e.operands.forEach((u, m) => R(u, `${t}.operands[${m}]`));
587
- break;
588
- case "not": {
589
- R(e.operand, `${t}.operand`);
590
- const { operand: u } = e;
591
- x(u) && u.type === "binary" && u.operator === "IN" && x(u.right) && u.right.type === "subquery" && r("notInSubquery", t, "NOT IN keeps no rows at all if the sub query gives a NULL: NOT EXISTS doesn't", "warning");
592
- break;
593
- }
594
- case "if": {
595
- ["condition", "then"].forEach((m) => {
596
- e[m] === void 0 && r("incomplete", `${t}.${m}`, `an IF with no ${m}`);
597
- });
598
- const u = i.length;
599
- $("condition", !1), $("then", !0), $("else", !0), i.slice(u).some((m) => m.kind === "invalidStructure") || Ee(
600
- ["then", "else"].filter((m) => e[m] !== void 0).map((m) => [e[m], `${t}.${m}`])
601
- );
602
- break;
603
- }
604
- case "case": {
605
- const u = i.length;
606
- $("subject", !0), Array.isArray(e.branches) ? (e.branches.length === 0 && r("incomplete", t, "a CASE with no WHEN"), e.branches.forEach((g, p) => {
607
- if (!x(g)) {
608
- const N = `${t}.branches[${p}]`;
609
- r("invalidStructure", N, "a branch has `when` and `then`");
610
- return;
611
- }
612
- R(g.when, `${t}.branches[${p}].when`, e.subject !== void 0), R(g.then, `${t}.branches[${p}].then`, !0);
613
- })) : s("a case node has a `branches` array");
614
- const m = i.length;
615
- $("else", !0), Array.isArray(e.branches) && i.slice(u).concat(i.slice(m)).every((g) => g.kind !== "invalidStructure") && Ee([
616
- ...e.branches.map((g, p) => [g.then, `${t}.branches[${p}].then`]),
617
- ...e.else === void 0 ? [] : [[e.else, `${t}.else`]]
618
- ]);
619
- break;
620
- }
621
- case "exists":
622
- D(e, t);
623
- break;
624
- case "subquery":
625
- s("a sub query is only IN's right side");
626
- break;
627
- case "list":
628
- s("a list is only IN's right side");
629
- break;
630
- default:
631
- s(`unknown expression type ${JSON.stringify(e.type)}`);
632
- }
633
- };
634
- ne = (e, t) => {
635
- Array.isArray(e.items) ? e.items.length === 0 ? r("incomplete", t, "IN with no values") : e.items.forEach((o, s) => R(o, `${t}.items[${s}]`, !0)) : r("invalidStructure", t, "a list has an `items` array");
636
- }, P = (e, t) => {
637
- const { id: o, query: s } = e;
638
- if (!U(o) || o === "" || !x(s)) {
639
- r("invalidStructure", t, "a sub query has a non-empty string `id` and a `query`");
640
- return;
641
- }
642
- h.has(o) && r("duplicateId", `${t}.id`, `the id "${o}" is used twice`), h.add(o);
643
- const $ = { inQuery: l, aliasOf: d, outerTables: f };
644
- l = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map(), f = void 0;
645
- const u = i.length;
646
- se(s, `${t}.query`, !1), { inQuery: l, aliasOf: d, outerTables: f } = $;
647
- const m = i.length === u;
648
- (Array.isArray(s.select) ? s.select : []).length !== 1 && r("subqueryColumns", `${t}.query.select`, "a sub query after IN picks exactly one column to compare with"), m && ie(s, `${t}.query`);
649
- }, D = (e, t) => {
650
- const { query: o, link: s } = e;
651
- if (!x(o) || !Array.isArray(o.joins)) {
652
- r("invalidStructure", `${t}.query`, "an EXISTS has a `query` with `from` and `joins`");
653
- return;
654
- }
655
- const $ = { inQuery: l, aliasOf: d, outerTables: f };
656
- l = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map(), f = $.inQuery, [
657
- [o.from, `${t}.query.from`],
658
- ...o.joins.map((p, N) => [p, `${t}.query.joins[${N}]`])
659
- ].forEach(([p, N], y) => {
660
- const A = new Set(l.keys());
661
- F(p, N, y > 0), y > 0 && x(p) && L(p.joinType, `${N}.joinType`), [...l.keys()].filter((Q) => !A.has(Q) && $.inQuery.has(Q)).forEach((Q) => r(
662
- "ambiguousTable",
663
- `${N}.table`,
664
- `"${Q}" is a table of the query around it too: give it an alias`
665
- ));
666
- });
667
- const m = [
668
- ...o.joins.map((p, N) => [
669
- x(p) ? p.on : void 0,
670
- `${t}.query.joins[${N}].on`
671
- ]),
672
- [o.where, `${t}.query.where`]
673
- ];
674
- m.forEach(([p, N]) => {
675
- p !== void 0 && R(p, N);
676
- }), o.joins.forEach((p, N) => {
677
- x(p) && p.joinType !== "cross" && p.on === void 0 && r("incomplete", `${t}.query.joins[${N}].on`, "a join with no ON condition");
678
- });
679
- const g = { inQuery: l, aliasOf: d };
680
- l = new Map([...$.inQuery, ...g.inQuery]), d = new Map([...$.aliasOf, ...g.aliasOf]), f = void 0, R(s, `${t}.link`), { inQuery: l, aliasOf: d, outerTables: f } = $, [...m, [s, `${t}.link`]].forEach(([p, N]) => {
681
- x(p) && oe(p, v) && r("misplacedAggregate", N, "an aggregate (SUM, COUNT, …) can't be used here");
682
- });
683
- };
684
- const ee = (e, t, o = []) => {
685
- const s = new Set(o);
686
- e.forEach(($, u) => {
687
- !x($) || !U($.id) || $.id === "" ? r("invalidStructure", `${t}[${u}]`, "every entry has a non-empty string id") : s.has($.id) ? r("duplicateId", `${t}[${u}].id`, `id "${$.id}" is used twice`) : s.add($.id);
688
- });
689
- }, ke = (e, t, o) => Array.isArray(e[t]) ? e[t] : (e[t] !== void 0 && r("invalidStructure", o, `\`${t}\` is an array`), []), se = (e, t, o) => {
690
- const s = (y) => t ? `${t}.${y}` : y;
691
- F(e.from, s("from"), !0);
692
- const { from: $ } = e, u = x($) && $.query !== void 0 ? $.id : void 0;
693
- x($) && $.query !== void 0 && (!U(u) || u === "") && r("invalidStructure", s("from"), "a derived table has a non-empty string id");
694
- const m = Array.isArray(e.joins) ? e.joins : [];
695
- Array.isArray(e.joins) || r("invalidStructure", s("joins"), "`joins` is an array"), m.forEach((y, A) => F(y, s(`joins[${A}]`), !0)), ee(m, s("joins"), U(u) ? [u] : []), m.forEach((y, A) => {
696
- if (x(y)) {
697
- if (Oe.includes(y.joinType))
698
- L(y.joinType, s(`joins[${A}].joinType`));
699
- else {
700
- const Q = JSON.stringify(y.joinType);
701
- r("invalidStructure", s(`joins[${A}].joinType`), `unknown join type ${Q}`);
702
- }
703
- y.joinType !== "cross" && (y.on !== void 0 ? R(y.on, s(`joins[${A}].on`)) : r("incomplete", s(`joins[${A}].on`), "a join with no ON condition"));
704
- }
705
- }), e.where !== void 0 && R(e.where, s("where"));
706
- const g = Array.isArray(e.select) ? e.select : [];
707
- Array.isArray(e.select) || r("invalidStructure", s("select"), "`select` is an array"), ee(g, s("select")), g.forEach((y, A) => {
708
- x(y) && (I(y.alias, K, s(`select[${A}].alias`), "an alias"), Y(y.alias) || r("invalidStructure", s(`select[${A}].alias`), "an alias is a string"), R(y.expression, s(`select[${A}].expression`), !0));
709
- });
710
- const p = ke(e, "groupBy", s("groupBy"));
711
- if (ee(p, s("groupBy")), p.forEach((y, A) => {
712
- x(y) && (Y(y.fromSelect) || r("invalidStructure", s(`groupBy[${A}].fromSelect`), "`fromSelect` is a column's id"), R(y.expression, s(`groupBy[${A}].expression`), !0));
713
- }), e.having !== void 0 && R(e.having, s("having")), e.distinct !== void 0 && typeof e.distinct != "boolean" && r("invalidStructure", s("distinct"), "`distinct` is a boolean"), !o) {
714
- ["orderBy", "limit", "offset", "shared"].forEach((y) => {
715
- e[y] !== void 0 && r("invalidStructure", s(y), `a derived table has no \`${y}\``);
716
- });
717
- return;
718
- }
719
- const N = ke(e, "orderBy", "orderBy");
720
- ee(N, "orderBy"), N.forEach((y, A) => {
721
- x(y) && (y.direction !== "asc" && y.direction !== "desc" && r("invalidStructure", `orderBy[${A}].direction`, 'a sort direction is "asc" or "desc"'), R(y.expression, `orderBy[${A}].expression`, !0));
722
- }), ["limit", "offset"].forEach((y) => {
723
- const A = e[y];
724
- A !== void 0 && !(Number.isInteger(A) && A >= 0) ? r("invalidStructure", y, `\`${y}\` is a non-negative integer`) : A !== void 0 && !Number.isSafeInteger(A) && r("tooLong", y, `\`${y}\` is past ${Number.MAX_SAFE_INTEGER}, which is exact`);
725
- });
726
- }, qe = (e, t, o) => {
727
- const s = `${t}.query`, { union: $ } = e;
728
- if (!Array.isArray($) || $.length < 1 || typeof e.all != "boolean") {
729
- r("invalidStructure", s, "a union has one or more branches in `union`, and a boolean `all`"), k(o, `${t}.alias`), l.set(o, void 0);
730
- return;
731
- }
732
- let u = [];
733
- const m = [];
734
- let g = !0;
735
- $.forEach((p, N) => {
736
- const y = `${s}.union[${N}]`;
737
- if (!x(p)) {
738
- r("invalidStructure", y, "a union's branch is a query"), g = !1;
739
- return;
740
- }
741
- const A = { inQuery: l, aliasOf: d, outerTables: f };
742
- l = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map(), f = void 0;
743
- const Q = i.length;
744
- se(p, y, !1);
745
- const H = i.length === Q, S = (Array.isArray(p.select) ? p.select : []).filter(x), B = H ? S.map((j) => j.expression.type === "literal" ? Me(j.expression) : W(j.expression)) : [];
746
- if ({ inQuery: l, aliasOf: d, outerTables: f } = A, !H) {
747
- g = !1;
748
- return;
749
- }
750
- ie(p, y);
751
- const G = S.map((j) => ye(j));
752
- if (S.length === 0) {
753
- r("unionColumns", `${y}.select`, "a union's branch names its columns"), g = !1;
754
- return;
755
- }
756
- if (N === 0)
757
- u = G, G.forEach((j, M) => {
758
- if (j) return;
759
- r("derivedColumnName", `${y}.select[${M}]`, "a union's column needs an alias: nothing outside could name it");
760
- }), G.forEach((j, M) => {
761
- j && G.indexOf(j) !== M && r("derivedColumnName", `${y}.select[${M}]`, `two columns named "${j}"`);
762
- });
763
- else if (G.length !== u.length) {
764
- const j = `${G.length} column(s), where the first branch has ${u.length}`;
765
- r("unionColumns", `${y}.select`, j);
766
- return;
767
- } else
768
- G.forEach((j, M) => {
769
- if (j === u[M]) return;
770
- const _ = `column ${M + 1} is "${String(u[M])}" in the first branch, not "${String(j)}"`;
771
- r("unionColumns", `${y}.select[${M}]`, _);
772
- });
773
- B.forEach((j, M) => {
774
- if (j === void 0) return;
775
- const _ = m[M];
776
- if (_ === void 0)
777
- m[M] = j;
778
- else if (le(_) !== le(j)) {
779
- const J = `column "${String(u[M])}" is ${z[j]} here, ${z[_]} in a branch before`;
780
- r("unionTypes", `${y}.select[${M}].expression`, J);
781
- }
782
- });
783
- }), k(o, `${t}.alias`), l.set(o, g ? u.filter((p) => p !== void 0) : void 0);
784
- };
785
- C = (e, t) => {
786
- const { query: o, alias: s } = e;
787
- if (e.table === void 0 && x(o) && o.union !== void 0 && U(s) && s !== "") {
788
- I(s, K, `${t}.alias`, "an alias"), qe(o, t, s);
789
- return;
790
- }
791
- if (e.table !== void 0 || !x(o) || !U(s) || s === "") {
792
- r("invalidStructure", t, "a derived table has a `query` and an `alias`, and no `table`"), U(s) && s !== "" && (k(s, `${t}.alias`), l.set(s, void 0));
793
- return;
794
- }
795
- I(s, K, `${t}.alias`, "an alias");
796
- const $ = { inQuery: l, aliasOf: d, outerTables: f };
797
- l = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map(), f = void 0;
798
- const u = i.length;
799
- se(o, `${t}.query`, !1), { inQuery: l, aliasOf: d, outerTables: f } = $;
800
- const m = Array.isArray(o.select) ? o.select : [], g = [], p = (A, Q) => {
801
- g.includes(A) ? r("derivedColumnName", Q, `two columns named "${A}"`) : g.push(A);
802
- };
803
- m.forEach((A, Q) => {
804
- if (!x(A) || !x(A.expression)) return;
805
- const H = ye(A);
806
- H ? p(H, `${t}.query.select[${Q}]`) : r("derivedColumnName", `${t}.query.select[${Q}]`, "a derived table's column needs an alias: nothing outside could name it");
807
- });
808
- const N = i.length === u;
809
- N && m.length === 0 && _e(b, o, w).forEach((A) => p(A.name, `${t}.query.select`)), k(s, `${t}.alias`), l.set(s, N || m.length > 0 ? g : void 0), N && ie(o, `${t}.query`);
810
- const { drillAcross: y } = e;
811
- y !== void 0 && !(x(y) && typeof y.synced == "boolean" && Number.isInteger(y.copied) && y.copied >= 0) && r("invalidStructure", `${t}.drillAcross`, "`drillAcross` has a boolean `synced` and a non-negative integer `copied`");
812
- };
813
- const ie = (e, t) => {
814
- var N, y, A, Q, H;
815
- const o = (S) => t ? `${t}.${S}` : S, s = sr(e);
816
- if (s) {
817
- const S = e.joins.findIndex((B) => (B.table ?? X(B)) === s.table);
818
- r(
819
- "joinOrder",
820
- o(`joins[${S}].on`),
821
- `the join condition of "${s.table}" uses "${s.needs}", which is joined after it`
822
- );
823
- }
824
- const $ = (S, B) => {
825
- oe(S, v) && r("misplacedAggregate", B, "an aggregate (SUM, COUNT, …) can't be used here");
826
- };
827
- $(e.where, o("where")), e.joins.forEach((S, B) => {
828
- S.joinType !== "cross" && $(S.on, o(`joins[${B}].on`));
829
- }), (N = e.groupBy) == null || N.forEach((S, B) => $(S.expression, o(`groupBy[${B}].expression`)));
830
- const u = We(e, v), m = "isn't a group key or an aggregate (SUM, COUNT, …)";
831
- if (u.selectAll && r("notGrouped", o("select"), "a grouped query has to pick its columns, not *"), e.select.forEach((S, B) => {
832
- u.select.includes(S.id) && r("notGrouped", o(`select[${B}].expression`), `this column ${m}`);
833
- }), (y = e.orderBy) == null || y.forEach((S, B) => {
834
- u.orderBy.includes(S.id) && r("notGrouped", `orderBy[${B}].expression`, `this sort key ${m}`);
835
- }), u.having && r("notGrouped", o("having"), `a column in this condition ${m}`), c.dialect === "mssql") {
836
- const S = [], B = (M, _) => {
837
- const [J, ae] = M.length <= _.length ? [M, _] : [_, M];
838
- return J.every((xe, Ie) => xe.direction === ae[Ie].direction && re(xe.expression, ae[Ie].expression));
839
- }, G = (M) => {
840
- var J;
841
- return [...M.type === "function" && ((J = M.orderBy) != null && J.length) ? [M.orderBy] : [], ...ve(M).flatMap(G)];
842
- }, j = (M, _) => {
843
- G(M).forEach((J) => {
844
- S.some((ae) => !B(ae, J)) && r(
845
- "dialectUnsupported",
846
- _,
847
- "SQL Server sorts every STRING_AGG of a query alike: this one's order differs"
848
- ), S.push(J);
849
- });
850
- };
851
- e.select.forEach((M, _) => j(M.expression, o(`select[${_}].expression`))), e.having && j(e.having, o("having")), (A = e.orderBy) == null || A.forEach((M, _) => j(M.expression, `orderBy[${_}].expression`));
852
- }
853
- if (c.allowUnknownFunctions && Be(e, v)) {
854
- const S = (B, G) => {
855
- ze(B, v) && r(
856
- "unknownAggregate",
857
- G,
858
- "a function the editor doesn't know: it isn't made a group key, in case it sums rows up — declare it in `functions` (`aggregate: true` if it does)",
859
- "warning"
860
- );
861
- };
862
- e.select.forEach((B, G) => S(B.expression, o(`select[${G}].expression`))), (Q = e.orderBy) == null || Q.forEach((B, G) => S(B.expression, `orderBy[${G}].expression`)), S(e.having, o("having"));
863
- }
864
- e.joins.forEach((S, B) => {
865
- if (S.joinType === "cross" || !S.on) return;
866
- const G = ir(S.on), j = X(S), M = be(e).slice(0, B + 1).map(X);
867
- G.some((_) => _ !== j && !M.includes(_)) || G.includes(j) && G.some((_) => M.includes(_)) || r(
868
- "unlinkedJoin",
869
- o(`joins[${B}].on`),
870
- `the join condition of "${j}" doesn't compare it with a table joined before it: every row meets every row it lets through`,
871
- "warning"
872
- );
873
- }), e.joins.forEach((S, B) => {
874
- var j;
875
- if (!S.query || !((j = S.drillAcross) != null && j.synced)) return;
876
- ar(b, e, S) || r(
877
- "drillAcrossOutOfStep",
878
- o(`joins[${B}]`),
879
- `"${S.alias}" is kept in step with the query but doesn't match its grouping`
880
- );
881
- const G = $e(S.query) ? void 0 : S.query.from.table;
882
- G !== void 0 && or(b, e, G) && r(
883
- "drillAcrossFilterMixed",
884
- o(`joins[${B}]`),
885
- `a condition of the query names both what "${S.alias}" shares and what it doesn't: it isn't applied to it`,
886
- "warning"
887
- );
888
- }), e.joins.forEach((S, B) => {
889
- S.joinType !== "cross" || S.query && Le(S.query, v) || r(
890
- "crossJoin",
891
- o(`joins[${B}]`),
892
- `every row of "${X(S)}" meets every row of the query: they multiply`,
893
- "warning"
894
- );
895
- });
896
- const g = kr(e, b), p = (S) => r(
897
- "fanOut",
898
- S,
899
- `${g.tables.map((B) => `"${B}"`).join(", ")} rows repeat in this join: a sum, average or count of their columns comes out too high`,
900
- "warning"
901
- );
902
- e.select.forEach((S, B) => {
903
- g.select.includes(S.id) && p(o(`select[${B}].expression`));
904
- }), g.having && p(o("having")), (H = e.orderBy) == null || H.forEach((S, B) => {
905
- g.orderBy.includes(S.id) && p(`orderBy[${B}].expression`);
906
- });
907
- };
908
- a.shared !== void 0 && !Array.isArray(a.shared) && r("invalidStructure", "shared", "`shared` is an array"), ee(w, "shared");
909
- const Ae = /* @__PURE__ */ new Set();
910
- if (w.forEach((e, t) => {
911
- if (!x(e)) return;
912
- const o = `shared[${t}]`, { name: s } = e;
913
- !U(s) || s === "" ? r("invalidStructure", `${o}.name`, "a shared query has a non-empty string `name`") : (I(s, K, `${o}.name`, "a name"), Ae.has(s) && r("duplicateTableName", `${o}.name`, `two shared queries named "${s}"`), Ae.add(s));
914
- const $ = U(s) && s !== "" ? s : o, u = { inQuery: l, aliasOf: d, outerTables: f };
915
- l = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map(), f = void 0, C({ query: e.query, alias: $ }, o);
916
- const m = l.get($);
917
- ({ inQuery: l, aliasOf: d, outerTables: f } = u), U(e.id) && T.set(e.id, Array.isArray(m) ? m : void 0);
918
- }), se(a, "", !0), i.length === 0) {
919
- const e = a;
920
- if (ie(e, ""), c.requireLimit) {
921
- const { max: o } = c.requireLimit === !0 ? {} : c.requireLimit, s = Be(e, v) && !((Te = e.groupBy) != null && Te.length);
922
- e.limit === void 0 && !s ? r("noLimit", "limit", "no LIMIT: the query reads every row", "warning") : o !== void 0 && e.limit !== void 0 && e.limit > o && r("limitTooHigh", "limit", `LIMIT ${e.limit} is above ${o}`, "warning");
923
- }
924
- nr(e, b).forEach((o) => {
925
- r("paramConflict", "", `param "${o}" is compared against columns of different types`);
926
- }), tr(e).forEach((o) => {
927
- r("paramConflict", "", `param "${o}" stands for two different relative dates`);
928
- });
929
- const t = Ar(e);
930
- (Ne = e.orderBy) == null || Ne.forEach((o, s) => {
931
- t.includes(o.id) && r(
932
- "distinctSort",
933
- `orderBy[${s}].expression`,
934
- "with DISTINCT, a sort key has to be one of the selected columns"
935
- );
936
- });
937
- }
938
- i.some((e) => e.kind === "invalidStructure") || Nr(n, a).forEach((e) => r(
939
- "joinOnlyColumn",
940
- e.map((t, o) => typeof t == "number" ? `[${t}]` : `${o ? "." : ""}${t}`).join(""),
941
- "a column for joining tables only, used outside a join's condition"
942
- )), w.forEach((e, t) => {
943
- !x(e) || !U(e.id) || O.has(e.id) || r("unusedShared", `shared[${t}]`, "a shared query used nowhere", "warning");
944
- });
945
- const Xe = c.hideWarnings ?? [];
946
- return i.filter((e) => e.severity === "error" || !Xe.includes(e.kind));
947
- }
948
- function Wr(n, a = {
949
- relativeDate: gr
950
- }) {
951
- return a.relativeDate(n);
952
- }
953
- function zr({ unit: n, offset: a, anchor: c }) {
954
- if (n === "day" && a === 0) return "today";
955
- const i = a < 0 ? `minus_${-a}` : `plus_${a}`;
956
- return [n, a === 0 ? "0" : i, c].filter(Boolean).join("_");
957
- }
958
- const Mr = {
959
- from: "from",
960
- joins: "from",
961
- where: "where",
962
- groupBy: "group",
963
- having: "having",
964
- select: "select",
965
- distinct: "select",
966
- orderBy: "order",
967
- limit: "order",
968
- offset: "order"
969
- };
970
- function Vr(n, a, c = {}) {
971
- const { schema: i, functions: r } = c, b = (h, w) => typeof w == "number" ? h == null ? void 0 : h[w] : void 0, v = (h) => {
972
- var w;
973
- return h.alias || i && h.table !== void 0 && ((w = he(i, h.table)) == null ? void 0 : w.label) || h.table || "";
974
- }, l = (h, w) => {
975
- var C;
976
- if (!h || w.length === 0) return [];
977
- const [E, T, O] = w;
978
- switch (h.type) {
979
- case "logical": {
980
- const k = b(h.operands, T);
981
- return k ? [{ kind: "condition", number: T + 1 }, ...l(k, w.slice(2))] : [];
982
- }
983
- case "not":
984
- return [{ kind: "not" }, ...l(h.operand, w.slice(1))];
985
- case "binary": {
986
- if (E !== "left" && E !== "right") return [];
987
- const k = { kind: "side", side: E }, L = h[E];
988
- return (L == null ? void 0 : L.type) === "subquery" && T === "query" ? [k, { kind: "inSubQuery" }, ...I(L.query, w.slice(2))] : (L == null ? void 0 : L.type) === "list" && T === "items" && b(L.items, O) ? [k, { kind: "listItem", number: O + 1 }] : [k, ...l(L, w.slice(1))];
989
- }
990
- case "function": {
991
- const k = { kind: "function", name: h.name };
992
- if (E === "args" && b(h.args, T)) {
993
- const F = Ve(h.name, r), q = F && ((C = ce(F, T)) == null ? void 0 : C.label);
994
- return [
995
- k,
996
- { kind: "argument", number: T + 1, ...q && { label: q } },
997
- ...l(h.args[T], w.slice(2))
998
- ];
999
- }
1000
- const L = E === "orderBy" ? b(h.orderBy, T) : void 0;
1001
- return L ? [
1002
- k,
1003
- { kind: "sortKey", number: T + 1 },
1004
- ...l(L.expression, w.slice(3))
1005
- ] : [k];
1006
- }
1007
- case "if":
1008
- return E === "condition" || E === "then" || E === "else" ? [{ kind: "if", part: E }, ...l(h[E], w.slice(1))] : [];
1009
- case "case": {
1010
- if (E === "subject" || E === "else")
1011
- return [{ kind: "case", part: E }, ...l(h[E], w.slice(1))];
1012
- const k = E === "branches" ? b(h.branches, T) : void 0;
1013
- return !k || O !== "when" && O !== "then" ? [] : [
1014
- { kind: "case", part: O, branch: T + 1 },
1015
- ...l(k[O], w.slice(3))
1016
- ];
1017
- }
1018
- case "exists": {
1019
- const k = { kind: "exists", table: v(h.query.from) };
1020
- return E === "link" ? [k, { kind: "existsLink" }] : E === "query" ? [k, ...I(h.query, w.slice(1))] : [k];
1021
- }
1022
- default:
1023
- return [];
1024
- }
1025
- }, d = (h, w) => {
1026
- if (h.query && w[0] === "query") return f(h.alias, h.query, w.slice(1));
1027
- const E = h.query ? { kind: "subQuery", name: h.alias } : { kind: "table", name: v(h) };
1028
- return w[0] === "on" ? [E, { kind: "joinCondition" }, ...l(h.on, w.slice(1))] : [E];
1029
- };
1030
- function f(h, w, E, T = "subQuery") {
1031
- const O = { kind: T, name: h };
1032
- if (!$e(w)) return [O, ...I(w, E)];
1033
- const C = E[0] === "union" ? b(Ue(w), E[1]) : void 0;
1034
- if (!C) return [O];
1035
- const k = E[1] + 1;
1036
- return [O, { kind: "unionQuery", number: k }, ...I(C, E.slice(2))];
1037
- }
1038
- function I(h, w) {
1039
- var F, q;
1040
- const [E, T, O] = w, C = Mr[String(E)];
1041
- if (!C) return [];
1042
- const k = { kind: "section", section: C }, L = w.slice(3);
1043
- switch (E) {
1044
- // A sub query is a place of its own: no "From Tables" before it.
1045
- case "from":
1046
- return h.from.query ? T === "query" ? f(h.from.alias, h.from.query, w.slice(2)) : [{ kind: "subQuery", name: h.from.alias }] : [k, { kind: "table", name: v(h.from) }];
1047
- case "joins": {
1048
- const D = b(h.joins, T);
1049
- return D ? D.query ? d(D, w.slice(2)) : [k, ...d(D, w.slice(2))] : [k];
1050
- }
1051
- case "where":
1052
- case "having":
1053
- return [k, ...l(h[E], w.slice(1))];
1054
- case "select": {
1055
- const D = b(h.select, T);
1056
- if (!D) return [k];
1057
- const { expression: P, alias: ne } = D, de = P.type === "field" && i && P.table !== void 0 ? (q = (F = he(i, P.table)) == null ? void 0 : F.columns.find((V) => V.name === P.column)) == null ? void 0 : q.label : void 0, W = ne || de;
1058
- return [
1059
- k,
1060
- { kind: "column", number: T + 1, ...W && { name: W } },
1061
- ...O === "expression" ? l(P, L) : []
1062
- ];
1063
- }
1064
- case "groupBy":
1065
- case "orderBy": {
1066
- const D = b(h[E], T);
1067
- return D ? [
1068
- k,
1069
- { kind: E === "groupBy" ? "groupKey" : "sortKey", number: T + 1 },
1070
- ...O === "expression" ? l(D.expression, L) : []
1071
- ] : [k];
1072
- }
1073
- default:
1074
- return [k];
1075
- }
1076
- }
1077
- if (a[0] === "shared") {
1078
- const h = b(n.shared, a[1]);
1079
- return h ? a[2] === "query" ? f(h.name, h.query, a.slice(3), "sharedQuery") : [{ kind: "sharedQuery", name: h.name }] : [];
1080
- }
1081
- return I(n, a);
1082
- }
1083
- export {
1084
- Pr as Q,
1085
- $r as S,
1086
- br as a,
1087
- Dr as b,
1088
- Fr as c,
1089
- Lr as d,
1090
- Gr as e,
1091
- wr as f,
1092
- Er as g,
1093
- pe as h,
1094
- Xr as i,
1095
- _r as j,
1096
- Wr as k,
1097
- Hr as l,
1098
- Rr as m,
1099
- Vr as n,
1100
- Jr as o,
1101
- zr as p,
1102
- xr as q,
1103
- qr as r,
1104
- Qr as s,
1105
- Ar as t,
1106
- kr as u,
1107
- Kr as v
1108
- };