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