@nongt/visql-core 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3281 +0,0 @@
1
- import { D as $e, h as ue, q as Q, t as D, i as H, s as Xn, l as le, u as Kn, w as Pe, e as Ve, x as dn, k as z, r as fe, o as xe, j as K, y as Yn, d as W, z as Jt, A as Be, B as me, C as Pt, M as Y, F as zn, G as Vt, g as Z, H as We, I as fn, b as be, J as Zn, n as Wt, K as et, f as Ht, L as Xt, N as Mn, O as On, P as Ge, Q as Kt } from "./schema-DFC26AhZ.js";
2
- import { c as Yt, s as zt, b as nt } from "./calendarDate-CYlr9TvX.js";
3
- const Zt = 1e3, tt = 15, er = 40, ls = 100;
4
- function nr(e) {
5
- const [n] = e.replace(/^[+-]/, "").split(/e/i), [r, t = ""] = n.split(".");
6
- return `${r}${t.replace(/0+$/, "")}`.replace(/^0+/, "").length;
7
- }
8
- function nn(e) {
9
- return Number.isFinite(e) && nr(String(e)) <= tt;
10
- }
11
- const us = [];
12
- function oe(e) {
13
- return Q(e).filter((n) => n.query !== void 0);
14
- }
15
- function Te(e, n = []) {
16
- var r;
17
- return e.query ? e.query : e.shared === void 0 || (r = n.find((t) => t.id === e.shared)) == null ? void 0 : r.query;
18
- }
19
- function rt(e) {
20
- const n = [], r = (t) => {
21
- t.type === "subquery" ? n.push(t) : fe(t).forEach(r);
22
- };
23
- return Xn(e).forEach(r), n;
24
- }
25
- function st(e, n) {
26
- let r = !1;
27
- const t = (i) => {
28
- if (i.type !== "subquery") return xe(i, t);
29
- const a = n(i);
30
- return a !== i && (r = !0), a;
31
- }, s = Pe(e, t, (i) => i);
32
- return r ? s : e;
33
- }
34
- const cs = (e, n) => `${e}#${n}`;
35
- function tr(e) {
36
- return !("type" in e) && "of" in e;
37
- }
38
- const rr = (e) => ({
39
- id: e.id,
40
- alias: e.name,
41
- query: e.query
42
- });
43
- function Un(e, n) {
44
- var s;
45
- const r = oe(e).find((i) => i.id === n);
46
- if (r) return r;
47
- const t = (s = e.shared) == null ? void 0 : s.find((i) => i.id === n);
48
- return t && rr(t);
49
- }
50
- function it(e, n) {
51
- const r = Un(e, n);
52
- if (r) return H(r.query) ? void 0 : r;
53
- const t = rt(e).find((l) => l.id === n);
54
- if (t) return t;
55
- const s = /^(.*)#(\d+)$/.exec(n), i = s ? Un(e, s[1]) : void 0, a = Number(s == null ? void 0 : s[2]), o = i && H(i.query) ? i.query.union[a] : void 0;
56
- return i && o ? {
57
- id: n,
58
- alias: i.alias,
59
- query: o,
60
- of: i,
61
- index: a
62
- } : void 0;
63
- }
64
- function ot(e) {
65
- return { id: e.id, ...Ve(e.query) };
66
- }
67
- function Ye(e) {
68
- const {
69
- from: n,
70
- joins: r,
71
- where: t,
72
- select: s,
73
- groupBy: i,
74
- having: a,
75
- distinct: o
76
- } = e;
77
- return {
78
- from: n,
79
- joins: r,
80
- select: s,
81
- ...t !== void 0 ? { where: t } : {},
82
- ...i !== void 0 ? { groupBy: i } : {},
83
- ...a !== void 0 ? { having: a } : {},
84
- ...o !== void 0 ? { distinct: o } : {}
85
- };
86
- }
87
- function sr(e, n) {
88
- return n.reduce((r, t) => {
89
- const s = r && it(r, t);
90
- return s ? ot(s) : void 0;
91
- }, e);
92
- }
93
- function mn(e, n, r) {
94
- if (n.length === 0) return r(e);
95
- const [t, ...s] = n, i = it(e, t);
96
- if (!i) return e;
97
- const a = ot(i), o = mn(a, s, r);
98
- if (o === a || !ue(o)) return e;
99
- if ("type" in i && i.type === "subquery") {
100
- const c = { ...i, query: Ye(o) };
101
- return st(e, (m) => m === i ? c : m);
102
- }
103
- const l = (c, m) => {
104
- if (!oe(e).some((f) => f.id === c.id))
105
- return dn(e, (f, p) => p.id === c.id ? m : f);
106
- const d = { ...c, query: m };
107
- return c === e.from ? { ...e, from: d } : {
108
- ...e,
109
- joins: e.joins.map((f) => f === c ? d : f)
110
- };
111
- };
112
- if (tr(i)) {
113
- const { of: c, index: m } = i, { union: d } = c.query;
114
- return l(c, {
115
- ...c.query,
116
- union: d.map((f, p) => p === m ? Ye(o) : f)
117
- });
118
- }
119
- return l(i, Ye(o));
120
- }
121
- const ir = {
122
- text: "varchar",
123
- integer: "integer",
124
- number: "decimal",
125
- date: "date",
126
- dateTime: "dateTime",
127
- time: "time",
128
- boolean: "boolean"
129
- };
130
- function Ne(e, n, r = []) {
131
- const t = Ve(n);
132
- if (t.select.length === 0)
133
- return Q(t).flatMap((o) => {
134
- var c;
135
- if (o.table !== void 0) return ((c = z(e, o.table)) == null ? void 0 : c.columns) ?? [];
136
- const l = Te(o, r);
137
- return l ? Ne(e, l, r) : [];
138
- });
139
- const s = new Map(Q(t).map((o) => [D(o), o.table])), i = (o) => {
140
- var l;
141
- if (o.type === "field") {
142
- const c = o.table === void 0 ? void 0 : s.get(o.table), m = c === void 0 || (l = z(e, c)) == null ? void 0 : l.columns.find((d) => d.name === o.column);
143
- return (m == null ? void 0 : m.type) ?? "varchar";
144
- }
145
- if (o.type === "function") {
146
- const c = o.name.toUpperCase();
147
- if (c === "COUNT") return "integer";
148
- if (c === "SUM" || c === "AVG") return "decimal";
149
- if ((c === "MIN" || c === "MAX") && o.args[0]) return i(o.args[0]);
150
- }
151
- return o.type === "literal" && typeof o.value == "number" ? "decimal" : o.type === "literal" && o.as ? ir[o.as] : "varchar";
152
- }, a = (o) => {
153
- var d, f;
154
- if (o.type !== "field" || o.table === void 0) return !1;
155
- const l = Q(t).find((p) => D(p) === o.table);
156
- if (!l) return !1;
157
- const c = l.table === void 0 ? Te(l, r) : void 0, m = l.table !== void 0 ? (d = z(e, l.table)) == null ? void 0 : d.columns : c && Ne(e, c, r);
158
- return !!((f = m == null ? void 0 : m.find((p) => p.name === o.column)) != null && f.joinOnly);
159
- };
160
- return t.select.flatMap((o) => {
161
- const l = K(o);
162
- return l ? [{
163
- name: l,
164
- label: l,
165
- type: i(o.expression),
166
- ...a(o.expression) ? { joinOnly: !0 } : {}
167
- }] : [];
168
- });
169
- }
170
- function at(e, n, r = []) {
171
- const t = Te(n, r), s = (t ? Ne(e, t, r) : []).filter((i, a, o) => o.findIndex((l) => l.name === i.name) === a);
172
- return { name: n.alias, label: n.alias, columns: s };
173
- }
174
- function ds(e, n, r = []) {
175
- return Q(n).filter((t) => t.table === void 0).map((t) => at(e, t, r));
176
- }
177
- function lt(e, n = $e) {
178
- if (H(e)) return !1;
179
- const r = e;
180
- return (r.groupBy ?? []).length === 0 && r.select.length > 0 && r.select.every((t) => le(t.expression, n)) && Kn(r, n).select.length === 0;
181
- }
182
- function jn(e, n, r) {
183
- const t = (s) => s.type === "field" ? s.table === n ? { ...s, table: r } : s : s.type === "exists" && Yn(s.query).has(n) ? { ...s, link: t(s.link) } : xe(s, t);
184
- return Pe(e, t, (s) => s);
185
- }
186
- function ut(e, n) {
187
- const r = Ve(n), t = Q(r).flatMap((s) => s.table === void 0 ? [] : [{ table: s.table, alias: s.alias }]);
188
- return r.select.length === 0 ? t.flatMap(({ table: s }) => {
189
- var i;
190
- return (((i = z(e, s)) == null ? void 0 : i.columns) ?? []).map((a) => ({ name: a.name, table: s, column: a.name }));
191
- }) : r.select.flatMap((s) => {
192
- const { expression: i } = s;
193
- if (i.type !== "field" || !i.column) return [];
194
- const a = t.find((l) => D(l) === i.table), o = s.alias || i.column;
195
- return a ? [{ name: o, table: a.table, column: i.column }] : [];
196
- });
197
- }
198
- function ct(e, n) {
199
- return oe(n).flatMap((r) => ut(e, r.query).flatMap(({ name: t, table: s, column: i }) => e.relations.flatMap((a) => {
200
- const o = a.fromTable === s && a.fromColumn === i;
201
- if (!o && !(a.toTable === s && a.toColumn === i)) return [];
202
- const l = o ? a.toTable : a.fromTable, c = {
203
- type: "binary",
204
- operator: "=",
205
- left: { type: "field", table: l, column: o ? a.toColumn : a.fromColumn },
206
- right: { type: "field", table: r.alias, column: t }
207
- };
208
- return [{ table: l, on: c }];
209
- })));
210
- }
211
- function or(e, n, r) {
212
- var t;
213
- return (t = ct(e, n).find((s) => s.table === r)) == null ? void 0 : t.on;
214
- }
215
- function dt(e, n, r) {
216
- var l;
217
- const t = Q(n).flatMap((c) => c !== r && c.table !== void 0 ? [{ table: c.table, alias: c.alias }] : []), s = (c, m) => m === void 0 ? { type: "field", table: c } : { type: "field", table: c, column: m }, a = ut(e, r.query).flatMap(({ name: c, table: m, column: d }) => t.flatMap((f) => e.relations.filter((p) => p.fromTable === m && p.fromColumn === d && p.toTable === f.table || p.toTable === m && p.toColumn === d && p.fromTable === f.table).map((p) => ({
218
- name: c,
219
- right: s(D(f), p.fromTable === m ? p.toColumn : p.fromColumn)
220
- }))))[0], o = (l = at(e, r).columns[0]) == null ? void 0 : l.name;
221
- return {
222
- type: "binary",
223
- operator: "=",
224
- left: s(r.alias, (a == null ? void 0 : a.name) ?? o),
225
- right: (a == null ? void 0 : a.right) ?? { type: "field" }
226
- };
227
- }
228
- const Le = (e, n) => `${e} ${n}${e === 1 ? "" : "s"}`;
229
- function ft({ unit: e, offset: n, anchor: r }) {
230
- const t = Math.abs(n);
231
- if (r) {
232
- const s = r === "start" ? "Start" : "End";
233
- return n === 0 ? `${s} of this ${e}` : t === 1 ? `${s} of ${n < 0 ? "last" : "next"} ${e}` : n < 0 ? `${s} of the ${e} ${Le(t, e)} ago` : `${s} of the ${e} in ${Le(t, e)}`;
234
- }
235
- return n === 0 ? "Today" : e === "day" && t === 1 ? n < 0 ? "Yesterday" : "Tomorrow" : n < 0 ? `${Le(t, e)} ago` : `In ${Le(t, e)}`;
236
- }
237
- const ar = {
238
- // Section captions on the main canvas
239
- sectionFrom: "From Tables",
240
- sectionWhere: "Conditions",
241
- sectionGroup: "Group Rows",
242
- sectionSelect: "Columns Selection",
243
- sectionOrder: "Sort & Limit",
244
- /** Shared queries (WITH, issue 194): their section, before FROM. */
245
- sectionShared: "Shared Queries",
246
- // Breadcrumb / navigation
247
- main: "Main",
248
- close: "Close (ESC)",
249
- jumpedTo: "Jumped to",
250
- editInSubCanvas: (e) => `Edit in sub-canvas (${e})`,
251
- // Reordering
252
- moveUp: "Move Up",
253
- moveDown: "Move Down",
254
- moveGroupUp: "Move Group Up",
255
- moveGroupDown: "Move Group Down",
256
- moveBranchUp: "Move Branch Up",
257
- moveBranchDown: "Move Branch Down",
258
- // Conditions and groups
259
- createCondition: "Create Condition",
260
- /** Read-only mode, empty WHERE: stands in for the Create Condition button. */
261
- noCondition: "No Condition",
262
- addCondition: "Add Condition",
263
- addGroup: "Add Group",
264
- addIfExpression: "Add IF Expression",
265
- addCaseExpression: "Add CASE Expression",
266
- wrapInGroup: "Wrap in Group",
267
- wrapInNewGroup: "Wrap in New Group",
268
- collapseGroup: "Collapse Group",
269
- // Wrapping in NOT (shown as NOT itself, like AND/OR — not "Exclude",
270
- // which reads as "everything else" and NOT leaves out NULL rows too).
271
- negateCondition: "Negate Condition",
272
- negateGroup: "Negate Group",
273
- removeNot: "Remove NOT",
274
- delete: "Delete",
275
- deleteGroup: "Delete Group",
276
- deleteIf: "Delete IF",
277
- deleteCase: "Delete CASE",
278
- // EXISTS: whether a row has related rows ("Has Leave Request linked by
279
- // Employee · Employee ID where …"). The button itself reads EXISTS.
280
- addExists: "Add a related-rows condition",
281
- /** An entry of its menu when the same table is linked more than one way
282
- * (`via`: the foreign key's column). */
283
- existsVia: (e, n) => `${e} — by ${n}`,
284
- existsHas: "Has",
285
- existsLinkedBy: "linked by",
286
- existsWhere: "where",
287
- /** No conditions on the related rows: any will do. */
288
- existsAny: "any",
289
- existsEdit: "Edit the related rows' conditions",
290
- // IF / CASE
291
- addBranch: "Add Branch",
292
- removeBranch: "Remove Branch",
293
- addElse: "Add ELSE",
294
- removeElse: "Remove ELSE",
295
- // Functions
296
- addArg: "Add Arg",
297
- removeArg: "Remove Arg",
298
- // Value type menu
299
- typeField: "Field",
300
- typeValue: "Value",
301
- /** NULL, picked as a value (no value, on purpose). */
302
- typeNull: "Empty",
303
- /** A value's types, picked when nothing typed is compared with it
304
- * (issue 130). */
305
- typeText: "Text",
306
- typeNumber: "Number",
307
- typeDate: "Date",
308
- typeBoolean: "Yes / No",
309
- typeFunction: "Function",
310
- typeExpression: "Expression",
311
- /** A named param (set by the application, shown read-only). */
312
- typeParam: "Parameter",
313
- /** A date relative to when the query runs (issue 140): the type menu's
314
- * item, its words ("30 days ago", "Start of last month"), its presets'
315
- * "Custom", and its custom parts. */
316
- typeRelativeDate: "Relative date",
317
- relativeDate: ft,
318
- relativeCustom: "Custom…",
319
- relativeUnits: {
320
- day: "days",
321
- week: "weeks",
322
- month: "months",
323
- year: "years"
324
- },
325
- relativeAgo: "ago",
326
- relativeFromNow: "from now",
327
- relativeSameDay: "That day",
328
- relativeStart: "Start of it",
329
- relativeEnd: "End of it",
330
- /** A parameter's value isn't in the query: it's given when it runs. */
331
- paramHint: "Given when the query runs",
332
- paramNamePlaceholder: "name",
333
- typeMenuBasic: "Basic",
334
- /** A function picker's groups, where aggregates are offered: those
335
- * (which group the rows) apart from the rest. Kept short: the list is
336
- * as narrow as the name box. */
337
- functionGroupAggregate: "Aggregates",
338
- functionGroupOther: "Functions",
339
- typeMenuCondition: "Condition",
340
- /** IN's value as a query of its own (issue 122), when offered: its type,
341
- * its menu section, and its canvas's name. */
342
- typeSubquery: "Sub query",
343
- typeMenuQuery: "Query",
344
- /** IN's values, one each (issue 130): its type, adding one, taking one
345
- * out. */
346
- typeList: "Values",
347
- /** A union of tables' rows (issue 121): the add-table picker's groups
348
- * when rows can be added. */
349
- /** A NULL value (no value at all): on a union's branch, that table's
350
- * having none for the column — and filling one in instead. */
351
- nullValue: "No value",
352
- nullInUnion: "Empty for this table",
353
- fillInValue: "Fill in a value",
354
- openUnionBranch: (e) => `Open ${e}'s query`,
355
- removeUnionBranch: (e) => `Remove ${e}'s query`,
356
- joinTableGroup: "Join a table",
357
- /** The heading over tables in no group, when others have one. */
358
- otherTablesGroup: "Other tables",
359
- /** Free-form unions (issue 153): a new one, the query as one's first
360
- * query, another query for one, and a new query's canvas. */
361
- createUnion: "Create Union",
362
- unionWithQuery: "Union with another query",
363
- addUnionQuery: "Add query",
364
- /** A union of one query back as a plain query. */
365
- unwrapUnion: "Make it a plain query",
366
- newUnionQuery: "New query in the union",
367
- /** Issue 153, step 4: a union joined. */
368
- joinUnion: "Join a union",
369
- addRowsGroup: "Add rows from another table",
370
- addListValue: "Add value",
371
- removeListValue: (e) => `Remove ${e}`,
372
- subqueryLabel: "Sub query",
373
- // A measure from another table (drill-across): in a SELECT column's type
374
- // menu, then on its sub query.
375
- /** The type menu's section, and its one item. */
376
- typeMenuMeasure: "Measure",
377
- measureFrom: "Measure from…",
378
- /** Why it's off: nothing is summed up yet, so there are no groups. */
379
- measureNeedsGroups: "Sum something up first (a measure is per group)",
380
- /** Why a table can't be one: a group key's table it doesn't link to. */
381
- measureUnlinked: (e) => `Doesn't link to ${e}`,
382
- /** What to sum up of the table picked. */
383
- measureCount: "Count of rows",
384
- measureOf: (e, n) => `${{
385
- SUM: "Sum",
386
- AVG: "Average",
387
- MIN: "Minimum",
388
- MAX: "Maximum"
389
- }[e]} of ${n}`,
390
- /** The checkbox on a measure's FROM row. */
391
- keepInStep: "Keep in step with the report",
392
- /** On a measure's canvas: what it follows, while kept in step. */
393
- measureFollows: (e) => `Kept in step with the report: per ${e}`,
394
- measureAlso: (e) => `also ${e}`,
395
- /** Where its rows come from (the report's base decides). */
396
- measureRows: (e) => `Only groups with ${e} rows appear. To see every group, start from the table they belong to.`,
397
- // FROM / JOIN
398
- chooseBaseTableHint: "Choose a base table to get started.",
399
- chooseBaseTable: "Choose a base table",
400
- addTable: "+ Add Table / Sub Query",
401
- removeJoin: "Remove Join",
402
- removeBaseTable: "Remove Base Table",
403
- setJoinCondition: "Set condition…",
404
- conditionCount: (e) => `${e} condition${e === 1 ? "" : "s"}`,
405
- /** Why a FROM row can't move there: `table`'s ON condition uses `needs`,
406
- * which would then only be joined after it. */
407
- joinOrderConflict: (e, n) => `${e}'s join condition uses ${n}, which must come first`,
408
- // Sub queries (derived tables): a query of its own, joined like a table
409
- // or as the base.
410
- /** First in the Add Table and base table pickers: opens a new one's
411
- * canvas, to pick its first table. */
412
- createSubQuery: "Create Sub Query",
413
- /** That canvas's label until its first table is picked. */
414
- newSubQuery: "New sub query",
415
- /** The icon after a sub query's name, which opens its own canvas: its
416
- * tooltip and name (in read-only mode: viewSubQuery). */
417
- editSubQuery: "Edit Sub Query",
418
- viewSubQuery: "View Sub Query",
419
- /** A derived table of one row (a total): CROSS JOIN it, no condition. */
420
- joinToEveryRow: "Join to every row",
421
- /** In place of its condition, once CROSS joined. */
422
- joinedToEveryRow: "Joined to every row",
423
- /** Shared queries (issue 194): the pickers' group of them; the action
424
- * that makes one (its canvas, empty, labelled newSharedQuery until its
425
- * first table); the icon opening one (in read-only mode:
426
- * viewSharedQuery); removing one (its places become sub queries). */
427
- sharedQueriesGroup: "Shared Queries",
428
- createSharedQuery: "Create Shared Query",
429
- newSharedQuery: "New shared query",
430
- editSharedQuery: "Edit Shared Query",
431
- viewSharedQuery: "View Shared Query",
432
- removeSharedQuery: "Remove Shared Query",
433
- /** The section's "+": a shared query made before it's used. */
434
- addSharedQuery: "New Shared Query",
435
- /** Under a shared query's name: where it's used. */
436
- sharedUsedIn: (e) => e === 0 ? "Not used yet" : e === 1 ? "Used in 1 place" : `Used in ${e} places`,
437
- /** On a sub query's row: it becomes a shared query; on a shared query's
438
- * place: it gets a copy of its own, a sub query. */
439
- makeShared: "Make Shared",
440
- makeSubQuery: "Make Sub Query",
441
- /** Removing a shared query that's used: what happens to its places. */
442
- removeSharedKeepPlaces: "Remove: each place gets a copy as a sub query",
443
- removeSharedWithPlaces: "Remove, with the tables using it",
444
- /** Why the second can't be: a query reads from it as its base. */
445
- removeSharedIsBase: "A query reads from it as its base",
446
- /** Renaming a shared query: a name another one, or a table, has. */
447
- sharedNameTaken: (e) => `Another shared query or table is called "${e}"`,
448
- /** Renaming a derived table: no name given. */
449
- derivedNameEmpty: "Give it a name",
450
- /** Renaming a derived table: a name another table already has. */
451
- derivedNameTaken: (e) => `Another table is called "${e}"`,
452
- // GROUP BY / HAVING ("group" alone already names an AND/OR group)
453
- /** The "+" that starts grouping. */
454
- groupRows: "Group Rows",
455
- /** A group key added for a SELECT column, following it. */
456
- groupKeyFromColumn: (e) => `From column ${e}`,
457
- /** A grouped query's HAVING or sort key with no group key to pick: why,
458
- * and what to do instead. */
459
- onlyGroupKeys: "Only group keys here — sum up another column with a function",
460
- addGrouping: "Add Grouping",
461
- removeGrouping: "Remove Grouping",
462
- /** Read-only mode, no grouping. */
463
- notGrouped: "Not grouped",
464
- /** Above HAVING's tree (and the "+" that starts it) on the canvas — the
465
- * counterpart of `sectionWhere`: conditions on groups, not rows. */
466
- havingCaption: "Group Conditions",
467
- addHaving: "Add Group Condition",
468
- /** A column (in SELECT, ORDER BY or HAVING) that isn't one value per group. */
469
- notPerGroup: "Each group has many of these values: group by it, or summarize it (SUM, COUNT…)",
470
- /** Quick fix on a SELECT column that isn't one value per group. */
471
- groupByColumn: "Group by this",
472
- /** A sum, average or count over rows the joins repeat (the tables'
473
- * labels, joined). */
474
- fanOut: (e) => `${e} rows repeat in these joins (each matches several joined rows), so sums, averages and counts of their columns come out too high`,
475
- /** A grouped query with no columns picked (SELECT *). */
476
- groupedNeedsColumns: "Pick the columns to show when rows are grouped",
477
- // COUNT's choice of what to count (the function sub-canvas)
478
- countRows: "Every row",
479
- countValues: "Rows with a value",
480
- countDistinct: "Different values",
481
- // STRING_AGG's choice of what to join (the function sub-canvas)
482
- joinEveryValue: "Every value",
483
- joinDistinctValues: "Different values",
484
- // SELECT
485
- addColumn: "Add Column",
486
- /** Read-only mode, no columns picked: every column is selected. */
487
- allColumns: "All",
488
- removeColumn: "Remove Column",
489
- aliasPlaceholder: "alias",
490
- /** The SELECT node's DISTINCT switch. */
491
- distinct: "Leave out duplicate rows",
492
- /** Read-only mode, DISTINCT on. */
493
- distinctOn: "Duplicate rows left out",
494
- // ORDER BY / LIMIT / OFFSET (ASC/DESC themselves are SQL, not translated)
495
- addSort: "Add Sort",
496
- removeSort: "Remove Sort",
497
- toggleSortDirection: "Ascending / descending",
498
- /** Opens the row-count inputs. */
499
- limitRows: "Limit rows",
500
- removeLimit: "Remove row limit",
501
- // The row-count inputs read as one sentence, each input between two
502
- // fragments: "Show [50] rows, skipping the first [100]". A fragment may be
503
- // empty where the language doesn't need it.
504
- showRowsBefore: "Show",
505
- showRowsAfter: "rows,",
506
- skipRowsBefore: "skipping the first",
507
- skipRowsAfter: "",
508
- /** What the row counts come to (1-based; `to` undefined: no limit). */
509
- rowRange: (e, n) => n === void 0 ? `Rows ${e} onward` : `Rows ${e}–${n}`,
510
- allRows: "All rows",
511
- /** LIMIT 0. */
512
- noRows: "No rows",
513
- /** Skipping rows without a sort: the database may return any rows. */
514
- pagingNeedsSort: "Add a sort, or each page may get different rows",
515
- /** DISTINCT on, and a sort key that isn't a selected column (no database
516
- * accepts that). */
517
- sortNeedsSelected: "Duplicate rows are left out, so sort only by selected columns",
518
- /** Read-only mode, no sorting and no limit. */
519
- noSort: "Unsorted",
520
- // A text value marked as the empty text (the '' toggle next to it)
521
- emptyText: "Empty",
522
- markEmpty: "Empty text (no characters at all)",
523
- unmarkEmpty: "Type a value instead",
524
- // Running the query (the host's onRun) and its results under the canvas
525
- run: "Run",
526
- running: "Running…",
527
- /** The Run button's tooltip. */
528
- runShortcut: "Run the query (Ctrl/⌘+Enter)",
529
- /** Why Run is off: no table picked yet. */
530
- runNeedsTable: "Choose a table first",
531
- /** Why Run is off: the query has errors. */
532
- runNeedsFixes: (e) => `Fix ${e} problem${e === 1 ? "" : "s"} first`,
533
- runFailed: "The query failed",
534
- /** How many rows came back (`truncated`: more matched). */
535
- runRows: (e, n) => `${n ? "First " : ""}${e} row${e === 1 ? "" : "s"}`,
536
- runNoRows: "No rows",
537
- /** The results are from before the latest edits. */
538
- runOutdated: "The query has changed since this run",
539
- closeResults: "Close results",
540
- // The problems button (above the canvas) and its list (issue 132): errors,
541
- // then warnings, one entry per validateQuery issue, its text by kind (see
542
- // QueryIssueKind) and under it where it is (issueLocation).
543
- problems: (e) => `${e} problem${e === 1 ? "" : "s"}`,
544
- problemsErrors: "Errors — the query can't run",
545
- problemsWarnings: "Warnings — it runs, check the result",
546
- /** Issues about the query as a whole (no one section). */
547
- problemsQuery: "Query",
548
- // Where a problem is: the steps of its location, joined by ' › '. A
549
- // section is its caption, a sub query its name, a column its alias;
550
- // SQL keywords (NOT, IF, CASE, WHEN) stay as they are.
551
- locationJoinCondition: "join condition",
552
- locationColumn: (e) => `column ${e}`,
553
- locationGroupKey: (e) => `key ${e}`,
554
- locationSortKey: (e) => `sort key ${e}`,
555
- locationCondition: (e) => `condition ${e}`,
556
- locationLeft: "left side",
557
- locationRight: "right side",
558
- /** One of IN's values, or a function's argument with no label. */
559
- locationValue: (e) => `value ${e}`,
560
- locationUnionQuery: (e) => `query ${e}`,
561
- locationInSubquery: "sub query",
562
- issueInvalidStructure: "Not in the form a query takes",
563
- issueDuplicateId: "Two parts share an id",
564
- issueUnknownTable: "A table that isn't available",
565
- issueUnknownColumn: "A column that isn't available",
566
- issueTableNotInQuery: "A column of a table that isn't in the query",
567
- issueUnqualifiedField: "A column with no table",
568
- issueIncomplete: "Not filled in yet",
569
- issueArgCount: "A function given too many values",
570
- issueAmbiguousTable: "A table named like one of the query around it",
571
- issueDuplicateTableName: "Two tables with the same name: give one an alias",
572
- issueDerivedColumnName: "A sub query's column with no name, or a name used twice",
573
- issueUnknownFunction: "A function that isn't available",
574
- issueJoinOrder: "A join condition uses a table joined after it",
575
- issueDistinctSort: "Sorted by a column that isn't selected",
576
- issueNotGrouped: "A column that isn't one value per group",
577
- issueUnknownAggregate: "A function that may or may not sum rows up",
578
- issueMisplacedAggregate: "SUM, COUNT and the like can't be used here",
579
- issueParamConflict: "A parameter compared with columns of different types",
580
- issueFanOut: "Sums, averages or counts come out too high: a join repeats rows",
581
- issueCrossJoin: "Every row joined to every row of a table: rows multiply",
582
- issueDrillAcrossOutOfStep: "A measure kept in step that no longer matches the grouping",
583
- issueDrillAcrossFilterMixed: "A condition a measure from another table can't follow",
584
- issueUnlinkedJoin: "A join condition not linking its table to one before it: rows multiply",
585
- issueTooLong: "Too long: a name, a text, or a number with too many digits",
586
- issueDialectUnsupported: "Something this database doesn't have",
587
- issueSubqueryColumns: "A sub query after IN must pick exactly one column",
588
- issueNotInSubquery: "NOT IN a sub query keeps no rows if it gives a NULL",
589
- issueNoLimit: "No row limit: reads every row",
590
- issueLimitTooHigh: "More rows than allowed",
591
- issueTypeMismatch: "Values of types that don't go together",
592
- issueInvalidPattern: "A pattern that isn't a regular expression",
593
- issueUnionColumns: "Stacked queries whose columns don't line up",
594
- issueUnionTypes: "Stacked queries giving a column of different types",
595
- issueSharedOrder: "A shared query can use only the shared queries before it",
596
- issueUnusedShared: "A shared query used nowhere",
597
- issueJoinOnlyColumn: "A column for joining tables only, used as a value",
598
- // What a problem is about, where the query says (issue 132); the kind's
599
- // text above where it doesn't.
600
- issueUnknownTableNamed: (e) => `There's no table "${e}"`,
601
- issueUnknownColumnNamed: (e, n) => `${e} has no column "${n}"`,
602
- issueJoinOnlyColumnNamed: (e) => `${e} is for joining tables only`,
603
- issueTableNotInQueryNamed: (e) => `"${e}" isn't one of the query's tables`,
604
- issueUnqualifiedFieldNamed: (e) => `"${e}" names no table`,
605
- issueAmbiguousTableNamed: (e) => `"${e}" is a table of the query around it too: give it an alias`,
606
- issueNoColumn: "No column picked",
607
- issueNoValue: "No value filled in",
608
- issueNothingToCompare: "Nothing to compare with",
609
- issueComparedWithNull: "Compared with NULL, which is never true: use IS NULL",
610
- issueNoJoinCondition: (e) => `${e}'s join condition isn't set`,
611
- issueEmptyGroup: "An empty group of conditions",
612
- /** `part`: 'condition', or the keyword THEN. */
613
- issueIfPartMissing: (e) => `IF with no ${e}`,
614
- issueCaseNoWhen: "CASE with no WHEN",
615
- issueInNoValues: "IN with no values",
616
- issueFunctionNeedsArgs: (e, n) => `${e} needs ${n} value${n === 1 ? "" : "s"}`,
617
- issueFunctionTakesArgs: (e, n) => `${e} takes at most ${n} value${n === 1 ? "" : "s"}`,
618
- issueDuplicateTableNamed: (e) => `Two tables named "${e}": give one an alias`,
619
- issueDuplicateColumnNamed: (e) => `Two columns named "${e}"`,
620
- issueUnnamedColumn: "A column with no name: give it an alias",
621
- issueUnknownFunctionNamed: (e) => `${e} isn't an available function`,
622
- issueDialectUnsupportedNamed: (e) => `${e} isn't in this database`,
623
- issueJoinOrderNamed: (e) => `${e}'s join condition uses a table joined after it`,
624
- issueNotGroupedNamed: (e) => `${e} isn't one value per group: group by it, or sum it up`,
625
- issueSelectAllGrouped: "A grouped query has to pick its columns, not all of them (*)",
626
- issueMisplacedAggregateNamed: (e) => `${e} can't be used here`,
627
- // A collapsed expression's peek (issue 131): the whole of it, a part per
628
- // line; picking a part goes to it.
629
- peekHint: "Pick a part to go to it",
630
- // Find (issue 131): what's in the query, to go to it.
631
- /** `keys`: its shortcut, as the user's keyboard has it (⌘F, Ctrl+F). */
632
- find: (e) => `Find in the query (${e})`,
633
- findPlaceholder: "Find a column, value, function…",
634
- findNothing: "Nothing in the query matches",
635
- // The query's outline (issue 131), in place of the canvas's map: its
636
- // sections in order, a part a line; picking one goes to it.
637
- outline: "Outline",
638
- outlineCollapse: "Fold the outline away",
639
- outlineExpand: "Show the outline",
640
- outlineAllColumns: "All columns",
641
- outlineEmpty: "Nothing yet: pick a table to start.",
642
- outlineLimit: (e) => `At most ${e} row${e === 1 ? "" : "s"}`,
643
- outlineOffset: (e) => `Skip ${e} row${e === 1 ? "" : "s"}`
644
- }, Ln = (e) => "from" in e ? e.from : { table: e.table };
645
- let Dn = 0;
646
- function Ae() {
647
- return Dn += 1, `join-${Date.now().toString(36)}-${Dn}`;
648
- }
649
- let Gn = 0;
650
- function lr() {
651
- return Gn += 1, `select-${Date.now().toString(36)}-${Gn}`;
652
- }
653
- let Rn = 0;
654
- function qn() {
655
- return Rn += 1, `group-${Date.now().toString(36)}-${Rn}`;
656
- }
657
- let Qn = 0;
658
- function ur() {
659
- return Qn += 1, `order-${Date.now().toString(36)}-${Qn}`;
660
- }
661
- function ze(e, n, r) {
662
- if (n < 0 || n >= e.length || r < 0 || r >= e.length || n === r) return e;
663
- const t = [...e], [s] = t.splice(n, 1);
664
- return t.splice(r, 0, s), t;
665
- }
666
- const _n = (e) => e !== void 0 && Number.isSafeInteger(e) && e >= 0 ? e : void 0, Ze = (e) => (e ?? "").length <= Y;
667
- function Se(e, n, r) {
668
- return e.map((t) => t.id === n ? r(t) : t);
669
- }
670
- function mt(e, n, r) {
671
- return e.map((t) => t.id === n ? r(t) : t);
672
- }
673
- function cr(e) {
674
- return e.query ? { id: e.id, alias: e.alias, query: e.query } : e.shared !== void 0 ? { shared: e.shared, alias: e.alias } : { table: e.table, alias: e.alias };
675
- }
676
- function dr(e, n, r) {
677
- return e.query ? {
678
- id: e.id,
679
- alias: e.alias,
680
- query: e.query,
681
- joinType: r,
682
- on: n
683
- } : e.shared !== void 0 ? {
684
- id: Ae(),
685
- shared: e.shared,
686
- alias: e.alias,
687
- joinType: r,
688
- on: n
689
- } : {
690
- id: Ae(),
691
- table: e.table,
692
- alias: e.alias,
693
- joinType: r,
694
- on: n
695
- };
696
- }
697
- function yt(e, n) {
698
- const [r, ...t] = n;
699
- return { ...e, from: cr(r), joins: t };
700
- }
701
- function ne(e) {
702
- const n = /* @__PURE__ */ new Set(), r = (t) => {
703
- var s;
704
- if (t)
705
- switch (t.type) {
706
- case "field":
707
- t.table && n.add(t.table);
708
- break;
709
- case "binary":
710
- r(t.left), r(t.right);
711
- break;
712
- case "logical":
713
- t.operands.forEach(r);
714
- break;
715
- case "list":
716
- t.items.forEach(r);
717
- break;
718
- case "not":
719
- r(t.operand);
720
- break;
721
- case "if":
722
- r(t.condition), r(t.then), r(t.else);
723
- break;
724
- case "case":
725
- r(t.subject), t.branches.forEach((i) => {
726
- r(i.when), r(i.then);
727
- }), r(t.else);
728
- break;
729
- case "function":
730
- t.args.forEach(r), (s = t.orderBy) == null || s.forEach((i) => r(i.expression));
731
- break;
732
- // Only the tables its link names on the outer query's side: its own
733
- // tables are joined inside it (withExistsJoins), never to the query
734
- // around it — that would repeat its rows, which EXISTS is there to avoid.
735
- case "exists": {
736
- const i = Yn(t.query);
737
- ne(t.link).filter((a) => !i.has(a)).forEach((a) => n.add(a));
738
- break;
739
- }
740
- }
741
- };
742
- return r(e), [...n];
743
- }
744
- function yn(e, n, r, t, s) {
745
- const i = Be(n), a = t === void 0 && s === void 0, o = a ? Vt(e, i, r) : void 0, l = {
746
- id: Ae(),
747
- table: r,
748
- joinType: t ?? (o == null ? void 0 : o.joinType) ?? "inner",
749
- // Else matched to a derived table holding its key, if one does.
750
- on: s ?? (o == null ? void 0 : o.on) ?? (a ? or(e, n, r) : void 0)
751
- };
752
- return { ...n, joins: [...n.joins, l] };
753
- }
754
- function fr(e, n, r) {
755
- const t = Be(n), s = zn(e, t, r);
756
- return (s && s.length > 0 ? s : [r]).reduce((a, o) => yn(e, a, o), n);
757
- }
758
- function ce(e, n, r) {
759
- return ne(r).reduce((t, s) => {
760
- if (Q(t).some((o) => o.alias === s)) return t;
761
- const i = Be(t);
762
- return (zn(e, i, s) ?? [s]).reduce((o, l) => yn(e, o, l), t);
763
- }, n);
764
- }
765
- function mr(e, n, r, t) {
766
- return {
767
- ...ce(e, n, t),
768
- select: mt(n.select, r, (s) => ({ ...s, expression: t }))
769
- };
770
- }
771
- function hn(e, n, r) {
772
- const t = Q(e);
773
- if (n < 0 || n >= t.length || r < 0 || r >= t.length || n === r) return e;
774
- const s = [...t], [i] = s.splice(n, 1);
775
- s.splice(r, 0, i);
776
- const [a, o] = t;
777
- let l, c;
778
- if (n === 0 ? (c = a, l = o) : r === 0 && (l = t[n], c = a), l && c) {
779
- const { on: m, joinType: d } = l;
780
- s[s.indexOf(c)] = dr(c, m, d);
781
- }
782
- return yt(e, s);
783
- }
784
- function pn(e) {
785
- const n = /* @__PURE__ */ new Set([D(e.from)]);
786
- let r;
787
- return e.joins.some((t) => {
788
- n.add(D(t));
789
- const s = t.joinType === "cross" ? void 0 : t.on, i = ne(s).find((a) => !n.has(a));
790
- return i && (r = { table: t.table ?? D(t), needs: i }), i !== void 0;
791
- }), r;
792
- }
793
- function fs(e, n, r) {
794
- const t = hn(e, n, r);
795
- return t === e ? void 0 : pn(t);
796
- }
797
- function yr(e, n, r) {
798
- const t = hn(e, n, r);
799
- return t !== e && pn(t) === void 0;
800
- }
801
- function hr(e, n, r, t) {
802
- return {
803
- ...ce(e, n, t),
804
- orderBy: (n.orderBy ?? []).map((s) => s.id === r ? { ...s, expression: t } : s)
805
- };
806
- }
807
- function pr(e, n, r, t) {
808
- return {
809
- ...ce(e, n, t),
810
- groupBy: (n.groupBy ?? []).map((s) => s.id === r ? { ...s, expression: t } : s)
811
- };
812
- }
813
- function He(e, n) {
814
- if (!n || !Jt(n)) return n;
815
- const r = fe(n), t = r.map((l) => He(e, l)), i = t.some((l, c) => l !== r[c]) ? xe(n, (l) => t[r.indexOf(l)]) : n;
816
- if (i.type !== "exists") return i;
817
- const { query: a } = i, { joins: o } = ce(
818
- e,
819
- {
820
- id: "",
821
- from: a.from,
822
- joins: a.joins,
823
- select: []
824
- },
825
- a.where
826
- );
827
- return o === a.joins ? i : { ...i, query: { ...a, joins: o } };
828
- }
829
- function ms(e, n, r) {
830
- const t = He(e, r);
831
- return { ...ce(e, n, t), having: t };
832
- }
833
- function Fn(e, n) {
834
- const r = /* @__PURE__ */ new Set([
835
- ...n ? Q(n).map(D) : [],
836
- ...me(e).map((s) => s.name)
837
- ]);
838
- let t = 1;
839
- for (; r.has(`sub_query_${t}`); ) t += 1;
840
- return `sub_query_${t}`;
841
- }
842
- function ys() {
843
- return { id: W() };
844
- }
845
- function tn(e, n, r) {
846
- if (!ue(n))
847
- return r.type !== "setBaseTable" && r.type !== "setDerivedBaseTable" ? n : tn(e, {
848
- id: n.id,
849
- ...n.shared ? { shared: n.shared } : {},
850
- from: { table: "" },
851
- joins: [],
852
- select: []
853
- }, r);
854
- switch (r.type) {
855
- case "setBaseTable":
856
- return { ...n, from: { table: r.table } };
857
- case "setDerivedBaseTable":
858
- return {
859
- ...n,
860
- from: {
861
- id: r.id ?? Ae(),
862
- alias: Fn(e, n),
863
- query: { from: Ln(r), joins: [], select: [] }
864
- }
865
- };
866
- case "changeBaseAlias":
867
- return Ze(r.alias) ? {
868
- ...n,
869
- // A derived table (or a shared query's place) goes by its alias: it
870
- // can't be left without one.
871
- from: n.from.table === void 0 ? { ...n.from, alias: r.alias || n.from.alias } : { ...n.from, alias: r.alias }
872
- } : n;
873
- case "addJoin":
874
- return r.joinType === void 0 && r.on === void 0 ? fr(e, n, r.table) : yn(e, n, r.table, r.joinType, r.on);
875
- case "addDerivedJoin": {
876
- const t = {
877
- id: r.id ?? Ae(),
878
- alias: Fn(e, n),
879
- joinType: "left",
880
- query: { from: Ln(r), joins: [], select: [] }
881
- }, s = dt(e, n, t);
882
- return { ...n, joins: [...n.joins, { ...t, on: s }] };
883
- }
884
- case "renameDerivedTable": {
885
- const t = oe(n).find((l) => l.id === r.derivedId), s = r.alias.trim();
886
- if (!t || s === t.alias) return n;
887
- const i = Q(n).filter((l) => l !== t).map(D);
888
- if (!s || s.length > Y || i.includes(s) || z(e, s)) return n;
889
- const a = jn(n, t.alias, s), { from: o } = a;
890
- return {
891
- ...a,
892
- from: o.query && o.id === t.id ? { ...o, alias: s } : o,
893
- joins: a.joins.map((l) => l.id === t.id ? { ...l, alias: s } : l)
894
- };
895
- }
896
- case "renameSharedPlace": {
897
- const t = r.joinId === void 0 ? n.from : n.joins.find((o) => o.id === r.joinId), s = r.alias.trim();
898
- if ((t == null ? void 0 : t.shared) === void 0 || s === t.alias) return n;
899
- const i = Q(n).filter((o) => o !== t).map(D);
900
- if (!s || s.length > Y || i.includes(s) || z(e, s)) return n;
901
- const a = jn(n, t.alias, s);
902
- return r.joinId === void 0 ? { ...a, from: { ...a.from, alias: s } } : { ...a, joins: Se(a.joins, r.joinId, (o) => ({ ...o, alias: s })) };
903
- }
904
- case "setMeasureSynced":
905
- return {
906
- ...n,
907
- joins: Se(n.joins, r.joinId, (t) => t.query && t.drillAcross ? { ...t, drillAcross: { ...t.drillAcross, synced: r.synced } } : t)
908
- };
909
- case "removeJoin":
910
- return { ...n, joins: n.joins.filter((t) => t.id !== r.joinId) };
911
- case "changeJoinType":
912
- return {
913
- ...n,
914
- // A CROSS JOIN uses no ON, but keeps it: switched back, it's used again.
915
- joins: Se(n.joins, r.joinId, (t) => ({ ...t, joinType: r.joinType }))
916
- };
917
- case "changeJoinAlias":
918
- return Ze(r.alias) ? {
919
- ...n,
920
- // A derived table (or a shared query's place) goes by its alias: it
921
- // can't be left without one.
922
- joins: Se(n.joins, r.joinId, (t) => t.table === void 0 ? { ...t, alias: r.alias || t.alias } : { ...t, alias: r.alias })
923
- } : n;
924
- case "changeJoinOn":
925
- return {
926
- ...n,
927
- joins: Se(n.joins, r.joinId, (t) => ({
928
- ...t,
929
- on: He(e, r.on)
930
- }))
931
- };
932
- case "reorderJoin": {
933
- const t = n.joins.findIndex((a) => a.id === r.joinId);
934
- if (t === -1) return n;
935
- const s = r.direction === "up" ? t - 1 : t + 1;
936
- if (s < 0 || s >= n.joins.length) return n;
937
- const i = [...n.joins];
938
- return [i[t], i[s]] = [i[s], i[t]], { ...n, joins: i };
939
- }
940
- case "reorderTables":
941
- return yr(n, r.fromIndex, r.toIndex) ? hn(n, r.fromIndex, r.toIndex) : n;
942
- case "removeBaseTable":
943
- return n.joins.length > 0 ? yt(n, n.joins) : n.shared ? { id: n.id, shared: n.shared } : { id: n.id };
944
- case "addSelectItem": {
945
- const t = { id: lr(), expression: { type: "field" } };
946
- return { ...n, select: [...n.select, t] };
947
- }
948
- case "removeSelectItem":
949
- return { ...n, select: n.select.filter((t) => t.id !== r.selectId) };
950
- case "reorderSelectItems": {
951
- const t = ze(n.select, r.fromIndex, r.toIndex);
952
- return t === n.select ? n : { ...n, select: t };
953
- }
954
- case "setSelectAlias":
955
- return Ze(r.alias) ? {
956
- ...n,
957
- select: mt(n.select, r.selectId, (t) => ({ ...t, alias: r.alias }))
958
- } : n;
959
- case "setSelectExpression":
960
- return mr(e, n, r.selectId, r.expression);
961
- case "addGroupByItem": {
962
- const t = { id: qn(), expression: { type: "field" } };
963
- return { ...n, groupBy: [...n.groupBy ?? [], t] };
964
- }
965
- case "removeGroupByItem": {
966
- const t = (n.groupBy ?? []).filter((s) => s.id !== r.groupById);
967
- return { ...n, groupBy: t.length > 0 ? t : void 0 };
968
- }
969
- case "reorderGroupByItems": {
970
- const t = n.groupBy ?? [], s = ze(t, r.fromIndex, r.toIndex);
971
- return s === t ? n : { ...n, groupBy: s };
972
- }
973
- case "setGroupByExpression":
974
- return pr(e, n, r.groupById, r.expression);
975
- case "groupBySelectItem": {
976
- const t = n.select.find((i) => i.id === r.selectId);
977
- if (!t) return n;
978
- const s = { id: qn(), expression: t.expression };
979
- return { ...n, groupBy: [...n.groupBy ?? [], s] };
980
- }
981
- case "removeHaving":
982
- return { ...n, having: void 0 };
983
- case "setDistinct":
984
- return { ...n, distinct: r.distinct || void 0 };
985
- case "addOrderByItem": {
986
- const t = {
987
- id: ur(),
988
- expression: { type: "field" },
989
- direction: "asc"
990
- };
991
- return { ...n, orderBy: [...n.orderBy ?? [], t] };
992
- }
993
- case "removeOrderByItem": {
994
- const t = (n.orderBy ?? []).filter((s) => s.id !== r.orderById);
995
- return { ...n, orderBy: t.length > 0 ? t : void 0 };
996
- }
997
- case "reorderOrderByItems": {
998
- const t = n.orderBy ?? [], s = ze(t, r.fromIndex, r.toIndex);
999
- return s === t ? n : { ...n, orderBy: s };
1000
- }
1001
- case "setOrderByExpression":
1002
- return hr(e, n, r.orderById, r.expression);
1003
- case "setOrderByDirection":
1004
- return {
1005
- ...n,
1006
- orderBy: (n.orderBy ?? []).map((t) => t.id === r.orderById ? { ...t, direction: r.direction } : t)
1007
- };
1008
- case "setLimit":
1009
- return { ...n, limit: _n(r.limit) };
1010
- case "setOffset":
1011
- return { ...n, offset: _n(r.offset) };
1012
- case "clearPaging":
1013
- return { ...n, limit: void 0, offset: void 0 };
1014
- /* v8 ignore start -- PipelineAction is a closed union; every real case is
1015
- handled above. Exercised in tests via a bogus-cast, same convention as
1016
- applyRootAction's own `default` in PipelineEditor.tsx. */
1017
- default:
1018
- return n;
1019
- }
1020
- }
1021
- const gr = {
1022
- inner: "INNER",
1023
- left: "LEFT",
1024
- right: "RIGHT",
1025
- full: "FULL",
1026
- cross: "CROSS"
1027
- };
1028
- function hs(e) {
1029
- return `${gr[e.joinType]} JOIN ${D(e)}`;
1030
- }
1031
- function ps(e) {
1032
- return e.alias || "Column";
1033
- }
1034
- function gs() {
1035
- return "Sort";
1036
- }
1037
- function bs() {
1038
- return "Group";
1039
- }
1040
- function ws(e, n, r) {
1041
- const t = Q(n);
1042
- if (r !== void 0) {
1043
- const l = t.findIndex((c) => "id" in c && c.id === r);
1044
- return new Set(t.slice(0, l + 1).map(D));
1045
- }
1046
- const s = new Set(Be(n)), i = Pt(e, [...s]), a = new Set(ct(e, n).map((l) => l.table)), o = me(e).filter((l) => !s.has(l.name) && (i.has(l.name) || a.has(l.name)));
1047
- return /* @__PURE__ */ new Set([...t.map(D), ...o.map((l) => l.name)]);
1048
- }
1049
- function $s(e, n) {
1050
- const r = Q(n);
1051
- return me(e).flatMap((t) => {
1052
- const s = r.filter((i) => i.table === t.name).map(D);
1053
- return (s.length > 0 ? s : [t.name]).map((i) => ({ ref: i, table: t }));
1054
- });
1055
- }
1056
- function vs(e, n) {
1057
- const r = new Set(Be(n));
1058
- return me(e).filter((t) => !r.has(t.name));
1059
- }
1060
- function rn(e) {
1061
- return e ? e.type === "logical" ? e.operands.reduce((n, r) => n + rn(r), 0) : e.type === "not" ? rn(e.operand) : 1 : 0;
1062
- }
1063
- function Jn(e) {
1064
- return e.column ? e.table ? `${e.table}.${e.column}` : e.column : "?";
1065
- }
1066
- function Ss(e, n = ar) {
1067
- var r;
1068
- return e ? e.type === "binary" && e.left.type === "field" && ((r = e.right) == null ? void 0 : r.type) === "field" ? !e.left.column && !e.right.column ? n.setJoinCondition : `${Jn(e.left)} ${e.operator ?? "="} ${Jn(e.right)}` : n.conditionCount(rn(e)) : n.setJoinCondition;
1069
- }
1070
- function Es(e, n) {
1071
- const r = new Set(ne(e.where));
1072
- return ne(e.having).forEach((t) => r.add(t)), e.joins.filter((t) => t.id !== n).forEach((t) => ne(t.on).forEach((s) => r.add(s))), [...e.select, ...e.groupBy ?? [], ...e.orderBy ?? []].forEach((t) => ne(t.expression).forEach((s) => r.add(s))), r;
1073
- }
1074
- function Ts(e, n, r) {
1075
- const t = He(e, r);
1076
- return { ...ce(e, n, t), where: t };
1077
- }
1078
- function Ns(e, n, r, t) {
1079
- return r.length === 0 ? tn(e, n, t) : ue(n) ? mn(n, r, (s) => tn(e, s, t)) : n;
1080
- }
1081
- const gn = (e) => typeof e == "object" && e !== null && !Array.isArray(e) && !(e instanceof Date), bn = (e) => typeof e.shared == "string";
1082
- function qe(e, n) {
1083
- if (Array.isArray(e)) {
1084
- let s = !1;
1085
- const i = e.flatMap((a) => {
1086
- const o = qe(a, n);
1087
- return o !== a && (s = !0), o === void 0 ? [] : [o];
1088
- });
1089
- return s ? i : e;
1090
- }
1091
- if (!gn(e)) return e;
1092
- if (bn(e)) return n(e);
1093
- let r = !1;
1094
- const t = Object.entries(e).map(([s, i]) => {
1095
- const a = qe(i, n);
1096
- return a !== i && (r = !0), [s, a];
1097
- });
1098
- return r ? Object.fromEntries(t) : e;
1099
- }
1100
- function As(e) {
1101
- const n = new Map((e.shared ?? []).map((t) => [t.id, []])), r = (t, s) => {
1102
- if (Array.isArray(t)) {
1103
- t.forEach((i, a) => r(i, [...s, a]));
1104
- return;
1105
- }
1106
- if (gn(t)) {
1107
- if (bn(t)) {
1108
- const i = t.shared;
1109
- n.set(i, [...n.get(i) ?? [], s]);
1110
- return;
1111
- }
1112
- Object.entries(t).forEach(([i, a]) => r(a, [...s, i]));
1113
- }
1114
- };
1115
- return r(e, []), n;
1116
- }
1117
- function ks(e, n) {
1118
- const r = /* @__PURE__ */ new Set([
1119
- ...(n.shared ?? []).map((s) => s.name),
1120
- ...me(e).map((s) => s.name)
1121
- ]);
1122
- let t = 1;
1123
- for (; r.has(`shared_query_${t}`); ) t += 1;
1124
- return `shared_query_${t}`;
1125
- }
1126
- function br(e, n) {
1127
- const r = new Set(Q(n).map(D));
1128
- let t = e;
1129
- for (let s = 2; r.has(t); s += 1) t = `${e}_${s}`;
1130
- return t;
1131
- }
1132
- function wr(e, n, r, t = W(), s) {
1133
- const i = e.shared ?? [], a = i.findIndex((l) => l.id === s), o = { id: t, name: n, query: r };
1134
- return {
1135
- ...e,
1136
- shared: a < 0 ? [...i, o] : [...i.slice(0, a), o, ...i.slice(a)]
1137
- };
1138
- }
1139
- const ht = (e, n) => {
1140
- var r;
1141
- return (r = e.shared) == null ? void 0 : r.find((t) => t.id === n);
1142
- };
1143
- function xs(e, n, r, t = {}) {
1144
- const s = ht(e, r);
1145
- if (!s) return n;
1146
- const i = {
1147
- id: t.id ?? W(),
1148
- shared: r,
1149
- alias: br(s.name, n),
1150
- joinType: t.joinType ?? "inner",
1151
- ...t.on ? { on: t.on } : {}
1152
- };
1153
- return { ...n, joins: [...n.joins, i] };
1154
- }
1155
- function Bs(e, n, r) {
1156
- const t = ht(e, r);
1157
- return t ? { ...n, from: { shared: r, alias: t.name } } : n;
1158
- }
1159
- function Cs(e, n, r = W(), t = []) {
1160
- const s = sr(e, t), i = s && oe(s).find((c) => c.id === n);
1161
- if (!i) return e;
1162
- const a = new Set((e.shared ?? []).map((c) => c.name));
1163
- let o = i.alias;
1164
- for (let c = 2; a.has(o); c += 1) o = `${i.alias}_${c}`;
1165
- const l = wr(e, o, i.query, r, t[0]);
1166
- return mn(l, t, (c) => c.from.query && c.from.id === n ? { ...c, from: { shared: r, alias: i.alias } } : {
1167
- ...c,
1168
- joins: c.joins.map((m) => {
1169
- if (m.id !== n || !m.query) return m;
1170
- const { query: d, ...f } = m;
1171
- return { ...f, shared: r };
1172
- })
1173
- });
1174
- }
1175
- function pt(e, n) {
1176
- const { shared: r, ...t } = e;
1177
- return "joinType" in t ? { ...t, query: n } : { id: W(), alias: t.alias, query: n };
1178
- }
1179
- function Is(e, n) {
1180
- const r = new Map((e.shared ?? []).map((s) => [s.id, s.query])), t = n.reduce(
1181
- (s, i) => typeof s == "object" && s !== null ? s[i] : void 0,
1182
- e
1183
- );
1184
- return !gn(t) || !bn(t) ? e : qe(e, (s) => {
1185
- const i = r.get(s.shared);
1186
- return s === t && i ? pt(s, i) : s;
1187
- });
1188
- }
1189
- function Ms(e, n, r) {
1190
- var t;
1191
- return !((t = e.shared) != null && t.some((s) => s.id === n)) || r === "" ? e : {
1192
- ...e,
1193
- shared: e.shared.map((s) => s.id === n ? { ...s, name: r } : s)
1194
- };
1195
- }
1196
- class $r extends Error {
1197
- constructor(n) {
1198
- super(`removeSharedQuery: "${n}" is a query's base: make it a sub query there instead`), this.name = "SharedBaseError";
1199
- }
1200
- }
1201
- function Os(e, n, r = "subQueries") {
1202
- var l;
1203
- const t = (l = e.shared) == null ? void 0 : l.find((c) => c.id === n);
1204
- if (!t) return e;
1205
- const s = e.shared.filter((c) => c !== t), { shared: i, ...a } = e, o = s.length > 0 ? { ...a, shared: s } : a;
1206
- return qe(o, (c) => {
1207
- if (c.shared !== n) return c;
1208
- if (r === "subQueries") return pt(c, t.query);
1209
- if (!("joinType" in c)) throw new $r(t.name);
1210
- });
1211
- }
1212
- const gt = (e) => e.query !== void 0 && !H(e.query);
1213
- function bt(e) {
1214
- const n = /* @__PURE__ */ new Map();
1215
- return e.relations.forEach((r) => {
1216
- n.set(r.fromTable, [...n.get(r.fromTable) ?? [], r.toTable]);
1217
- }), n;
1218
- }
1219
- function Ce(e, n, r = bt(e)) {
1220
- const t = /* @__PURE__ */ new Set([n]), s = [n];
1221
- for (let i = s.shift(); i !== void 0; i = s.shift())
1222
- (r.get(i) ?? []).forEach((a) => {
1223
- t.has(a) || (t.add(a), s.push(a));
1224
- });
1225
- return t;
1226
- }
1227
- const we = (e) => e ? e.type === "logical" && e.operator === "AND" ? e.operands : [e] : [];
1228
- function wt(e, n) {
1229
- const r = new Map(Q(e).map((t) => [D(t), t.table]));
1230
- return ne(n).map((t) => ({
1231
- ref: t,
1232
- table: r.has(t) ? r.get(t) : t
1233
- }));
1234
- }
1235
- const wn = (e, n) => wt(e, n).map((r) => r.table);
1236
- function Pn(e, n) {
1237
- const r = new Map(Q(e).map((t) => [D(t), t.table]));
1238
- return fn(n, (t) => {
1239
- if (t.type !== "field" || t.table === void 0) return t;
1240
- const s = r.get(t.table);
1241
- return s === void 0 || s === t.table ? t : { ...t, table: s };
1242
- });
1243
- }
1244
- function $t(e, n) {
1245
- const r = (n.groupBy ?? []).flatMap((s) => wt(n, s.expression)), t = bt(e);
1246
- return me(e).map((s) => {
1247
- const i = Ce(e, s.name, t), a = r.find((o) => o.table === void 0 || !i.has(o.table));
1248
- return a ? { table: s, unlinked: a.table ?? a.ref } : { table: s };
1249
- });
1250
- }
1251
- function vr(e, n, r) {
1252
- const t = Ce(e, r);
1253
- return we(n.where).filter((s) => {
1254
- const i = wn(n, s);
1255
- return i.length > 0 && i.every((a) => a !== void 0 && t.has(a));
1256
- });
1257
- }
1258
- function Sr(e, n, r) {
1259
- const t = Ce(e, r);
1260
- return we(n.where).some((s) => {
1261
- const i = wn(n, s);
1262
- return i.some((a) => a !== void 0 && t.has(a)) && i.some((a) => a === void 0 || !t.has(a));
1263
- });
1264
- }
1265
- function Re(e, n) {
1266
- let r = e;
1267
- for (let t = 2; n.has(r); t += 1) r = `${e}_${t}`;
1268
- return r;
1269
- }
1270
- function sn(e, n) {
1271
- if (e.type === "field" && e.column) return e.column;
1272
- if (e.type === "function") {
1273
- const r = e.args[0];
1274
- return (r == null ? void 0 : r.type) === "field" && r.column ? r.column : e.name.toLowerCase() || n;
1275
- }
1276
- return n;
1277
- }
1278
- const on = (e, n) => ({ type: "field", table: e, column: n });
1279
- function Er(e, n) {
1280
- return {
1281
- type: "logical",
1282
- operator: "OR",
1283
- operands: [
1284
- {
1285
- type: "binary",
1286
- operator: "=",
1287
- left: e,
1288
- right: n
1289
- },
1290
- {
1291
- type: "logical",
1292
- operator: "AND",
1293
- operands: [
1294
- { type: "binary", operator: "IS NULL", left: e },
1295
- { type: "binary", operator: "IS NULL", left: n }
1296
- ]
1297
- }
1298
- ]
1299
- };
1300
- }
1301
- function Tr(e, n, r) {
1302
- var i;
1303
- if (r.type !== "field" || r.table === void 0 || r.column === void 0) return !1;
1304
- const t = wn(n, r)[0], s = (i = z(e, t)) == null ? void 0 : i.columns.find((a) => a.name === r.column);
1305
- return s !== void 0 && !s.nullable;
1306
- }
1307
- function vt(e, n, r, t) {
1308
- const s = n.groupBy.map((a) => a.expression), i = t.map((a, o) => Tr(e, n, s[o]) ? {
1309
- type: "binary",
1310
- operator: "=",
1311
- left: on(r, a),
1312
- right: s[o]
1313
- } : Er(on(r, a), s[o]));
1314
- return i.length === 1 ? i[0] : { type: "logical", operator: "AND", operands: i };
1315
- }
1316
- function St(e, n, r, t, s, i) {
1317
- var k;
1318
- const a = n.groupBy.map((b) => Pn(n, b.expression)), o = vr(e, n, r).map((b) => Pn(n, b)), l = new Set(s.map((b) => b.alias).filter((b) => !!b)), c = a.map((b, I) => {
1319
- const G = Re(sn(b, `key_${I + 1}`), l);
1320
- return l.add(G), G;
1321
- }), m = [...o, ...t];
1322
- let d = {
1323
- id: "",
1324
- from: { table: r },
1325
- joins: [],
1326
- select: []
1327
- };
1328
- [...a, ...m, ...s.map((b) => b.expression)].forEach((b) => {
1329
- d = ce(e, d, b);
1330
- });
1331
- const f = ((k = i == null ? void 0 : i.groupBy) == null ? void 0 : k.length) ?? 0, p = [...(i == null ? void 0 : i.joins) ?? []], v = d.joins.map((b) => {
1332
- const I = p.findIndex((R) => R.table !== void 0 && R.table === b.table);
1333
- if (I === -1) return b;
1334
- const [G] = p.splice(I, 1);
1335
- return { ...b, id: G.id };
1336
- }), $ = {
1337
- ...i,
1338
- from: d.from,
1339
- joins: v,
1340
- where: m.length > 0 ? { type: "logical", operator: "AND", operands: m } : void 0,
1341
- groupBy: a.map((b, I) => {
1342
- var G, R;
1343
- return {
1344
- id: ((R = (G = i == null ? void 0 : i.groupBy) == null ? void 0 : G[I]) == null ? void 0 : R.id) ?? W(),
1345
- expression: b
1346
- };
1347
- }),
1348
- select: [
1349
- ...a.map((b, I) => {
1350
- var G;
1351
- return {
1352
- id: I < f && ((G = i == null ? void 0 : i.select[I]) == null ? void 0 : G.id) || W(),
1353
- alias: c[I],
1354
- expression: b
1355
- };
1356
- }),
1357
- ...s
1358
- ]
1359
- };
1360
- return $.where === void 0 && delete $.where, { query: $, copied: o.length, keyNames: c };
1361
- }
1362
- function Us(e, n, r) {
1363
- var v;
1364
- if ((n.groupBy ?? []).length === 0)
1365
- throw new Error("addMeasure: the query isn't grouped (a measure is per group)");
1366
- const t = $t(e, n).find(($) => $.table.name === r.table);
1367
- if (!t) throw new Error(`addMeasure: unknown table "${r.table}"`);
1368
- if (t.unlinked !== void 0)
1369
- throw new Error(`addMeasure: "${r.table}" doesn't share the query's grouping`);
1370
- const s = we(r.where), i = n.joins.find(($) => {
1371
- var k;
1372
- return gt($) && ((k = $.drillAcross) == null ? void 0 : k.synced) === !0 && $.query.from.table === r.table && Z(we($.query.where).slice($.drillAcross.copied), s);
1373
- });
1374
- let { joins: a } = n, o, l;
1375
- if (i) {
1376
- o = i.alias;
1377
- const $ = ((v = i.query.groupBy) == null ? void 0 : v.length) ?? 0, k = i.query.select.slice($).find((b) => Z(b.expression, r.value));
1378
- if (k)
1379
- l = k.alias;
1380
- else {
1381
- l = Re(
1382
- sn(r.value, "value"),
1383
- new Set(i.query.select.map((I) => I.alias ?? ""))
1384
- );
1385
- const b = { id: W(), alias: l, expression: r.value };
1386
- a = a.map((I) => I === i ? { ...i, query: { ...i.query, select: [...i.query.select, b] } } : I);
1387
- }
1388
- } else {
1389
- l = sn(r.value, "value");
1390
- const $ = { id: W(), alias: l, expression: r.value }, k = St(e, n, r.table, s, [$]), b = /* @__PURE__ */ new Set([
1391
- ...Q(n).map(D),
1392
- ...me(e).map((R) => R.name)
1393
- ]), I = `${r.table}_per_${k.keyNames.join("_and_")}`.slice(0, Y - 4);
1394
- o = Re(I, b);
1395
- const G = {
1396
- id: W(),
1397
- alias: o,
1398
- joinType: "left",
1399
- query: k.query,
1400
- on: vt(e, n, o, k.keyNames),
1401
- drillAcross: { synced: !0, copied: k.copied }
1402
- };
1403
- a = [...a, G];
1404
- }
1405
- const c = {
1406
- type: "function",
1407
- name: "MAX",
1408
- args: [on(o, l)]
1409
- }, m = new Set(n.select.map(($) => $.alias).filter(($) => !!$)), d = Re(`${r.table}_${l}`.slice(0, Y - 4), m);
1410
- let f = r.selectId !== void 0 ? n.select.map(($) => $.id === r.selectId ? { ...$, expression: c, alias: $.alias || d } : $) : [...n.select, { id: W(), expression: c, alias: d }];
1411
- return f = [...n.groupBy.filter(($) => !f.some((k) => Z(k.expression, $.expression))).map(($) => ({ id: W(), expression: $.expression })), ...f], { ...n, joins: a, select: f };
1412
- }
1413
- function Et(e, n, r) {
1414
- var m, d;
1415
- if (!gt(r)) return;
1416
- const t = r, s = t.query.from.table, i = n.groupBy ?? [];
1417
- if (s === void 0 || i.length === 0) return;
1418
- const a = $t(e, n).find((f) => f.table.name === s);
1419
- if (!a || a.unlinked !== void 0) return;
1420
- const o = ((m = t.query.groupBy) == null ? void 0 : m.length) ?? 0, l = we(t.query.where).slice(((d = t.drillAcross) == null ? void 0 : d.copied) ?? 0), c = St(e, n, s, l, t.query.select.slice(o), t.query);
1421
- return {
1422
- ...t,
1423
- query: c.query,
1424
- on: vt(e, n, t.alias, c.keyNames),
1425
- drillAcross: { synced: !0, copied: c.copied }
1426
- };
1427
- }
1428
- function Qe(e) {
1429
- var t, s;
1430
- const n = Ve(e.query), r = ((t = n.groupBy) == null ? void 0 : t.length) ?? 0;
1431
- return {
1432
- keys: (n.groupBy ?? []).map((i) => i.expression),
1433
- keyColumns: n.select.slice(0, r).map((i) => [i.alias, i.expression]),
1434
- copied: we(n.where).slice(0, ((s = e.drillAcross) == null ? void 0 : s.copied) ?? 0),
1435
- on: e.on
1436
- };
1437
- }
1438
- function Nr(e, n, r) {
1439
- const t = Et(e, n, r);
1440
- return t !== void 0 && Z(Qe(t), Qe(r));
1441
- }
1442
- function Tt(e, n, r) {
1443
- let t = !1;
1444
- const s = (o, l) => We(
1445
- l,
1446
- (c, m) => Tt(
1447
- e,
1448
- o && H(o) === H(l) ? be(o)[m] : void 0,
1449
- c
1450
- )
1451
- ), i = r.from.query ? (() => {
1452
- const o = n != null && n.from.query && n.from.id === r.from.id ? n.from.query : void 0, l = s(o, r.from.query);
1453
- return l === r.from.query ? r.from : { ...r.from, query: l };
1454
- })() : r.from;
1455
- i !== r.from && (t = !0);
1456
- const a = r.joins.map((o) => {
1457
- var d;
1458
- if (!o.query) return o;
1459
- const l = n == null ? void 0 : n.joins.find((f) => f.id === o.id && f.query !== void 0), c = s(l == null ? void 0 : l.query, o.query);
1460
- let m = c === o.query ? o : { ...o, query: c };
1461
- if ((d = m.drillAcross) != null && d.synced) {
1462
- const f = Et(e, r, m);
1463
- f && !Z(f, m) && (m = f);
1464
- } else if (m.drillAcross && (l != null && l.drillAcross) && !Z(Qe(l), Qe(m))) {
1465
- const f = { ...m };
1466
- delete f.drillAcross, m = f;
1467
- }
1468
- return m !== o && (t = !0), m;
1469
- });
1470
- return t ? { ...r, from: i, joins: a } : r;
1471
- }
1472
- function Ar(e, n, r) {
1473
- return ue(r) ? Tt(e, n && ue(n) ? n : void 0, r) : r;
1474
- }
1475
- const js = ["text", "number", "date", "boolean"], kr = {
1476
- varchar: "text",
1477
- integer: "integer",
1478
- decimal: "number",
1479
- date: "date",
1480
- dateTime: "dateTime",
1481
- time: "time",
1482
- boolean: "boolean"
1483
- };
1484
- function Nt(e) {
1485
- return kr[e];
1486
- }
1487
- function xr(e) {
1488
- const n = e.trim().toUpperCase();
1489
- if (/^((TINY|SMALL|MEDIUM|BIG)?INT|SIGNED|UNSIGNED)/.test(n)) return "integer";
1490
- if (/^(DECIMAL|NUMERIC|FLOAT|DOUBLE|REAL|MONEY)/.test(n)) return "number";
1491
- if (/^(DATETIME|TIMESTAMP|SMALLDATETIME)/.test(n)) return "dateTime";
1492
- if (n.startsWith("DATE")) return "date";
1493
- if (n.startsWith("TIME")) return "time";
1494
- if (/^BOOL|^BIT$/.test(n)) return "boolean";
1495
- if (/^(N?VAR)?CHAR|^N?TEXT|^STRING/.test(n)) return "text";
1496
- }
1497
- function _e(e) {
1498
- if (e.as) return e.as;
1499
- const { value: n } = e;
1500
- if (typeof n == "string") return n === "" ? void 0 : "text";
1501
- if (typeof n == "number") return Number.isInteger(n) ? "integer" : "number";
1502
- if (typeof n == "bigint") return "integer";
1503
- if (typeof n == "boolean") return "boolean";
1504
- if (n instanceof Date) return nt(n) ? "date" : "dateTime";
1505
- }
1506
- function $n(e, n, r) {
1507
- if (!e) return;
1508
- const t = (s) => $n(s, n, r);
1509
- switch (e.type) {
1510
- case "field":
1511
- return n(e);
1512
- case "literal":
1513
- return _e(e);
1514
- case "function": {
1515
- const s = Zn(e.name, r), i = (s == null ? void 0 : s.args.findIndex((l) => l.kind === "type-name")) ?? -1, a = i >= 0 ? e.args[i] : void 0;
1516
- if ((a == null ? void 0 : a.type) === "literal" && typeof a.value == "string")
1517
- return xr(a.value);
1518
- const o = s == null ? void 0 : s.returns;
1519
- return o === "arg" ? t(e.args[0]) : o;
1520
- }
1521
- case "if":
1522
- return t(e.then) ?? t(e.else);
1523
- case "case":
1524
- return [...e.branches.map((s) => s.then), e.else].map(t).find((s) => s !== void 0);
1525
- default:
1526
- return;
1527
- }
1528
- }
1529
- const Br = /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i, Cr = /^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/, Ir = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?$/;
1530
- function vn(e, n) {
1531
- if (e === "" || e === null) return e;
1532
- const r = typeof e == "string" ? e.trim() : void 0;
1533
- switch (n) {
1534
- case "text":
1535
- return e instanceof Date ? zt(e) : String(e);
1536
- case "integer":
1537
- case "number": {
1538
- let t;
1539
- return typeof e == "number" ? t = e : typeof e == "bigint" ? t = Number(e) : r !== void 0 && Br.test(r) && (t = Number(r)), t === void 0 || !nn(t) || n === "integer" && !Number.isInteger(t) ? void 0 : t;
1540
- }
1541
- case "date":
1542
- case "dateTime": {
1543
- if (e instanceof Date) return n === "date" && !nt(e) ? void 0 : e;
1544
- const t = r === void 0 ? null : Ir.exec(r);
1545
- if (!t) return;
1546
- const [, s, i, a, o, l, c] = t.map(Number), m = Yt(s, i, a);
1547
- return m.getUTCMonth() !== i - 1 || m.getUTCDate() !== a ? void 0 : t[4] === void 0 ? m : n === "date" ? void 0 : new Date(Date.UTC(s, i - 1, a, o, l, Number.isNaN(c) ? 0 : c));
1548
- }
1549
- case "time": {
1550
- const t = r === void 0 ? null : Cr.exec(r);
1551
- return t ? `${t[1]}:${t[2]}:${t[3] ?? "00"}` : void 0;
1552
- }
1553
- case "boolean":
1554
- return typeof e == "boolean" ? e : e === 1 || r === "1" || (r == null ? void 0 : r.toLowerCase()) === "true" ? !0 : e === 0 || r === "0" || (r == null ? void 0 : r.toLowerCase()) === "false" ? !1 : void 0;
1555
- /* v8 ignore start -- ValueType is a closed union, every case above */
1556
- default:
1557
- return;
1558
- }
1559
- }
1560
- function Mr(e, n, r) {
1561
- var m;
1562
- if (n === void 0) return e;
1563
- const { as: t, empty: s, ...i } = e;
1564
- let a = vn(e.value, n);
1565
- r != null && r.length && a !== "" && a !== null && (a = (m = r.find((d) => String(d.value) === String(e.value))) == null ? void 0 : m.value);
1566
- const o = s && n === "text", l = a === void 0 ? { type: "literal", value: "" } : { ...i, value: a, ...o ? { empty: s } : {} };
1567
- return t === void 0 && !!s == !!o && a === e.value ? e : l;
1568
- }
1569
- function Ls(e, n, r, t = !1) {
1570
- const s = e.items.flatMap((a) => {
1571
- if (a.type !== "literal") return [a];
1572
- const o = Mr(a, n, r);
1573
- return o.value === "" && !o.empty && !t ? [] : [o];
1574
- });
1575
- return s.length === e.items.length && s.every((a, o) => a === e.items[o]) ? e : { ...e, items: s };
1576
- }
1577
- function Ds(e) {
1578
- const n = _e(e);
1579
- return n === "integer" || n === "number" ? "number" : n === "date" || n === "dateTime" ? "date" : n;
1580
- }
1581
- function Gs(e, n) {
1582
- const t = (e.type === "literal" ? vn(e.value, n) : void 0) ?? "", s = e.type === "literal" && e.empty && n === "text";
1583
- return {
1584
- type: "literal",
1585
- value: t,
1586
- as: n,
1587
- ...s ? { empty: s } : {}
1588
- };
1589
- }
1590
- function Rs(e, n = !1) {
1591
- if (e !== void 0)
1592
- return e === "text" ? [
1593
- "=",
1594
- "!=",
1595
- "LIKE",
1596
- "REGEXP",
1597
- "IN",
1598
- ...n ? ["BETWEEN"] : [],
1599
- "IS NULL",
1600
- "IS NOT NULL"
1601
- ] : e === "boolean" ? ["=", "!=", "IS NULL", "IS NOT NULL"] : ["=", "!=", "<", "<=", ">", ">=", "IN", "BETWEEN", "IS NULL", "IS NOT NULL"];
1602
- }
1603
- const At = "source", kt = "rows_", se = (e) => e ? { type: "literal", value: null, as: e } : { type: "literal", value: null }, ke = (e) => e.type === "literal" && e.value === null, Sn = (e) => new Map(
1604
- Q(e).map((n) => [D(n), n.table])
1605
- );
1606
- function an(e, n) {
1607
- const r = Sn(e);
1608
- return ne(n).map((t) => r.get(t) ?? t);
1609
- }
1610
- function xt(e, n) {
1611
- const r = Sn(e);
1612
- return fn(n, (t) => {
1613
- if (t.type !== "field" || t.table === void 0) return t;
1614
- const s = r.get(t.table);
1615
- return s === void 0 || s === t.table ? t : { ...t, table: s };
1616
- });
1617
- }
1618
- function Fe(e, n, r) {
1619
- const t = Sn(n);
1620
- return $n(r, (s) => {
1621
- var o;
1622
- const i = t.get(s.table ?? "") ?? s.table ?? "", a = (o = z(e, i)) == null ? void 0 : o.columns.find((l) => l.name === s.column);
1623
- return a && Nt(a.type);
1624
- }, $e);
1625
- }
1626
- function En(e, n) {
1627
- let r = e;
1628
- for (let t = 2; n.has(r); t += 1) r = `${e}_${t}`;
1629
- return r;
1630
- }
1631
- const Je = (e) => e ? e.type === "logical" && e.operator === "AND" ? e.operands : [e] : [], Bt = (e) => {
1632
- if (e.length !== 0)
1633
- return e.length === 1 ? e[0] : { type: "logical", operator: "AND", operands: e };
1634
- }, ie = (e) => e.from.table, Vn = (e, n) => z(e, n).label;
1635
- function Xe(e) {
1636
- const { from: n } = e;
1637
- return n.query && H(n.query) ? n : void 0;
1638
- }
1639
- function Ie(e, n) {
1640
- if (n === void 0) return Xe(e);
1641
- const r = oe(e).find((t) => t.id === n);
1642
- return r && H(r.query) ? r : void 0;
1643
- }
1644
- function Me(e, n, r) {
1645
- const t = { ...n, query: r };
1646
- return n === e.from ? { ...e, from: t } : { ...e, joins: e.joins.map((s) => s === n ? t : s) };
1647
- }
1648
- function Ke(e, n) {
1649
- const [r] = n;
1650
- return r.select.map((t, s) => {
1651
- var d;
1652
- const i = K(t) ?? "", a = n.map((f) => {
1653
- var p;
1654
- return { branch: f, expression: (p = f.select[s]) == null ? void 0 : p.expression };
1655
- }).filter((f) => f.expression !== void 0 && !ke(f.expression)), l = ((d = n.map((f) => {
1656
- var p;
1657
- return (p = f.select[s]) == null ? void 0 : p.expression;
1658
- }).filter(
1659
- (f) => (f == null ? void 0 : f.type) === "literal" && f.value === null
1660
- ).find((f) => f.as)) == null ? void 0 : d.as) ?? (a[0] && Fe(e, a[0].branch, a[0].expression));
1661
- if (i === At && a.length === n.length && a.every((f) => f.expression.type === "literal"))
1662
- return {
1663
- name: i,
1664
- kind: "source",
1665
- tables: [],
1666
- type: "text"
1667
- };
1668
- if (i.startsWith(kt) && a.length === 1 && a[0].expression.type === "literal")
1669
- return {
1670
- name: i,
1671
- kind: "rows",
1672
- tables: [],
1673
- type: "integer"
1674
- };
1675
- const c = a[0];
1676
- if (!c)
1677
- return {
1678
- name: i,
1679
- kind: "shared",
1680
- tables: [],
1681
- type: l
1682
- };
1683
- const m = an(c.branch, c.expression);
1684
- return a.some((f) => an(f.branch, f.expression).includes(ie(f.branch))) ? {
1685
- name: i,
1686
- kind: "own",
1687
- tables: m,
1688
- type: l
1689
- } : {
1690
- name: i,
1691
- kind: "shared",
1692
- tables: m,
1693
- type: l,
1694
- expression: xt(c.branch, c.expression)
1695
- };
1696
- });
1697
- }
1698
- function qs(e, n) {
1699
- const r = Xe(n);
1700
- if (!r) return [];
1701
- const { union: t } = r.query;
1702
- return Ke(e, t).map((s, i) => {
1703
- const a = t.map((o) => !ke(o.select[i].expression));
1704
- return {
1705
- name: s.name,
1706
- kind: s.kind,
1707
- filledBy: t.filter((o, l) => a[l]).map(ie),
1708
- nullIn: t.filter((o, l) => !a[l]).map(ie)
1709
- };
1710
- });
1711
- }
1712
- function Ct(e, n, r, t, s) {
1713
- const i = Ce(e, n), a = r.filter((m) => m.kind === "shared" && m.expression), o = (m) => m.tables.every((d) => i.has(d));
1714
- if (!a.some(o)) return `"${n}" shares no column with the union`;
1715
- const l = a.find((m) => !o(m));
1716
- if (l && s === "refuse")
1717
- return `"${n}" can't reach column "${l.name}" (${l.tables.join(", ")})`;
1718
- const c = t.find((m) => !m.tables.every((d) => i.has(d)));
1719
- if (c)
1720
- return `"${n}" can't follow a condition on ${c.tables.join(", ")}`;
1721
- }
1722
- function It(e) {
1723
- const [n] = e, r = new Set(e.map(ie));
1724
- return Je(n.where).flatMap((t) => {
1725
- const s = an(n, t), i = s.filter((a) => r.has(a));
1726
- if (i.length === 0) return [{ operand: xt(n, t), tables: s }];
1727
- if (i.length === s.length) return [];
1728
- throw new Error("a condition naming both a branch's own table and shared ones can't be placed: split it, or put it on the union instead");
1729
- });
1730
- }
1731
- function Wn(e, n, r, t) {
1732
- const s = t.unshared ?? "refuse", i = Ke(e, n), a = It(n);
1733
- if (!z(e, r.table))
1734
- throw new Error(`addUnionTable: unknown table "${r.table}"`);
1735
- if (n.some((x) => ie(x) === r.table))
1736
- throw new Error(`addUnionTable: "${r.table}" is in the union already`);
1737
- const o = Ct(e, r.table, i, a, s);
1738
- if (o) throw new Error(`addUnionTable: ${o}`);
1739
- const l = Ce(e, r.table), c = r.label ?? Vn(e, r.table), m = i.map((x) => x.kind === "source" ? { type: "literal", value: c } : x.kind === "shared" && x.expression && x.tables.every((F) => l.has(F)) ? x.expression : se(x.type)), d = new Set(i.map((x) => x.name)), f = [], p = (x) => {
1740
- const F = En(x, d);
1741
- return d.add(F), f.push(F), F;
1742
- }, v = [], $ = {
1743
- from: { table: r.table },
1744
- joins: []
1745
- };
1746
- r.columns.forEach((x) => {
1747
- const F = x.alias ?? (x.expression.type === "field" ? x.expression.column : void 0) ?? "value", pe = Fe(e, $, x.expression);
1748
- v.push({ name: p(F), own: x.expression, others: () => se(pe) });
1749
- }), t.source && !i.some((x) => x.kind === "source") && v.push({
1750
- name: p(At),
1751
- own: { type: "literal", value: c },
1752
- others: (x) => ({ type: "literal", value: Vn(e, ie(x)) })
1753
- });
1754
- const k = (x) => `${kt}${x}`;
1755
- (t.rowMarkers || i.some((x) => x.kind === "rows")) && (n.filter((x) => !d.has(k(ie(x)))).forEach((x) => {
1756
- v.push({
1757
- name: p(k(ie(x))),
1758
- own: se("integer"),
1759
- others: (F) => F === x ? { type: "literal", value: 1 } : se("integer")
1760
- });
1761
- }), v.push({
1762
- name: p(k(r.table)),
1763
- own: { type: "literal", value: 1 },
1764
- others: () => se("integer")
1765
- }));
1766
- const b = (x, F) => ({
1767
- id: W(),
1768
- alias: x,
1769
- expression: F
1770
- }), I = n.map((x) => ({
1771
- ...x,
1772
- select: [...x.select, ...v.map((F) => b(F.name, F.others(x)))]
1773
- })), G = Bt([...a.map((x) => x.operand), ...Je(r.where)]);
1774
- let R = {
1775
- id: "",
1776
- from: { table: r.table },
1777
- joins: [],
1778
- ...G ? { where: G } : {},
1779
- select: [
1780
- ...i.map((x, F) => b(x.name, m[F])),
1781
- ...v.map((x) => b(x.name, x.own))
1782
- ]
1783
- };
1784
- [G, ...R.select.map((x) => x.expression)].forEach((x) => {
1785
- R = ce(e, R, x);
1786
- });
1787
- const {
1788
- from: X,
1789
- joins: ee,
1790
- select: ye,
1791
- where: he
1792
- } = R, te = {
1793
- from: X,
1794
- joins: ee,
1795
- select: ye,
1796
- ...he ? { where: he } : {}
1797
- };
1798
- return { union: [...I, te], added: f };
1799
- }
1800
- function Mt(e) {
1801
- const n = (s) => new Error(`addUnionTable: ${s}`);
1802
- if (e.from.query) throw n("the query reads from a derived table");
1803
- if (e.select.length === 0) throw n("the query picks no columns (SELECT *)");
1804
- if ((e.groupBy ?? []).length > 0 || e.having || e.distinct || (e.orderBy ?? []).length > 0 || e.select.some((s) => le(s.expression, $e)))
1805
- throw n("a union is of detail rows: no aggregates, GROUP BY, HAVING, DISTINCT or ORDER BY");
1806
- const r = /* @__PURE__ */ new Set(), t = e.select.map((s, i) => {
1807
- const a = En(K(s) ?? `column_${i + 1}`, r);
1808
- return r.add(a), { ...s, alias: a };
1809
- });
1810
- return {
1811
- from: e.from,
1812
- joins: e.joins,
1813
- ...e.where ? { where: e.where } : {},
1814
- select: t
1815
- };
1816
- }
1817
- function Qs(e, n, r, t = {}) {
1818
- const s = Xe(n);
1819
- if (s) {
1820
- const { union: c, added: m } = Wn(e, s.query.union, r, t), d = { ...s, query: { ...s.query, union: c } }, f = n.select.length === 0 ? [] : [
1821
- ...n.select,
1822
- ...m.map((p) => ({
1823
- id: W(),
1824
- expression: { type: "field", table: s.alias, column: p }
1825
- }))
1826
- ];
1827
- return { ...n, from: d, select: f };
1828
- }
1829
- const i = Mt(n), { union: a } = Wn(e, [i], r, t), o = t.alias ?? "stacked", l = a[0].select.map((c) => c.alias);
1830
- return {
1831
- id: n.id,
1832
- from: { id: W(), alias: o, query: { union: a, all: !0 } },
1833
- joins: [],
1834
- select: l.map((c) => ({
1835
- id: W(),
1836
- expression: { type: "field", table: o, column: c }
1837
- })),
1838
- ...n.limit !== void 0 ? { limit: n.limit } : {},
1839
- ...n.offset !== void 0 ? { offset: n.offset } : {}
1840
- };
1841
- }
1842
- function _s(e, n, r = {}) {
1843
- const t = Xe(n);
1844
- let s;
1845
- try {
1846
- s = t ? t.query.union : [Mt(n)];
1847
- } catch {
1848
- return [];
1849
- }
1850
- const i = Ke(e, s);
1851
- let a;
1852
- try {
1853
- a = It(s);
1854
- } catch {
1855
- return [];
1856
- }
1857
- const o = /* @__PURE__ */ new Set([
1858
- ...s.map(ie),
1859
- ...i.flatMap((l) => l.kind === "shared" ? l.tables : [])
1860
- ]);
1861
- return e.tables.map((l) => l.name).filter((l) => !o.has(l) && Ct(e, l, i, a, r.unshared ?? "refuse") === void 0);
1862
- }
1863
- function Or(e, n, r) {
1864
- const t = r.union.findIndex((l, c) => l.select !== n.union[c].select);
1865
- if (t === -1) return r;
1866
- const s = r.union[t], i = n.union[t].select.map((l) => l.id), a = r.union.map((l, c) => {
1867
- if (c === t) return l;
1868
- const m = s.select.map((f) => {
1869
- const p = K(f), v = Fe(e, s, f.expression), $ = i.indexOf(f.id), k = $ === -1 ? void 0 : l.select[$];
1870
- if (!k)
1871
- return { id: W(), ...p ? { alias: p } : {}, expression: se(v) };
1872
- let b = k;
1873
- K(k) !== p && (b = { ...b, alias: p });
1874
- const { expression: I } = k;
1875
- return ke(I) && I.type === "literal" && I.as !== v && (b = { ...b, expression: se(v) }), b;
1876
- });
1877
- return m.length === l.select.length && m.every((f, p) => f === l.select[p]) ? l : { ...l, select: m };
1878
- }), o = a.map((l) => {
1879
- const c = l.select.map((m, d) => {
1880
- const { expression: f } = m;
1881
- if (f.type !== "literal" || f.value !== null) return m;
1882
- const p = a.find(($) => {
1883
- var b;
1884
- const k = (b = $.select[d]) == null ? void 0 : b.expression;
1885
- return k !== void 0 && !ke(k);
1886
- }), v = p && Fe(e, p, p.select[d].expression);
1887
- return v && f.as !== v ? { ...m, expression: se(v) } : m;
1888
- });
1889
- return c.every((m, d) => m === l.select[d]) ? l : { ...l, select: c };
1890
- });
1891
- return o.every((l, c) => l === r.union[c]) ? r : { ...r, union: o };
1892
- }
1893
- function Ur(e, n) {
1894
- const r = (i) => i.union[0].select.map((a) => K(a)), t = r(e), s = r(n);
1895
- return t.length !== s.length ? [] : t.flatMap((i, a) => {
1896
- const o = s[a];
1897
- return i && o && i !== o && !s.includes(i) && !t.includes(o) ? [{ from: i, to: o }] : [];
1898
- });
1899
- }
1900
- function Ot(e, n, r) {
1901
- let t = r;
1902
- n && H(n) && H(t) && n.union.length === t.union.length && (t = Or(e, n, t));
1903
- const s = t;
1904
- return We(s, (i, a) => Tn(
1905
- e,
1906
- n && H(n) === H(s) ? be(n)[a] : void 0,
1907
- i
1908
- ));
1909
- }
1910
- function Tn(e, n, r) {
1911
- const t = (f) => {
1912
- var p;
1913
- return Ot(
1914
- e,
1915
- n && ((p = oe(n).find((v) => v.id === f.id)) == null ? void 0 : p.query),
1916
- f.query
1917
- );
1918
- }, { from: s } = r, i = s.query && t(s), a = i && i !== s.query ? { ...s, query: i } : s;
1919
- let o = !1;
1920
- const l = r.joins.map((f) => {
1921
- if (!f.query) return f;
1922
- const p = t(f);
1923
- return p === f.query ? f : (o = !0, { ...f, query: p });
1924
- });
1925
- if (a === s && !o) return r;
1926
- const c = { ...r, from: a, joins: l }, m = oe(c).flatMap((f) => {
1927
- var v;
1928
- const p = n && ((v = oe(n).find(($) => $.id === f.id)) == null ? void 0 : v.query);
1929
- return p && H(p) && H(f.query) ? Ur(p, f.query).map(($) => ({ ...$, alias: f.alias })) : [];
1930
- });
1931
- if (m.length === 0) return c;
1932
- const d = (f) => {
1933
- if (f.type !== "field") return xe(f, d);
1934
- const p = m.find((v) => v.alias === f.table && v.from === f.column);
1935
- return p ? { ...f, column: p.to } : f;
1936
- };
1937
- return Pe(c, d, (f) => f);
1938
- }
1939
- function jr(e, n, r) {
1940
- if (!ue(r)) return r;
1941
- const t = n && ue(n) ? n : void 0;
1942
- return dn(Tn(e, t, r), (s, i) => {
1943
- var a, o;
1944
- return Ot(
1945
- e,
1946
- (o = (a = t == null ? void 0 : t.shared) == null ? void 0 : a.find((l) => l.id === i.id)) == null ? void 0 : o.query,
1947
- s
1948
- );
1949
- });
1950
- }
1951
- function Ut(e) {
1952
- return e.type === "field" ? [e] : fe(e).flatMap(Ut);
1953
- }
1954
- const jt = (e, n, r) => Ut(e).some((t) => t.table === n && r.has(t.column ?? ""));
1955
- function Lr(e, n, r) {
1956
- const t = n.query.union.filter((l, c) => c !== r), s = [
1957
- e.where,
1958
- e.having,
1959
- ...e.joins.map((l) => l.on),
1960
- ...(e.groupBy ?? []).map((l) => l.expression),
1961
- ...(e.orderBy ?? []).map((l) => l.expression)
1962
- ].filter((l) => l !== void 0), i = (l) => s.some(
1963
- (c) => jt(c, n.alias, /* @__PURE__ */ new Set([l]))
1964
- ), a = new Set(t[0].select.flatMap((l, c) => {
1965
- const m = t.every((f) => f.select[c] && ke(f.select[c].expression)), d = K(l);
1966
- return m && !(d && i(d)) ? [c] : [];
1967
- })), o = new Set([...a].flatMap((l) => {
1968
- const c = K(t[0].select[l]);
1969
- return c ? [c] : [];
1970
- }));
1971
- return { at: a, names: o };
1972
- }
1973
- function Fs(e, n, r) {
1974
- const t = Ie(e, r);
1975
- if (!t || !t.query.union[n] || t.query.union.length < 2) return e;
1976
- const s = Lr(e, t, n), i = t.query.union.filter((c, m) => m !== n), a = s.at.size < i[0].select.length ? s : { at: /* @__PURE__ */ new Set(), names: /* @__PURE__ */ new Set() }, o = e.select.filter(
1977
- (c) => !jt(c.expression, t.alias, a.names)
1978
- ), l = i.map((c) => ({ ...c, select: c.select.filter((m, d) => !a.at.has(d)) }));
1979
- return Me({ ...e, select: o }, t, { ...t.query, union: l });
1980
- }
1981
- function Dr(e, n) {
1982
- const r = /* @__PURE__ */ new Set([
1983
- ...n ? Q(n).map(D) : [],
1984
- ...e.tables.map((s) => s.name)
1985
- ]);
1986
- let t = 1;
1987
- for (; r.has(`union_${t}`); ) t += 1;
1988
- return `union_${t}`;
1989
- }
1990
- function Js(e, n, r, t) {
1991
- return {
1992
- id: e,
1993
- from: { id: n, alias: r, query: { union: [{ from: t, joins: [], select: [] }], all: !0 } },
1994
- joins: [],
1995
- select: []
1996
- };
1997
- }
1998
- function Ps(e, n, r) {
1999
- const t = /* @__PURE__ */ new Set(), s = e.select.map(($, k) => {
2000
- const b = En(K($) ?? `column_${k + 1}`, t);
2001
- return t.add(b), { ...$, alias: b };
2002
- }), {
2003
- from: i,
2004
- joins: a,
2005
- where: o,
2006
- groupBy: l,
2007
- having: c,
2008
- distinct: m
2009
- } = e, d = {
2010
- from: i,
2011
- joins: a,
2012
- select: s,
2013
- ...o ? { where: o } : {},
2014
- ...l ? { groupBy: l } : {},
2015
- ...c ? { having: c } : {},
2016
- ...m !== void 0 ? { distinct: m } : {}
2017
- }, f = ($) => ({ type: "field", table: r, column: $ }), p = ($) => {
2018
- var k;
2019
- return (k = s.find((b) => Z(b.expression, $))) == null ? void 0 : k.alias;
2020
- }, v = {
2021
- ...e,
2022
- from: { id: n, alias: r, query: { union: [d], all: !0 } },
2023
- joins: [],
2024
- select: s.map(($) => ({ id: W(), expression: f($.alias) })),
2025
- ...e.orderBy ? {
2026
- orderBy: e.orderBy.map(($) => {
2027
- const k = p($.expression);
2028
- return k ? { ...$, expression: f(k) } : $;
2029
- })
2030
- } : {}
2031
- };
2032
- return ["where", "groupBy", "having", "distinct"].forEach(($) => delete v[$]), v;
2033
- }
2034
- function Vs(e, n, r, t) {
2035
- const s = Ie(n, r);
2036
- if (!s) return n;
2037
- const i = Ke(e, s.query.union).map((a) => ({
2038
- id: W(),
2039
- ...a.name ? { alias: a.name } : {},
2040
- expression: se(a.type)
2041
- }));
2042
- return Me(n, s, {
2043
- ...s.query,
2044
- union: [...s.query.union, { from: t, joins: [], select: i }]
2045
- });
2046
- }
2047
- function Ws(e, n, r, t) {
2048
- const s = {
2049
- id: r,
2050
- alias: Dr(e, n),
2051
- joinType: "left",
2052
- query: { union: [{ from: t, joins: [], select: [] }], all: !0 }
2053
- };
2054
- return { ...n, joins: [...n.joins, { ...s, on: dt(e, n, s) }] };
2055
- }
2056
- function Hs(e, n, r) {
2057
- const t = Ie(e, n);
2058
- return !t || t.query.all === r ? e : Me(e, t, { ...t.query, all: r });
2059
- }
2060
- function Xs(e, n, r, t, s) {
2061
- const i = Ie(n, r), [a, ...o] = (i == null ? void 0 : i.query.union) ?? [], l = a == null ? void 0 : a.select[t], c = s.trim();
2062
- if (!i || !l || !c || c.length > Y || a.select.some((d) => K(d) === c)) return n;
2063
- const m = Me(n, i, {
2064
- ...i.query,
2065
- union: [
2066
- { ...a, select: a.select.map((d, f) => f === t ? { ...d, alias: c } : d) },
2067
- ...o
2068
- ]
2069
- });
2070
- return Tn(e, n, m);
2071
- }
2072
- function Ks(e, n) {
2073
- var m;
2074
- const r = Ie(e, n);
2075
- if (!r || r.query.union.length !== 1) return e;
2076
- const [t] = r.query.union, s = new Map(t.select.flatMap((d) => {
2077
- const f = K(d);
2078
- return f ? [[f, d.expression]] : [];
2079
- })), i = (d) => d.type === "field" && d.table === r.alias && s.has(d.column ?? ""), a = (d) => fn(d, (f) => i(f) ? s.get(f.column) : f), o = e.select.map((d) => {
2080
- const f = a(d.expression);
2081
- if (d.alias || !i(d.expression)) return { ...d, expression: f };
2082
- const p = d.expression.column;
2083
- return K({ ...d, expression: f }) === p ? { ...d, expression: f } : { ...d, expression: f, alias: p };
2084
- }), l = t.groupBy !== void 0 || t.having !== void 0 || !!t.distinct || t.select.some((d) => le(d.expression, $e));
2085
- if (r === e.from && !l) {
2086
- const d = Pe({ ...e, select: o }, a, (f) => f);
2087
- return {
2088
- ...d,
2089
- from: t.from,
2090
- joins: [...t.joins, ...d.joins],
2091
- where: Bt([...Je(t.where), ...Je(d.where)]),
2092
- // Nothing picked: the query's own columns, as the union had them.
2093
- select: d.select.length > 0 ? d.select : t.select
2094
- };
2095
- }
2096
- const c = e.joins.length === 0 && !e.where && !((m = e.groupBy) != null && m.length) && !e.having && !e.distinct && [...e.select, ...e.orderBy ?? []].every((d) => i(d.expression));
2097
- return r === e.from && c ? {
2098
- ...e,
2099
- ...t,
2100
- select: o.length > 0 ? o : t.select,
2101
- ...e.orderBy ? {
2102
- orderBy: e.orderBy.map((d) => ({ ...d, expression: a(d.expression) }))
2103
- } : {}
2104
- } : Me(e, r, t);
2105
- }
2106
- const Hn = (e, n) => e.type === "binary" && e.operator === "IS NULL" && Z(e.left, n);
2107
- function ln(e) {
2108
- var n;
2109
- if (!e) return [];
2110
- if (e.type === "logical" && e.operator === "AND") return e.operands.flatMap(ln);
2111
- if (e.type === "binary" && (e.operator ?? "=") === "=" && e.left.type === "field" && ((n = e.right) == null ? void 0 : n.type) === "field")
2112
- return [[e.left, e.right]];
2113
- if (e.type === "logical" && e.operator === "OR" && e.operands.length === 2) {
2114
- const [[r] = [], t] = [ln(e.operands[0]), e.operands[1]];
2115
- if (r && t.type === "logical" && t.operator === "AND" && t.operands.length === 2 && Hn(t.operands[0], r[0]) && Hn(t.operands[1], r[1]))
2116
- return [r];
2117
- }
2118
- return [];
2119
- }
2120
- function Gr(e, n) {
2121
- const r = e.groupBy ?? [];
2122
- return r.length > 0 && r.every((t) => e.select.some((s) => Z(s.expression, t.expression) && n.includes(K(s) ?? "")));
2123
- }
2124
- function Rr(e, n) {
2125
- const r = D(e.from), t = /* @__PURE__ */ new Map([[r, e.from.table]]), s = [r], i = e.shared ?? [];
2126
- return e.joins.map((a) => {
2127
- var f, p;
2128
- const { id: o } = a, l = Te(a, i), c = D(a);
2129
- t.set(c, a.table);
2130
- const m = ln(a.on).flatMap(([v, $]) => [[v, $], [$, v]]).filter(([v, $]) => v.table === c && s.includes($.table ?? ""));
2131
- if (s.push(c), a.joinType === "cross")
2132
- return {
2133
- joinId: o,
2134
- key: c,
2135
- parent: r,
2136
- side: l && lt(l) ? "one" : "cross"
2137
- };
2138
- if (a.table === void 0) {
2139
- const v = m.length > 0 && l !== void 0 && !H(l) && Gr(l, m.map(([$]) => $.column));
2140
- return {
2141
- joinId: o,
2142
- key: c,
2143
- parent: ((f = m[0]) == null ? void 0 : f[1].table) ?? r,
2144
- side: v ? "one" : "unknown"
2145
- };
2146
- }
2147
- return m.map(([v, $]) => {
2148
- const k = t.get($.table), b = (I, G) => n.relations.some((R) => R.fromTable === I[0] && R.fromColumn === I[1].column && R.toTable === G[0] && R.toColumn === G[1].column);
2149
- if (b([a.table, v], [k, $]))
2150
- return {
2151
- joinId: o,
2152
- key: c,
2153
- parent: $.table,
2154
- side: "many"
2155
- };
2156
- if (b([k, $], [a.table, v]))
2157
- return {
2158
- joinId: o,
2159
- key: c,
2160
- parent: $.table,
2161
- side: "one"
2162
- };
2163
- }).find((v) => v !== void 0) ?? {
2164
- joinId: o,
2165
- key: c,
2166
- parent: ((p = m[0]) == null ? void 0 : p[1].table) ?? r,
2167
- side: "unknown"
2168
- };
2169
- });
2170
- }
2171
- function un(e, n, r = {}) {
2172
- const t = Rr(e, n).map((o) => o.side === "unknown" && r.unknown === "repeat" ? { ...o, side: "many" } : o), s = [D(e.from), ...t.map((o) => o.key)], i = (o) => {
2173
- const l = /* @__PURE__ */ new Set([o]);
2174
- return t.forEach((c) => {
2175
- l.has(c.parent) && l.add(c.key);
2176
- }), l;
2177
- }, a = /* @__PURE__ */ new Set();
2178
- return t.forEach((o) => {
2179
- const l = i(o.key);
2180
- o.side === "many" && s.filter((c) => !l.has(c)).forEach((c) => a.add(c)), o.side === "one" && l.forEach((c) => a.add(c)), o.side === "cross" && s.forEach((c) => a.add(c));
2181
- }), a;
2182
- }
2183
- const qr = /* @__PURE__ */ new Set(["SUM", "AVG", "COUNT"]);
2184
- function Qr(e, n) {
2185
- return e.type === "field" ? e.table && n.has(e.table) ? [e.table] : [] : [...new Set(fe(e).flatMap((r) => Qr(r, n)))];
2186
- }
2187
- function Ys(e, n) {
2188
- const r = D(e.from);
2189
- return e.joins.some((s) => s.joinType === "right" || s.joinType === "full") || un(e, n).has(r) ? "many" : un(e, n, { unknown: "repeat" }).has(r) ? "unknown" : "one";
2190
- }
2191
- function Lt(e, n, r = !1) {
2192
- const t = e.type === "function" && qr.has(e.name.toUpperCase()) && !e.distinct, s = r || t;
2193
- return e.type === "field" ? s && e.table && n.has(e.table) ? [e.table] : [] : fe(e).flatMap((i) => Lt(i, n, s));
2194
- }
2195
- function _r(e, n) {
2196
- const r = un(e, n), t = /* @__PURE__ */ new Set(), s = (l) => {
2197
- const c = l ? Lt(l, r) : [];
2198
- return c.forEach((m) => t.add(m)), c.length > 0;
2199
- }, i = e.select.filter((l) => s(l.expression)).map((l) => l.id), a = (e.orderBy ?? []).filter((l) => s(l.expression)).map((l) => l.id), o = s(e.having);
2200
- return {
2201
- tables: [...t],
2202
- select: i,
2203
- orderBy: a,
2204
- having: o
2205
- };
2206
- }
2207
- function Fr(e, n) {
2208
- return e.select.filter((r) => le(r.expression, n));
2209
- }
2210
- function Jr(e) {
2211
- return { ...e.expression, fromSelect: e.id };
2212
- }
2213
- function Ee(e) {
2214
- const { fromSelect: n, ...r } = e;
2215
- return n === void 0 ? e : r;
2216
- }
2217
- function Dt(e, n) {
2218
- const r = (s) => typeof s.fromSelect == "string" ? n(s, s.fromSelect) : xe(s, r), t = r(e);
2219
- return Z(t, e) ? e : t;
2220
- }
2221
- function Pr(e, n) {
2222
- var o;
2223
- const r = new Map(Fr(e, n).map((l) => [l.id, l])), t = (l) => Dt(l, (c, m) => {
2224
- const d = r.get(m);
2225
- return d ? Jr(d) : Ee(c);
2226
- }), s = e.having && t(e.having);
2227
- let i = !1;
2228
- const a = (o = e.orderBy) == null ? void 0 : o.map((l) => {
2229
- const c = t(l.expression);
2230
- return c === l.expression ? l : (i = !0, { ...l, expression: c });
2231
- });
2232
- return s === e.having && !i ? e : { ...e, having: s, ...a ? { orderBy: a } : {} };
2233
- }
2234
- function zs(e, n) {
2235
- const r = new Set((n.groupBy ?? []).flatMap(({ expression: t }) => t.type === "field" && t.column ? [t.column.toLowerCase()] : []));
2236
- return Dt(e, (t, s) => {
2237
- const i = n.select.find((a) => a.id === s);
2238
- return !(i != null && i.alias) || r.has(i.alias.toLowerCase()) || !Z(Ee(t), i.expression) ? Ee(t) : { type: "field", column: i.alias };
2239
- });
2240
- }
2241
- function cn(e, n) {
2242
- const r = (m) => cn(m, n), t = (m) => We(m, r), s = e.from.query && t(e.from.query), i = s && s !== e.from.query ? { ...e.from, query: s } : e.from;
2243
- let a = !1;
2244
- const o = e.joins.map((m) => {
2245
- if (!m.query) return m;
2246
- const d = t(m.query);
2247
- return d === m.query ? m : (a = !0, { ...m, query: d });
2248
- }), l = i === e.from && !a ? e : { ...e, from: i, joins: o }, c = st(l, (m) => {
2249
- const d = r(m.query);
2250
- return d === m.query ? m : { ...m, query: d };
2251
- });
2252
- return Wt(Pr(c, n), n);
2253
- }
2254
- function Zs(e, n, r, t = $e) {
2255
- if (!ue(r)) return r;
2256
- const s = dn(
2257
- cn(r, t),
2258
- (a) => We(a, (o) => cn(o, t))
2259
- ), i = jr(e, n, s);
2260
- return Ar(e, n, i);
2261
- }
2262
- const Vr = [
2263
- "=",
2264
- "!=",
2265
- "<",
2266
- "<=",
2267
- ">",
2268
- ">=",
2269
- "LIKE",
2270
- "IN",
2271
- "BETWEEN",
2272
- "REGEXP",
2273
- "IS NULL",
2274
- "IS NOT NULL"
2275
- ], Wr = ["IS NULL", "IS NOT NULL"];
2276
- function Hr(e) {
2277
- return Wr.includes(e);
2278
- }
2279
- function Xr(e) {
2280
- return !e.distinct || !e.orderBy ? [] : e.orderBy.filter(({ expression: n }) => !(n.type === "field" && !n.column)).filter(({ expression: n }) => e.select.length === 0 ? n.type !== "field" : !e.select.some((r) => Z(r.expression, Ee(n)))).map(({ id: n }) => n);
2281
- }
2282
- function Gt(e, n) {
2283
- n(e), fe(e).forEach((r) => Gt(r, n));
2284
- }
2285
- const Rt = (e) => {
2286
- const n = /* @__PURE__ */ new Map();
2287
- return et(e, (r) => (r.type === "param" && r.relative && (n.has(r.name) || n.set(r.name, /* @__PURE__ */ new Set()), n.get(r.name).add(JSON.stringify(r.relative))), r)), n;
2288
- };
2289
- function qt(e, n) {
2290
- const r = /* @__PURE__ */ new Map(), t = (i, a) => Gt(i, (o) => {
2291
- if (o.type === "param" && !r.has(o.name) && r.set(o.name, /* @__PURE__ */ new Set()), o.type !== "binary" || !o.right) return;
2292
- const l = (m, d) => {
2293
- const f = a(d);
2294
- m.type !== "param" || !f || (r.has(m.name) || r.set(m.name, /* @__PURE__ */ new Set()), r.get(m.name).add(f));
2295
- };
2296
- l(o.left, o.right), (o.right.type === "list" ? o.right.items : [o.right]).forEach((m) => l(m, o.left));
2297
- }), s = (i) => {
2298
- const a = /* @__PURE__ */ new Map();
2299
- Q(i).forEach((l) => a.set(D(l), l.table));
2300
- const o = (l) => {
2301
- var d;
2302
- if (!n || l.type !== "field" || !l.table || !l.column) return;
2303
- const c = a.has(l.table) ? a.get(l.table) : l.table, m = c === void 0 ? void 0 : z(n, c);
2304
- return (d = m == null ? void 0 : m.columns.find((f) => f.name === l.column)) == null ? void 0 : d.type;
2305
- };
2306
- Xn(i).forEach((l) => t(l, o)), Q(i).forEach((l) => l.query && be(l.query).forEach(s)), rt(i).forEach((l) => s(l.query));
2307
- };
2308
- return (e.shared ?? []).forEach((i) => be(i.query).forEach(s)), s(e), r;
2309
- }
2310
- function ei(e, n) {
2311
- const r = Rt(e);
2312
- return [...qt(e, n)].map(([t, s]) => {
2313
- const i = r.get(t);
2314
- return {
2315
- name: t,
2316
- ...s.size === 1 ? { type: [...s][0] } : {},
2317
- // (Two different ones: validateQuery reports it; the first here.)
2318
- ...i ? { relative: JSON.parse([...i][0]) } : {}
2319
- };
2320
- });
2321
- }
2322
- function Kr(e) {
2323
- return [...Rt(e)].filter(([, n]) => n.size > 1).map(([n]) => n);
2324
- }
2325
- function Yr(e, n) {
2326
- return [...qt(e, n)].filter(([, r]) => r.size > 1).map(([r]) => r);
2327
- }
2328
- function ni(e, n) {
2329
- const r = new Map(Object.entries(n));
2330
- return et(e, (t) => {
2331
- if (t.type !== "param") return t;
2332
- if (!r.has(t.name)) throw new Error(`no value for parameter "${t.name}"`);
2333
- const s = r.get(t.name);
2334
- return s === "" ? { type: "literal", value: s, empty: !0 } : { type: "literal", value: s };
2335
- });
2336
- }
2337
- function zr(e, n, r, t) {
2338
- const s = new Map(t);
2339
- return Q(n).forEach((i) => {
2340
- var o;
2341
- const a = i.table !== void 0 ? (o = z(e, i.table)) == null ? void 0 : o.columns : (() => {
2342
- const l = Te(i, r);
2343
- return l && Ne(e, l, r);
2344
- })();
2345
- s.set(D(i), new Set((a ?? []).filter((l) => l.joinOnly).map((l) => l.name)));
2346
- }), s;
2347
- }
2348
- function Zr(e, n) {
2349
- const r = [], t = n.shared ?? [], s = (o, l, c, m) => {
2350
- var f;
2351
- if (Array.isArray(o)) {
2352
- o.forEach((p, v) => s(p, [...l, v], c, m));
2353
- return;
2354
- }
2355
- if (typeof o != "object" || o === null || o instanceof Date) return;
2356
- const d = o;
2357
- if (d.type === "field") {
2358
- const { table: p, column: v } = d;
2359
- !m && p && v && ((f = c.get(p)) != null && f.has(v)) && r.push(l);
2360
- return;
2361
- }
2362
- if (d.type === "subquery") {
2363
- a(d.query, [...l, "query"], !0);
2364
- return;
2365
- }
2366
- if (d.type === "exists") {
2367
- const p = d.query;
2368
- a(p, [...l, "query"], !1, c);
2369
- return;
2370
- }
2371
- Object.entries(d).forEach(([p, v]) => s(v, [...l, p], c, m));
2372
- }, i = (o, l) => {
2373
- "union" in o ? be(o).forEach((c, m) => a(c, [...l, "union", m], !0)) : a(o, l, !0);
2374
- };
2375
- function a(o, l, c, m) {
2376
- var p, v, $;
2377
- const d = zr(e, o, t, m);
2378
- o.from.query && i(o.from.query, [...l, "from", "query"]), o.joins.forEach((k, b) => {
2379
- k.query && i(k.query, [...l, "joins", b, "query"]), k.on && s(k.on, [...l, "joins", b, "on"], d, !0);
2380
- }), o.where && s(o.where, [...l, "where"], d, !1);
2381
- const f = o;
2382
- (p = f.select) == null || p.forEach((k, b) => s(
2383
- k.expression,
2384
- [...l, "select", b, "expression"],
2385
- d,
2386
- c
2387
- )), (v = f.groupBy) == null || v.forEach((k, b) => s(
2388
- k.expression,
2389
- [...l, "groupBy", b, "expression"],
2390
- d,
2391
- c
2392
- )), f.having && s(f.having, [...l, "having"], d, !1), ($ = f.orderBy) == null || $.forEach((k, b) => s(
2393
- k.expression,
2394
- [...l, "orderBy", b, "expression"],
2395
- d,
2396
- !1
2397
- ));
2398
- }
2399
- return t.forEach((o, l) => i(o.query, ["shared", l, "query"])), a(n, [], !1), r;
2400
- }
2401
- function ti(e, n) {
2402
- return !(e === "mssql" && n === "REGEXP");
2403
- }
2404
- function es(e, n) {
2405
- return !(e === "mysql" && n === "full");
2406
- }
2407
- const ri = [
2408
- "invalidStructure",
2409
- "duplicateId",
2410
- "unknownTable",
2411
- "unknownColumn",
2412
- "tableNotInQuery",
2413
- "unqualifiedField",
2414
- "incomplete",
2415
- "argCount",
2416
- "ambiguousTable",
2417
- "duplicateTableName",
2418
- "derivedColumnName",
2419
- "unknownFunction",
2420
- "joinOrder",
2421
- "distinctSort",
2422
- "notGrouped",
2423
- "unknownAggregate",
2424
- "misplacedAggregate",
2425
- "paramConflict",
2426
- "fanOut",
2427
- "crossJoin",
2428
- "unlinkedJoin",
2429
- "drillAcrossOutOfStep",
2430
- "drillAcrossFilterMixed",
2431
- "tooLong",
2432
- "dialectUnsupported",
2433
- "subqueryColumns",
2434
- "notInSubquery",
2435
- "noLimit",
2436
- "limitTooHigh",
2437
- "typeMismatch",
2438
- "invalidPattern",
2439
- "unionColumns",
2440
- "unionTypes",
2441
- "sharedOrder",
2442
- "unusedShared",
2443
- "joinOnlyColumn"
2444
- ], si = [
2445
- "fanOut",
2446
- "crossJoin",
2447
- "unlinkedJoin",
2448
- "drillAcrossFilterMixed",
2449
- "notInSubquery",
2450
- "noLimit",
2451
- "limitTooHigh",
2452
- "typeMismatch",
2453
- "unknownAggregate",
2454
- "unusedShared"
2455
- ];
2456
- function ns(e) {
2457
- return [...e.matchAll(/([A-Za-z_][A-Za-z0-9_]*)|\[(\d+)\]/g)].map(([, n, r]) => n ?? Number(r));
2458
- }
2459
- const De = (e) => e === "integer" ? "number" : e === "dateTime" ? "date" : e, de = {
2460
- text: "text",
2461
- integer: "a whole number",
2462
- number: "a number",
2463
- date: "a date",
2464
- dateTime: "a date and time",
2465
- time: "a time of day",
2466
- boolean: "yes / no"
2467
- }, O = (e) => typeof e == "object" && e !== null && !Array.isArray(e), q = (e) => typeof e == "string", ts = ["day", "week", "month", "year"], rs = (e) => O(e) && ts.includes(e.unit) && Number.isSafeInteger(e.offset) && (e.anchor === void 0 || e.unit !== "day" && (e.anchor === "start" || e.anchor === "end")), ge = (e) => e === void 0 || q(e), ss = (e) => e === null || q(e) || typeof e == "boolean" || typeof e == "bigint" || typeof e == "number" && Number.isFinite(e) || e instanceof Date && !Number.isNaN(e.getTime()), en = (e) => O(e) && e.type === "literal" && e.value === "" && e.empty !== !0;
2468
- function ii(e, n, r = {}) {
2469
- var xn, Bn;
2470
- const t = [], s = (u, y, g, h = "error") => {
2471
- t.push({
2472
- kind: u,
2473
- severity: h,
2474
- path: y,
2475
- pathSegments: ns(y),
2476
- message: g
2477
- });
2478
- };
2479
- if (!O(n) || !q(n.id) || n.id === "")
2480
- return s("invalidStructure", "", "a query is an object with a non-empty string id"), t;
2481
- if (!("from" in n)) return t;
2482
- const i = Ht(e, r.tableFilter, r.columnFilter), a = Xt(r.functions ?? $e);
2483
- let o = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), c;
2484
- const m = (u, y, g, h) => {
2485
- q(u) && u.length > y && s("tooLong", g, `${h} is longer than ${y} characters`);
2486
- }, d = /* @__PURE__ */ new Set(), f = O(n) && Array.isArray(n.shared) ? n.shared : [], p = new Set(f.flatMap((u) => O(u) && q(u.id) ? [u.id] : [])), v = /* @__PURE__ */ new Map(), $ = /* @__PURE__ */ new Set();
2487
- let k;
2488
- const b = (u, y) => {
2489
- o.has(u) && s("duplicateTableName", y, `two tables named "${u}"`);
2490
- }, I = (u, y) => {
2491
- On.includes(u) && !es(r.dialect, u) && s("dialectUnsupported", y, `${u.toUpperCase()} JOIN isn't in this database`);
2492
- }, G = (u, y, g = !1) => {
2493
- if (g && O(u) && u.query !== void 0) {
2494
- k(u, y);
2495
- return;
2496
- }
2497
- if (g && O(u) && u.shared !== void 0) {
2498
- const { shared: N, alias: w } = u, S = q(w) && w !== "";
2499
- if (!q(N) || !S || u.table !== void 0) {
2500
- s("invalidStructure", y, "a shared query's place has a string `shared` and an `alias`, and no `table`"), S && (b(w, `${y}.alias`), o.set(w, void 0));
2501
- return;
2502
- }
2503
- m(w, Y, `${y}.alias`, "an alias"), b(w, `${y}.alias`), $.add(N), p.has(N) ? v.has(N) || s("sharedOrder", `${y}.shared`, "a shared query can use only those before it") : s("unknownTable", `${y}.shared`, `no shared query "${N}"`), o.set(w, v.get(N));
2504
- return;
2505
- }
2506
- if (!O(u) || !q(u.table) || !ge(u.alias)) {
2507
- s("invalidStructure", y, "a table entry has a string `table` and optional `alias`");
2508
- return;
2509
- }
2510
- m(u.alias, Y, `${y}.alias`, "an alias");
2511
- const h = i.tables.find((N) => N.name === u.table);
2512
- h || s("unknownTable", `${y}.table`, `unknown table "${u.table}"`), q(u.alias) && u.alias !== "" ? (b(u.alias, `${y}.alias`), o.set(u.alias, h), l.set(u.table, u.alias)) : (b(u.table, `${y}.table`), o.set(u.table, h));
2513
- }, R = (u, y, g) => {
2514
- var T;
2515
- if (!u) return;
2516
- const { args: h, name: N } = u, w = h.filter((A) => !A.optional).length, S = (T = h[h.length - 1]) != null && T.variadic ? 1 / 0 : h.length;
2517
- y < w ? s("incomplete", g, `${N} needs ${w} argument(s)`) : y > S && s("argCount", g, `${N} takes ${S} argument(s)`);
2518
- };
2519
- let X, ee, ye;
2520
- const he = (u) => {
2521
- const y = u.table && (o.get(u.table) ?? (c == null ? void 0 : c.get(u.table)));
2522
- if (!y || Array.isArray(y)) return;
2523
- const g = y.columns.find((h) => h.name === u.column);
2524
- return g && Nt(g.type);
2525
- }, te = (u) => $n(u, he, a), x = r.typeMismatch ?? "warning", F = (u, y, g) => {
2526
- if (u.type === "literal") {
2527
- if (u.value === null || u.value === "" && !u.empty || typeof u.value == "number" && !nn(u.value) || vn(u.value, y) !== void 0) return;
2528
- const w = u.value instanceof Date ? "a date" : JSON.stringify(String(u.value));
2529
- s("typeMismatch", g, `${w} isn't ${de[y]}`, x);
2530
- return;
2531
- }
2532
- const h = te(u);
2533
- if (h === void 0 || De(h) === De(y)) return;
2534
- const N = `${de[h]} compared with ${de[y]}`;
2535
- s("typeMismatch", g, N, x);
2536
- }, pe = (u) => u && u.type !== "literal" ? te(u) : void 0, Qt = (u, y) => {
2537
- const { operator: g, left: h, right: N } = u;
2538
- if (!N) return;
2539
- const w = (T, A, M) => {
2540
- if (T.type !== "param" || !T.relative) return;
2541
- const E = pe(A);
2542
- if (E === void 0 || E === "date" || E === "dateTime") return;
2543
- const C = `a relative date compared with ${de[E]}`;
2544
- s("typeMismatch", M, C, x);
2545
- };
2546
- if (w(N, h, `${y}.right`), w(h, N, `${y}.left`), g === "LIKE" || g === "REGEXP") {
2547
- const T = pe(h);
2548
- if (T !== void 0 && T !== "text") {
2549
- const A = `${g} matches text, not ${de[T]}`;
2550
- s("typeMismatch", `${y}.left`, A, x);
2551
- }
2552
- if (F(N, "text", `${y}.right`), g === "REGEXP" && N.type === "literal" && q(N.value))
2553
- try {
2554
- new RegExp(N.value);
2555
- } catch (A) {
2556
- const M = `not a regular expression: ${A.message}`;
2557
- s("invalidPattern", `${y}.right`, M);
2558
- }
2559
- return;
2560
- }
2561
- const S = pe(h);
2562
- if (g === "IN" || g === "BETWEEN") {
2563
- if (S === void 0 || N.type !== "list") return;
2564
- N.items.forEach((T, A) => F(T, S, `${y}.right.items[${A}]`));
2565
- return;
2566
- }
2567
- if (S !== void 0) F(N, S, `${y}.right`);
2568
- else {
2569
- const T = pe(N);
2570
- T !== void 0 && F(h, T, `${y}.left`);
2571
- }
2572
- }, Nn = (u) => {
2573
- const y = u.map(([g]) => g.type === "literal" ? _e(g) : te(g)).find((g) => g !== void 0);
2574
- y !== void 0 && u.forEach(([g, h]) => F(g, y, h));
2575
- }, V = (u, y, g = !1) => {
2576
- if (!O(u) || !q(u.type)) {
2577
- s("invalidStructure", y, "an expression is an object with a string `type`");
2578
- return;
2579
- }
2580
- const h = (w) => s("invalidStructure", y, w), N = (w, S) => {
2581
- u[w] !== void 0 && V(u[w], `${y}.${w}`, S);
2582
- };
2583
- switch (g && u.type === "exists" && h("EXISTS is a condition, not a value"), ge(u.fromSelect) || h("`fromSelect` is a column's id"), u.type) {
2584
- case "literal":
2585
- if (!ss(u.value))
2586
- h("a literal value is a string, number, boolean, date or null");
2587
- else if (u.empty !== void 0 && typeof u.empty != "boolean")
2588
- h("a literal's `empty` is a boolean");
2589
- else if (en(u))
2590
- s("incomplete", y, "a value not filled in");
2591
- else if (typeof u.value == "number" && !nn(u.value)) {
2592
- const w = `a number with more than ${tt} significant digits is written as another number`;
2593
- s("tooLong", `${y}.value`, w);
2594
- } else
2595
- m(u.value, Zt, `${y}.value`, "a text value");
2596
- break;
2597
- case "param":
2598
- (!q(u.name) || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(u.name)) && h("a param has a plain identifier as its `name`"), u.relative !== void 0 && !rs(u.relative) && h("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"), m(u.name, Y, `${y}.name`, "a parameter's name");
2599
- break;
2600
- case "field":
2601
- if (!ge(u.table) || !ge(u.column))
2602
- h("a field has string `table` and `column`");
2603
- else if (u.column === void 0 || u.column === "")
2604
- s("incomplete", y, "a field with no column picked");
2605
- else if (u.table === void 0 || u.table === "")
2606
- s("unqualifiedField", y, `column "${u.column}" names no table`);
2607
- else if (o.has(u.table)) {
2608
- const w = o.get(u.table);
2609
- if (!(Array.isArray(w) ? w.includes(u.column) : !w || w.columns.some((T) => T.name === u.column))) {
2610
- const T = `${u.table}.${u.column}`;
2611
- s("unknownColumn", `${y}.column`, `unknown column "${T}"`);
2612
- }
2613
- } else {
2614
- const w = l.get(u.table);
2615
- let S = `table "${u.table}" isn't in the query`;
2616
- w ? S = `table "${u.table}" is named "${w}" in the query: use that` : c != null && c.has(u.table) && (S = `table "${u.table}" is the outer query's: only the EXISTS link names it`), s("tableNotInQuery", `${y}.table`, S);
2617
- }
2618
- break;
2619
- case "function": {
2620
- if (!q(u.name) || !Array.isArray(u.args)) {
2621
- h("a function has a string `name` and an `args` array");
2622
- break;
2623
- }
2624
- !r.allowUnknownFunctions && !a[u.name.toUpperCase()] && s("unknownFunction", `${y}.name`, `function "${u.name}" isn't allowed`);
2625
- const w = a[u.name.toUpperCase()];
2626
- if (r.dialect && (w != null && w.dialects) && !w.dialects.includes(r.dialect) && s("dialectUnsupported", `${y}.name`, `${w.name} isn't in this database`), m(u.name, Y, `${y}.name`, "a function's name"), R(w, u.args.length, `${y}.args`), u.distinct !== void 0 && typeof u.distinct != "boolean" && h("a function's `distinct` is a boolean"), u.distinct === !0 && r.dialect === "mssql" && u.name.toUpperCase() === "STRING_AGG" && s("dialectUnsupported", y, "SQL Server's STRING_AGG can't join only different values"), u.args.forEach((S, T) => {
2627
- var E, C;
2628
- const A = t.length;
2629
- V(S, `${y}.args[${T}]`, !0), w && ((E = Ge(w, T)) == null ? void 0 : E.kind) === "type-name" && O(S) && m(S.value, er, `${y}.args[${T}].value`, "a type name"), w && ((C = Ge(w, T)) == null ? void 0 : C.kind) === "fixed-text" && O(S) && !(S.type === "literal" && q(S.value)) && h(`${w.name}'s ${Ge(w, T).label} is a text value`);
2630
- const M = !t.slice(A).some((P) => P.kind === "invalidStructure");
2631
- w != null && w.aggregate && M && le(S, a) && s(
2632
- "misplacedAggregate",
2633
- `${y}.args[${T}]`,
2634
- "an aggregate can't be inside another: sum up per group in a sub query first"
2635
- );
2636
- }), u.orderBy !== void 0) {
2637
- if (!Array.isArray(u.orderBy)) {
2638
- h("a function's `orderBy` is an array");
2639
- break;
2640
- }
2641
- u.name.toUpperCase() !== "STRING_AGG" && h("only STRING_AGG takes an `orderBy`"), u.orderBy.forEach((S, T) => {
2642
- const A = `${y}.orderBy[${T}]`;
2643
- if (!O(S) || S.direction !== "asc" && S.direction !== "desc") {
2644
- s("invalidStructure", A, "a sort key has an `expression` and a `direction`");
2645
- return;
2646
- }
2647
- const M = t.length;
2648
- V(S.expression, `${A}.expression`, !0), !t.slice(M).some((E) => E.kind === "invalidStructure") && (le(S.expression, a) && s("misplacedAggregate", `${A}.expression`, "an aggregate can't be inside another"), u.distinct === !0 && r.dialect === "postgres" && !Z(S.expression, u.args[0]) && s(
2649
- "dialectUnsupported",
2650
- `${A}.expression`,
2651
- "PostgreSQL orders STRING_AGG of different values by the value only"
2652
- ));
2653
- });
2654
- }
2655
- break;
2656
- }
2657
- case "binary": {
2658
- u.operator !== void 0 && !Vr.includes(u.operator) && h(`unknown operator ${JSON.stringify(u.operator)}`), u.operator === "REGEXP" && r.dialect === "mssql" && s("dialectUnsupported", y, "SQL Server has no REGEXP");
2659
- const w = t.length;
2660
- V(u.left, `${y}.left`, !0);
2661
- const S = t.slice(w).some((T) => T.kind === "incomplete");
2662
- if (Hr(u.operator))
2663
- u.right !== void 0 && h(`${String(u.operator)} takes no right side`);
2664
- else if (u.right === void 0)
2665
- s("incomplete", `${y}.right`, "a comparison with nothing to compare to");
2666
- else if (O(u.right) && u.right.type === "literal" && u.right.value === null)
2667
- s("incomplete", `${y}.right`, "compared with NULL (never true): use IS NULL");
2668
- else if (O(u.right) && u.right.type === "subquery")
2669
- u.operator === "IN" ? ee(u.right, `${y}.right`) : s("invalidStructure", `${y}.right`, "a sub query is only IN's right side");
2670
- else if (u.operator === "BETWEEN") {
2671
- const { right: T } = u, A = O(T) && T.type === "list" && Array.isArray(T.items) ? T.items : void 0;
2672
- (A == null ? void 0 : A.length) !== 2 ? s("invalidStructure", `${y}.right`, "BETWEEN takes its two bounds as a list (expr.between)") : A.forEach((M, E) => {
2673
- const C = `${y}.right.items[${E}]`;
2674
- O(M) && M.type === "literal" && M.value === null ? s("incomplete", C, "a bound of NULL (never true)") : S && en(M) || V(M, C, !0);
2675
- });
2676
- } else O(u.right) && u.right.type === "list" ? u.operator === "IN" ? ye(u.right, `${y}.right`) : s("invalidStructure", `${y}.right`, "a list is only IN's or BETWEEN's right side") : u.operator === "IN" ? s("invalidStructure", `${y}.right`, "IN takes a list (expr.list) or a sub query") : S && en(u.right) || V(u.right, `${y}.right`, !0);
2677
- t.slice(w).some((T) => T.kind === "invalidStructure") || Qt(u, y);
2678
- break;
2679
- }
2680
- case "logical":
2681
- if (u.operator !== "AND" && u.operator !== "OR" && h("a logical operator is AND or OR"), !Array.isArray(u.operands)) {
2682
- h("a logical node has an `operands` array");
2683
- break;
2684
- }
2685
- u.operands.length === 0 && s("incomplete", y, "an empty AND/OR group"), u.operands.forEach((w, S) => V(w, `${y}.operands[${S}]`));
2686
- break;
2687
- case "not": {
2688
- V(u.operand, `${y}.operand`);
2689
- const { operand: w } = u;
2690
- O(w) && w.type === "binary" && w.operator === "IN" && O(w.right) && w.right.type === "subquery" && s("notInSubquery", y, "NOT IN keeps no rows at all if the sub query gives a NULL: NOT EXISTS doesn't", "warning");
2691
- break;
2692
- }
2693
- case "if": {
2694
- ["condition", "then"].forEach((S) => {
2695
- u[S] === void 0 && s("incomplete", `${y}.${S}`, `an IF with no ${S}`);
2696
- });
2697
- const w = t.length;
2698
- N("condition", !1), N("then", !0), N("else", !0), t.slice(w).some((S) => S.kind === "invalidStructure") || Nn(
2699
- ["then", "else"].filter((S) => u[S] !== void 0).map((S) => [u[S], `${y}.${S}`])
2700
- );
2701
- break;
2702
- }
2703
- case "case": {
2704
- const w = t.length;
2705
- N("subject", !0), Array.isArray(u.branches) ? (u.branches.length === 0 && s("incomplete", y, "a CASE with no WHEN"), u.branches.forEach((T, A) => {
2706
- if (!O(T)) {
2707
- const M = `${y}.branches[${A}]`;
2708
- s("invalidStructure", M, "a branch has `when` and `then`");
2709
- return;
2710
- }
2711
- V(T.when, `${y}.branches[${A}].when`, u.subject !== void 0), V(T.then, `${y}.branches[${A}].then`, !0);
2712
- })) : h("a case node has a `branches` array");
2713
- const S = t.length;
2714
- N("else", !0), Array.isArray(u.branches) && t.slice(w).concat(t.slice(S)).every((T) => T.kind !== "invalidStructure") && Nn([
2715
- ...u.branches.map((T, A) => [T.then, `${y}.branches[${A}].then`]),
2716
- ...u.else === void 0 ? [] : [[u.else, `${y}.else`]]
2717
- ]);
2718
- break;
2719
- }
2720
- case "exists":
2721
- X(u, y);
2722
- break;
2723
- case "subquery":
2724
- h("a sub query is only IN's right side");
2725
- break;
2726
- case "list":
2727
- h("a list is only IN's right side");
2728
- break;
2729
- default:
2730
- h(`unknown expression type ${JSON.stringify(u.type)}`);
2731
- }
2732
- };
2733
- ye = (u, y) => {
2734
- Array.isArray(u.items) ? u.items.length === 0 ? s("incomplete", y, "IN with no values") : u.items.forEach((g, h) => V(g, `${y}.items[${h}]`, !0)) : s("invalidStructure", y, "a list has an `items` array");
2735
- }, ee = (u, y) => {
2736
- const { id: g, query: h } = u;
2737
- if (!q(g) || g === "" || !O(h)) {
2738
- s("invalidStructure", y, "a sub query has a non-empty string `id` and a `query`");
2739
- return;
2740
- }
2741
- d.has(g) && s("duplicateId", `${y}.id`, `the id "${g}" is used twice`), d.add(g);
2742
- const N = { inQuery: o, aliasOf: l, outerTables: c };
2743
- o = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), c = void 0;
2744
- const w = t.length;
2745
- Oe(h, `${y}.query`, !1), { inQuery: o, aliasOf: l, outerTables: c } = N;
2746
- const S = t.length === w;
2747
- (Array.isArray(h.select) ? h.select : []).length !== 1 && s("subqueryColumns", `${y}.query.select`, "a sub query after IN picks exactly one column to compare with"), S && Ue(h, `${y}.query`);
2748
- }, X = (u, y) => {
2749
- const { query: g, link: h } = u;
2750
- if (!O(g) || !Array.isArray(g.joins)) {
2751
- s("invalidStructure", `${y}.query`, "an EXISTS has a `query` with `from` and `joins`");
2752
- return;
2753
- }
2754
- const N = { inQuery: o, aliasOf: l, outerTables: c };
2755
- o = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), c = N.inQuery, [
2756
- [g.from, `${y}.query.from`],
2757
- ...g.joins.map((A, M) => [A, `${y}.query.joins[${M}]`])
2758
- ].forEach(([A, M], E) => {
2759
- const C = new Set(o.keys());
2760
- G(A, M, E > 0), E > 0 && O(A) && I(A.joinType, `${M}.joinType`), [...o.keys()].filter((P) => !C.has(P) && N.inQuery.has(P)).forEach((P) => s(
2761
- "ambiguousTable",
2762
- `${M}.table`,
2763
- `"${P}" is a table of the query around it too: give it an alias`
2764
- ));
2765
- });
2766
- const S = [
2767
- ...g.joins.map((A, M) => [
2768
- O(A) ? A.on : void 0,
2769
- `${y}.query.joins[${M}].on`
2770
- ]),
2771
- [g.where, `${y}.query.where`]
2772
- ];
2773
- S.forEach(([A, M]) => {
2774
- A !== void 0 && V(A, M);
2775
- });
2776
- const T = { inQuery: o, aliasOf: l };
2777
- o = new Map([...N.inQuery, ...T.inQuery]), l = new Map([...N.aliasOf, ...T.aliasOf]), c = void 0, V(h, `${y}.link`), { inQuery: o, aliasOf: l, outerTables: c } = N, [...S, [h, `${y}.link`]].forEach(([A, M]) => {
2778
- O(A) && le(A, a) && s("misplacedAggregate", M, "an aggregate (SUM, COUNT, …) can't be used here");
2779
- });
2780
- };
2781
- const ve = (u, y, g = []) => {
2782
- const h = new Set(g);
2783
- u.forEach((N, w) => {
2784
- !O(N) || !q(N.id) || N.id === "" ? s("invalidStructure", `${y}[${w}]`, "every entry has a non-empty string id") : h.has(N.id) ? s("duplicateId", `${y}[${w}].id`, `id "${N.id}" is used twice`) : h.add(N.id);
2785
- });
2786
- }, An = (u, y, g) => Array.isArray(u[y]) ? u[y] : (u[y] !== void 0 && s("invalidStructure", g, `\`${y}\` is an array`), []), Oe = (u, y, g) => {
2787
- const h = (E) => y ? `${y}.${E}` : E;
2788
- G(u.from, h("from"), !0);
2789
- const { from: N } = u, w = O(N) && N.query !== void 0 ? N.id : void 0;
2790
- O(N) && N.query !== void 0 && (!q(w) || w === "") && s("invalidStructure", h("from"), "a derived table has a non-empty string id");
2791
- const S = Array.isArray(u.joins) ? u.joins : [];
2792
- Array.isArray(u.joins) || s("invalidStructure", h("joins"), "`joins` is an array"), S.forEach((E, C) => G(E, h(`joins[${C}]`), !0)), ve(S, h("joins"), q(w) ? [w] : []), S.forEach((E, C) => {
2793
- if (O(E)) {
2794
- if (On.includes(E.joinType))
2795
- I(E.joinType, h(`joins[${C}].joinType`));
2796
- else {
2797
- const P = JSON.stringify(E.joinType);
2798
- s("invalidStructure", h(`joins[${C}].joinType`), `unknown join type ${P}`);
2799
- }
2800
- E.joinType !== "cross" && (E.on !== void 0 ? V(E.on, h(`joins[${C}].on`)) : s("incomplete", h(`joins[${C}].on`), "a join with no ON condition"));
2801
- }
2802
- }), u.where !== void 0 && V(u.where, h("where"));
2803
- const T = Array.isArray(u.select) ? u.select : [];
2804
- Array.isArray(u.select) || s("invalidStructure", h("select"), "`select` is an array"), ve(T, h("select")), T.forEach((E, C) => {
2805
- O(E) && (m(E.alias, Y, h(`select[${C}].alias`), "an alias"), ge(E.alias) || s("invalidStructure", h(`select[${C}].alias`), "an alias is a string"), V(E.expression, h(`select[${C}].expression`), !0));
2806
- });
2807
- const A = An(u, "groupBy", h("groupBy"));
2808
- if (ve(A, h("groupBy")), A.forEach((E, C) => {
2809
- O(E) && (ge(E.fromSelect) || s("invalidStructure", h(`groupBy[${C}].fromSelect`), "`fromSelect` is a column's id"), V(E.expression, h(`groupBy[${C}].expression`), !0));
2810
- }), u.having !== void 0 && V(u.having, h("having")), u.distinct !== void 0 && typeof u.distinct != "boolean" && s("invalidStructure", h("distinct"), "`distinct` is a boolean"), !g) {
2811
- ["orderBy", "limit", "offset", "shared"].forEach((E) => {
2812
- u[E] !== void 0 && s("invalidStructure", h(E), `a derived table has no \`${E}\``);
2813
- });
2814
- return;
2815
- }
2816
- const M = An(u, "orderBy", "orderBy");
2817
- ve(M, "orderBy"), M.forEach((E, C) => {
2818
- O(E) && (E.direction !== "asc" && E.direction !== "desc" && s("invalidStructure", `orderBy[${C}].direction`, 'a sort direction is "asc" or "desc"'), V(E.expression, `orderBy[${C}].expression`, !0));
2819
- }), ["limit", "offset"].forEach((E) => {
2820
- const C = u[E];
2821
- C !== void 0 && !(Number.isInteger(C) && C >= 0) ? s("invalidStructure", E, `\`${E}\` is a non-negative integer`) : C !== void 0 && !Number.isSafeInteger(C) && s("tooLong", E, `\`${E}\` is past ${Number.MAX_SAFE_INTEGER}, which is exact`);
2822
- });
2823
- }, _t = (u, y, g) => {
2824
- const h = `${y}.query`, { union: N } = u;
2825
- if (!Array.isArray(N) || N.length < 1 || typeof u.all != "boolean") {
2826
- s("invalidStructure", h, "a union has one or more branches in `union`, and a boolean `all`"), b(g, `${y}.alias`), o.set(g, void 0);
2827
- return;
2828
- }
2829
- let w = [];
2830
- const S = [];
2831
- let T = !0;
2832
- N.forEach((A, M) => {
2833
- const E = `${h}.union[${M}]`;
2834
- if (!O(A)) {
2835
- s("invalidStructure", E, "a union's branch is a query"), T = !1;
2836
- return;
2837
- }
2838
- const C = { inQuery: o, aliasOf: l, outerTables: c };
2839
- o = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), c = void 0;
2840
- const P = t.length;
2841
- Oe(A, E, !1);
2842
- const ae = t.length === P, B = (Array.isArray(A.select) ? A.select : []).filter(O), U = ae ? B.map((j) => j.expression.type === "literal" ? _e(j.expression) : te(j.expression)) : [];
2843
- if ({ inQuery: o, aliasOf: l, outerTables: c } = C, !ae) {
2844
- T = !1;
2845
- return;
2846
- }
2847
- Ue(A, E);
2848
- const _ = B.map((j) => K(j));
2849
- if (B.length === 0) {
2850
- s("unionColumns", `${E}.select`, "a union's branch names its columns"), T = !1;
2851
- return;
2852
- }
2853
- if (M === 0)
2854
- w = _, _.forEach((j, L) => {
2855
- if (j) return;
2856
- s("derivedColumnName", `${E}.select[${L}]`, "a union's column needs an alias: nothing outside could name it");
2857
- }), _.forEach((j, L) => {
2858
- j && _.indexOf(j) !== L && s("derivedColumnName", `${E}.select[${L}]`, `two columns named "${j}"`);
2859
- });
2860
- else if (_.length !== w.length) {
2861
- const j = `${_.length} column(s), where the first branch has ${w.length}`;
2862
- s("unionColumns", `${E}.select`, j);
2863
- return;
2864
- } else
2865
- _.forEach((j, L) => {
2866
- if (j === w[L]) return;
2867
- const J = `column ${L + 1} is "${String(w[L])}" in the first branch, not "${String(j)}"`;
2868
- s("unionColumns", `${E}.select[${L}]`, J);
2869
- });
2870
- U.forEach((j, L) => {
2871
- if (j === void 0) return;
2872
- const J = S[L];
2873
- if (J === void 0)
2874
- S[L] = j;
2875
- else if (De(J) !== De(j)) {
2876
- const re = `column "${String(w[L])}" is ${de[j]} here, ${de[J]} in a branch before`;
2877
- s("unionTypes", `${E}.select[${L}].expression`, re);
2878
- }
2879
- });
2880
- }), b(g, `${y}.alias`), o.set(g, T ? w.filter((A) => A !== void 0) : void 0);
2881
- };
2882
- k = (u, y) => {
2883
- const { query: g, alias: h } = u;
2884
- if (u.table === void 0 && O(g) && g.union !== void 0 && q(h) && h !== "") {
2885
- m(h, Y, `${y}.alias`, "an alias"), _t(g, y, h);
2886
- return;
2887
- }
2888
- if (u.table !== void 0 || !O(g) || !q(h) || h === "") {
2889
- s("invalidStructure", y, "a derived table has a `query` and an `alias`, and no `table`"), q(h) && h !== "" && (b(h, `${y}.alias`), o.set(h, void 0));
2890
- return;
2891
- }
2892
- m(h, Y, `${y}.alias`, "an alias");
2893
- const N = { inQuery: o, aliasOf: l, outerTables: c };
2894
- o = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), c = void 0;
2895
- const w = t.length;
2896
- Oe(g, `${y}.query`, !1), { inQuery: o, aliasOf: l, outerTables: c } = N;
2897
- const S = Array.isArray(g.select) ? g.select : [], T = [], A = (C, P) => {
2898
- T.includes(C) ? s("derivedColumnName", P, `two columns named "${C}"`) : T.push(C);
2899
- };
2900
- S.forEach((C, P) => {
2901
- if (!O(C) || !O(C.expression)) return;
2902
- const ae = K(C);
2903
- ae ? A(ae, `${y}.query.select[${P}]`) : s("derivedColumnName", `${y}.query.select[${P}]`, "a derived table's column needs an alias: nothing outside could name it");
2904
- });
2905
- const M = t.length === w;
2906
- M && S.length === 0 && Ne(i, g, f).forEach((C) => A(C.name, `${y}.query.select`)), b(h, `${y}.alias`), o.set(h, M || S.length > 0 ? T : void 0), M && Ue(g, `${y}.query`);
2907
- const { drillAcross: E } = u;
2908
- E !== void 0 && !(O(E) && typeof E.synced == "boolean" && Number.isInteger(E.copied) && E.copied >= 0) && s("invalidStructure", `${y}.drillAcross`, "`drillAcross` has a boolean `synced` and a non-negative integer `copied`");
2909
- };
2910
- const Ue = (u, y) => {
2911
- var M, E, C, P, ae;
2912
- const g = (B) => y ? `${y}.${B}` : B, h = pn(u);
2913
- if (h) {
2914
- const B = u.joins.findIndex((U) => (U.table ?? D(U)) === h.table);
2915
- s(
2916
- "joinOrder",
2917
- g(`joins[${B}].on`),
2918
- `the join condition of "${h.table}" uses "${h.needs}", which is joined after it`
2919
- );
2920
- }
2921
- const N = (B, U) => {
2922
- le(B, a) && s("misplacedAggregate", U, "an aggregate (SUM, COUNT, …) can't be used here");
2923
- };
2924
- N(u.where, g("where")), u.joins.forEach((B, U) => {
2925
- B.joinType !== "cross" && N(B.on, g(`joins[${U}].on`));
2926
- }), (M = u.groupBy) == null || M.forEach((B, U) => N(B.expression, g(`groupBy[${U}].expression`)));
2927
- const w = Kn(u, a), S = "isn't a group key or an aggregate (SUM, COUNT, …)";
2928
- if (w.selectAll && s("notGrouped", g("select"), "a grouped query has to pick its columns, not *"), u.select.forEach((B, U) => {
2929
- w.select.includes(B.id) && s("notGrouped", g(`select[${U}].expression`), `this column ${S}`);
2930
- }), (E = u.orderBy) == null || E.forEach((B, U) => {
2931
- w.orderBy.includes(B.id) && s("notGrouped", `orderBy[${U}].expression`, `this sort key ${S}`);
2932
- }), w.having && s("notGrouped", g("having"), `a column in this condition ${S}`), r.dialect === "mssql") {
2933
- const B = [], U = (L, J) => {
2934
- const [re, je] = L.length <= J.length ? [L, J] : [J, L];
2935
- return re.every((Cn, In) => Cn.direction === je[In].direction && Z(Cn.expression, je[In].expression));
2936
- }, _ = (L) => {
2937
- var re;
2938
- return [...L.type === "function" && ((re = L.orderBy) != null && re.length) ? [L.orderBy] : [], ...fe(L).flatMap(_)];
2939
- }, j = (L, J) => {
2940
- _(L).forEach((re) => {
2941
- B.some((je) => !U(je, re)) && s(
2942
- "dialectUnsupported",
2943
- J,
2944
- "SQL Server sorts every STRING_AGG of a query alike: this one's order differs"
2945
- ), B.push(re);
2946
- });
2947
- };
2948
- u.select.forEach((L, J) => j(L.expression, g(`select[${J}].expression`))), u.having && j(u.having, g("having")), (C = u.orderBy) == null || C.forEach((L, J) => j(L.expression, `orderBy[${J}].expression`));
2949
- }
2950
- if (r.allowUnknownFunctions && Mn(u, a)) {
2951
- const B = (U, _) => {
2952
- Kt(U, a) && s(
2953
- "unknownAggregate",
2954
- _,
2955
- "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)",
2956
- "warning"
2957
- );
2958
- };
2959
- u.select.forEach((U, _) => B(U.expression, g(`select[${_}].expression`))), (P = u.orderBy) == null || P.forEach((U, _) => B(U.expression, `orderBy[${_}].expression`)), B(u.having, g("having"));
2960
- }
2961
- u.joins.forEach((B, U) => {
2962
- if (B.joinType === "cross" || !B.on) return;
2963
- const _ = ne(B.on), j = D(B), L = Q(u).slice(0, U + 1).map(D);
2964
- _.some((J) => J !== j && !L.includes(J)) || _.includes(j) && _.some((J) => L.includes(J)) || s(
2965
- "unlinkedJoin",
2966
- g(`joins[${U}].on`),
2967
- `the join condition of "${j}" doesn't compare it with a table joined before it: every row meets every row it lets through`,
2968
- "warning"
2969
- );
2970
- }), u.joins.forEach((B, U) => {
2971
- var j;
2972
- if (!B.query || !((j = B.drillAcross) != null && j.synced)) return;
2973
- Nr(i, u, B) || s(
2974
- "drillAcrossOutOfStep",
2975
- g(`joins[${U}]`),
2976
- `"${B.alias}" is kept in step with the query but doesn't match its grouping`
2977
- );
2978
- const _ = H(B.query) ? void 0 : B.query.from.table;
2979
- _ !== void 0 && Sr(i, u, _) && s(
2980
- "drillAcrossFilterMixed",
2981
- g(`joins[${U}]`),
2982
- `a condition of the query names both what "${B.alias}" shares and what it doesn't: it isn't applied to it`,
2983
- "warning"
2984
- );
2985
- }), u.joins.forEach((B, U) => {
2986
- B.joinType !== "cross" || B.query && lt(B.query, a) || s(
2987
- "crossJoin",
2988
- g(`joins[${U}]`),
2989
- `every row of "${D(B)}" meets every row of the query: they multiply`,
2990
- "warning"
2991
- );
2992
- });
2993
- const T = _r(u, i), A = (B) => s(
2994
- "fanOut",
2995
- B,
2996
- `${T.tables.map((U) => `"${U}"`).join(", ")} rows repeat in this join: a sum, average or count of their columns comes out too high`,
2997
- "warning"
2998
- );
2999
- u.select.forEach((B, U) => {
3000
- T.select.includes(B.id) && A(g(`select[${U}].expression`));
3001
- }), T.having && A(g("having")), (ae = u.orderBy) == null || ae.forEach((B, U) => {
3002
- T.orderBy.includes(B.id) && A(`orderBy[${U}].expression`);
3003
- });
3004
- };
3005
- n.shared !== void 0 && !Array.isArray(n.shared) && s("invalidStructure", "shared", "`shared` is an array"), ve(f, "shared");
3006
- const kn = /* @__PURE__ */ new Set();
3007
- if (f.forEach((u, y) => {
3008
- if (!O(u)) return;
3009
- const g = `shared[${y}]`, { name: h } = u;
3010
- !q(h) || h === "" ? s("invalidStructure", `${g}.name`, "a shared query has a non-empty string `name`") : (m(h, Y, `${g}.name`, "a name"), kn.has(h) && s("duplicateTableName", `${g}.name`, `two shared queries named "${h}"`), kn.add(h));
3011
- const N = q(h) && h !== "" ? h : g, w = { inQuery: o, aliasOf: l, outerTables: c };
3012
- o = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), c = void 0, k({ query: u.query, alias: N }, g);
3013
- const S = o.get(N);
3014
- ({ inQuery: o, aliasOf: l, outerTables: c } = w), q(u.id) && v.set(u.id, Array.isArray(S) ? S : void 0);
3015
- }), Oe(n, "", !0), t.length === 0) {
3016
- const u = n;
3017
- if (Ue(u, ""), r.requireLimit) {
3018
- const { max: g } = r.requireLimit === !0 ? {} : r.requireLimit, h = Mn(u, a) && !((xn = u.groupBy) != null && xn.length);
3019
- u.limit === void 0 && !h ? s("noLimit", "limit", "no LIMIT: the query reads every row", "warning") : g !== void 0 && u.limit !== void 0 && u.limit > g && s("limitTooHigh", "limit", `LIMIT ${u.limit} is above ${g}`, "warning");
3020
- }
3021
- Yr(u, i).forEach((g) => {
3022
- s("paramConflict", "", `param "${g}" is compared against columns of different types`);
3023
- }), Kr(u).forEach((g) => {
3024
- s("paramConflict", "", `param "${g}" stands for two different relative dates`);
3025
- });
3026
- const y = Xr(u);
3027
- (Bn = u.orderBy) == null || Bn.forEach((g, h) => {
3028
- y.includes(g.id) && s(
3029
- "distinctSort",
3030
- `orderBy[${h}].expression`,
3031
- "with DISTINCT, a sort key has to be one of the selected columns"
3032
- );
3033
- });
3034
- }
3035
- t.some((u) => u.kind === "invalidStructure") || Zr(e, n).forEach((u) => s(
3036
- "joinOnlyColumn",
3037
- u.map((y, g) => typeof y == "number" ? `[${y}]` : `${g ? "." : ""}${y}`).join(""),
3038
- "a column for joining tables only, used outside a join's condition"
3039
- )), f.forEach((u, y) => {
3040
- !O(u) || !q(u.id) || $.has(u.id) || s("unusedShared", `shared[${y}]`, "a shared query used nowhere", "warning");
3041
- });
3042
- const Ft = r.hideWarnings ?? [];
3043
- return t.filter((u) => u.severity === "error" || !Ft.includes(u.kind));
3044
- }
3045
- function oi(e, n = {
3046
- relativeDate: ft
3047
- }) {
3048
- return n.relativeDate(e);
3049
- }
3050
- function ai({ unit: e, offset: n, anchor: r }) {
3051
- if (e === "day" && n === 0) return "today";
3052
- const t = n < 0 ? `minus_${-n}` : `plus_${n}`;
3053
- return [e, n === 0 ? "0" : t, r].filter(Boolean).join("_");
3054
- }
3055
- const is = {
3056
- from: "from",
3057
- joins: "from",
3058
- where: "where",
3059
- groupBy: "group",
3060
- having: "having",
3061
- select: "select",
3062
- distinct: "select",
3063
- orderBy: "order",
3064
- limit: "order",
3065
- offset: "order"
3066
- };
3067
- function li(e, n, r = {}) {
3068
- const { schema: t, functions: s } = r, i = (d, f) => typeof f == "number" ? d == null ? void 0 : d[f] : void 0, a = (d) => {
3069
- var f;
3070
- return d.alias || t && d.table !== void 0 && ((f = z(t, d.table)) == null ? void 0 : f.label) || d.table || "";
3071
- }, o = (d, f) => {
3072
- var k;
3073
- if (!d || f.length === 0) return [];
3074
- const [p, v, $] = f;
3075
- switch (d.type) {
3076
- case "logical": {
3077
- const b = i(d.operands, v);
3078
- return b ? [{ kind: "condition", number: v + 1 }, ...o(b, f.slice(2))] : [];
3079
- }
3080
- case "not":
3081
- return [{ kind: "not" }, ...o(d.operand, f.slice(1))];
3082
- case "binary": {
3083
- if (p !== "left" && p !== "right") return [];
3084
- const b = { kind: "side", side: p }, I = d[p];
3085
- return (I == null ? void 0 : I.type) === "subquery" && v === "query" ? [b, { kind: "inSubQuery" }, ...m(I.query, f.slice(2))] : (I == null ? void 0 : I.type) === "list" && v === "items" && i(I.items, $) ? [b, { kind: "listItem", number: $ + 1 }] : [b, ...o(I, f.slice(1))];
3086
- }
3087
- case "function": {
3088
- const b = { kind: "function", name: d.name };
3089
- if (p === "args" && i(d.args, v)) {
3090
- const G = Zn(d.name, s), R = G && ((k = Ge(G, v)) == null ? void 0 : k.label);
3091
- return [
3092
- b,
3093
- { kind: "argument", number: v + 1, ...R && { label: R } },
3094
- ...o(d.args[v], f.slice(2))
3095
- ];
3096
- }
3097
- const I = p === "orderBy" ? i(d.orderBy, v) : void 0;
3098
- return I ? [
3099
- b,
3100
- { kind: "sortKey", number: v + 1 },
3101
- ...o(I.expression, f.slice(3))
3102
- ] : [b];
3103
- }
3104
- case "if":
3105
- return p === "condition" || p === "then" || p === "else" ? [{ kind: "if", part: p }, ...o(d[p], f.slice(1))] : [];
3106
- case "case": {
3107
- if (p === "subject" || p === "else")
3108
- return [{ kind: "case", part: p }, ...o(d[p], f.slice(1))];
3109
- const b = p === "branches" ? i(d.branches, v) : void 0;
3110
- return !b || $ !== "when" && $ !== "then" ? [] : [
3111
- { kind: "case", part: $, branch: v + 1 },
3112
- ...o(b[$], f.slice(3))
3113
- ];
3114
- }
3115
- case "exists": {
3116
- const b = { kind: "exists", table: a(d.query.from) };
3117
- return p === "link" ? [b, { kind: "existsLink" }] : p === "query" ? [b, ...m(d.query, f.slice(1))] : [b];
3118
- }
3119
- default:
3120
- return [];
3121
- }
3122
- }, l = (d, f) => {
3123
- if (d.query && f[0] === "query") return c(d.alias, d.query, f.slice(1));
3124
- const p = d.query ? { kind: "subQuery", name: d.alias } : { kind: "table", name: a(d) };
3125
- return f[0] === "on" ? [p, { kind: "joinCondition" }, ...o(d.on, f.slice(1))] : [p];
3126
- };
3127
- function c(d, f, p, v = "subQuery") {
3128
- const $ = { kind: v, name: d };
3129
- if (!H(f)) return [$, ...m(f, p)];
3130
- const k = p[0] === "union" ? i(be(f), p[1]) : void 0;
3131
- if (!k) return [$];
3132
- const b = p[1] + 1;
3133
- return [$, { kind: "unionQuery", number: b }, ...m(k, p.slice(2))];
3134
- }
3135
- function m(d, f) {
3136
- var G, R;
3137
- const [p, v, $] = f, k = is[String(p)];
3138
- if (!k) return [];
3139
- const b = { kind: "section", section: k }, I = f.slice(3);
3140
- switch (p) {
3141
- // A sub query is a place of its own: no "From Tables" before it.
3142
- case "from":
3143
- return d.from.query ? v === "query" ? c(d.from.alias, d.from.query, f.slice(2)) : [{ kind: "subQuery", name: d.from.alias }] : [b, { kind: "table", name: a(d.from) }];
3144
- case "joins": {
3145
- const X = i(d.joins, v);
3146
- return X ? X.query ? l(X, f.slice(2)) : [b, ...l(X, f.slice(2))] : [b];
3147
- }
3148
- case "where":
3149
- case "having":
3150
- return [b, ...o(d[p], f.slice(1))];
3151
- case "select": {
3152
- const X = i(d.select, v);
3153
- if (!X) return [b];
3154
- const { expression: ee, alias: ye } = X, he = ee.type === "field" && t && ee.table !== void 0 ? (R = (G = z(t, ee.table)) == null ? void 0 : G.columns.find((x) => x.name === ee.column)) == null ? void 0 : R.label : void 0, te = ye || he;
3155
- return [
3156
- b,
3157
- { kind: "column", number: v + 1, ...te && { name: te } },
3158
- ...$ === "expression" ? o(ee, I) : []
3159
- ];
3160
- }
3161
- case "groupBy":
3162
- case "orderBy": {
3163
- const X = i(d[p], v);
3164
- return X ? [
3165
- b,
3166
- { kind: p === "groupBy" ? "groupKey" : "sortKey", number: v + 1 },
3167
- ...$ === "expression" ? o(X.expression, I) : []
3168
- ] : [b];
3169
- }
3170
- default:
3171
- return [b];
3172
- }
3173
- }
3174
- if (n[0] === "shared") {
3175
- const d = i(e.shared, n[1]);
3176
- return d ? n[2] === "query" ? c(d.name, d.query, n.slice(3), "sharedQuery") : [{ kind: "sharedQuery", name: d.name }] : [];
3177
- }
3178
- return m(e, n);
3179
- }
3180
- export {
3181
- Hr as $,
3182
- As as A,
3183
- Rr as B,
3184
- Qr as C,
3185
- ar as D,
3186
- un as E,
3187
- Ys as F,
3188
- ei as G,
3189
- oi as H,
3190
- si as I,
3191
- ii as J,
3192
- li as K,
3193
- ls as L,
3194
- tt as M,
3195
- sr as N,
3196
- it as O,
3197
- hs as P,
3198
- ri as Q,
3199
- ps as R,
3200
- $r as S,
3201
- bs as T,
3202
- gs as U,
3203
- cs as V,
3204
- $n as W,
3205
- Nt as X,
3206
- Ds as Y,
3207
- js as Z,
3208
- Gs as _,
3209
- Zt as a,
3210
- Vr as a0,
3211
- Rs as a1,
3212
- ti as a2,
3213
- Ls as a3,
3214
- Mr as a4,
3215
- Jr as a5,
3216
- _e as a6,
3217
- nr as a7,
3218
- vn as a8,
3219
- ai as a9,
3220
- $s as aA,
3221
- tr as aB,
3222
- rt as aC,
3223
- ne as aD,
3224
- Ae as aE,
3225
- Xe as aF,
3226
- Ce as aG,
3227
- tn as aH,
3228
- ni as aI,
3229
- zs as aJ,
3230
- ct as aa,
3231
- fs as ab,
3232
- vs as ac,
3233
- Es as ad,
3234
- lt as ae,
3235
- Ss as af,
3236
- es as ag,
3237
- Xr as ah,
3238
- at as ai,
3239
- Zs as aj,
3240
- us as ak,
3241
- Ns as al,
3242
- mn as am,
3243
- pr as an,
3244
- ms as ao,
3245
- hr as ap,
3246
- mr as aq,
3247
- He as ar,
3248
- Ts as as,
3249
- Fn as at,
3250
- dt as au,
3251
- Fr as av,
3252
- _r as aw,
3253
- oe as ax,
3254
- ds as ay,
3255
- ws as az,
3256
- er as b,
3257
- ys as c,
3258
- Us as d,
3259
- Vs as e,
3260
- Ws as f,
3261
- Qs as g,
3262
- Js as h,
3263
- Xs as i,
3264
- Dr as j,
3265
- Ar as k,
3266
- Ps as l,
3267
- $t as m,
3268
- _s as n,
3269
- qs as o,
3270
- wr as p,
3271
- xs as q,
3272
- Fs as r,
3273
- Hs as s,
3274
- Cs as t,
3275
- Ks as u,
3276
- Is as v,
3277
- Os as w,
3278
- Ms as x,
3279
- Bs as y,
3280
- ks as z
3281
- };