@nongt/visql 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.
Files changed (46) hide show
  1. package/README.md +23 -359
  2. package/dist/{MuiTimePicker-BjywwrRm.js → MuiTimePicker-DRqT6ByZ.js} +1 -1
  3. package/dist/PipelineEditor-C10lng6j.js +10544 -0
  4. package/dist/core.js +336 -78
  5. package/dist/explain.js +165 -0
  6. package/dist/fixtures.js +1 -1
  7. package/dist/index.js +114 -98
  8. package/dist/issueLocation-BOSdd1JX.js +1106 -0
  9. package/dist/mui-date-pickers-host.js +1 -1
  10. package/dist/mui-date-pickers.js +1 -1
  11. package/dist/mui.js +95 -84
  12. package/dist/params-MMOdKWnW.js +2217 -0
  13. package/dist/{schema-DFC26AhZ.js → schema-dP_ISylQ.js} +270 -242
  14. package/dist/sql-import.js +613 -627
  15. package/dist/sqlGen-B7-2-i9V.js +903 -0
  16. package/dist/style.css +1 -1
  17. package/dist/tokens-DV5rTGMj.js +171 -0
  18. package/dist/types/core/ast.d.ts +1 -1
  19. package/dist/types/core/components/flow/NodeActionFrame.d.ts +20 -0
  20. package/dist/types/core/components/flow/useNodeActions.d.ts +18 -0
  21. package/dist/types/core/i18n/defaultMessages.d.ts +15 -0
  22. package/dist/types/core/i18n/messages.d.ts +11 -0
  23. package/dist/types/core/params.d.ts +10 -0
  24. package/dist/types/core/planFindings.d.ts +27 -0
  25. package/dist/types/core/queryHelpers.d.ts +1 -1
  26. package/dist/types/core/schema.d.ts +35 -20
  27. package/dist/types/core/scopeQuery.d.ts +2 -2
  28. package/dist/types/core/sqlGen.d.ts +10 -0
  29. package/dist/types/core/theme/appearance.d.ts +27 -0
  30. package/dist/types/core/theme/looks.d.ts +14 -0
  31. package/dist/types/core/theme/tokens.d.ts +9 -1
  32. package/dist/types/core-api.d.ts +3 -2
  33. package/dist/types/explain/explainQuery.d.ts +53 -0
  34. package/dist/types/explain/postgresPlan.d.ts +12 -0
  35. package/dist/types/explain.d.ts +2 -0
  36. package/dist/types/features/queryEditor/CanvasBackground.d.ts +2 -0
  37. package/dist/types/features/queryEditor/ExplainButton.d.ts +13 -0
  38. package/dist/types/features/queryEditor/IssuesButton.d.ts +14 -6
  39. package/dist/types/features/queryEditor/PipelineEditor.d.ts +15 -0
  40. package/dist/types/features/queryEditor/planText.d.ts +8 -0
  41. package/dist/types/index.d.ts +2 -0
  42. package/package.json +14 -1
  43. package/dist/PipelineEditor-9-9xOJcB.js +0 -10214
  44. package/dist/core-api-BsEMnDQ1.js +0 -1141
  45. package/dist/issueLocation-732-e0B8.js +0 -3281
  46. package/dist/tokens-BTaVMSOx.js +0 -95
package/dist/core.js CHANGED
@@ -1,80 +1,338 @@
1
- import { D as e, E as r, M as o, b as n, f as i, a as d, h as t, i as u, v as l } from "./schema-DFC26AhZ.js";
2
- import { M as m, a as E, b as T, Q as y, I as c, S as h, d as p, p as Q, e as _, f as U, g as b, c as A, h as M, K as N, B as D, q as I, k as B, t as f, v, m as L, G as C, H as R, w as F, r as G, x as q, i as x, C as H, E as P, F as g, y as k, s as O, z as X, A as Y, j, o as J, l as w, n as K, u as z, J as W } from "./issueLocation-732-e0B8.js";
3
- import { c as Z, f as $, i as aa } from "./calendarDate-CYlr9TvX.js";
4
- import { D as ea, q as ra, Q as oa, n as na, S as ia, c as da, d as ta, e as ua, f as la, g as Sa, a as ma, b as Ea, h as Ta, o as ya, r as ca, i as ha, p as pa, s as Qa, j as _a, k as Ua, l as ba, m as Aa, u as Ma } from "./core-api-BsEMnDQ1.js";
1
+ var N = Object.defineProperty;
2
+ var I = (e, t, r) => t in e ? N(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r;
3
+ var g = (e, t, r) => I(e, typeof t != "symbol" ? t + "" : t, r);
4
+ import { n as v, q as A, t as B, h as O } from "./schema-dP_ISylQ.js";
5
+ import { D as le, E as pe, M as ce, b as ye, f as de, c as fe, i as me, v as he } from "./schema-dP_ISylQ.js";
6
+ import { au as D, v as L, av as Q, F as M, $ as U, t as y, al as _, aw as i, ah as j } from "./params-MMOdKWnW.js";
7
+ import { M as Se, a as we, b as Ee, d as ge, e as ve, f as Te, g as Ne, c as Ie, h as Ae, k as Be, m as Oe, q as De, i as Le, j as Qe, s as Me, l as Ue, p as _e, n as je, o as qe, u as xe } from "./params-MMOdKWnW.js";
8
+ import { c as Re, f as $e, i as ke } from "./calendarDate-CYlr9TvX.js";
9
+ import { Q as Fe, l as Je, S as Pe, a as He, n as Xe, f as Ye, j as We, m as Ke, b as Ve, k as ze, r as Ze, c as et, g as tt, h as rt, i as at, s as nt, d as st, e as it, v as ot } from "./issueLocation-BOSdd1JX.js";
10
+ import { D as lt, c as pt, S as ct, a as yt, b as dt, s as ft, u as mt } from "./sqlGen-B7-2-i9V.js";
11
+ const q = (e) => typeof e == "object" && e !== null && !(e instanceof Date), T = {
12
+ /** A column: `expr.field('orders', 'status')`. */
13
+ field: (e, t) => ({ type: "field", table: e, column: t }),
14
+ /** A literal value, written into the SQL (as a bound parameter by
15
+ * astToParameterizedSql). `''` is marked as the empty text (see
16
+ * LiteralNode's `empty`), since code means it. */
17
+ value: (e) => e === "" ? { type: "literal", value: e, empty: !0 } : { type: "literal", value: e },
18
+ /** A named value the application supplies when generating the SQL
19
+ * (astToParameterizedSql's `values`). With `relative`, a date relative
20
+ * to when the query runs, which the application computes (issue 140):
21
+ * `expr.param('sale_from', { relative: { unit: 'day', offset: -30 } })`. */
22
+ param: (e, t = {}) => t.relative ? { type: "param", name: e, relative: t.relative } : { type: "param", name: e },
23
+ /** `left <operator> right`. */
24
+ compare: (e, t, r) => ({
25
+ type: "binary",
26
+ operator: t,
27
+ left: e,
28
+ right: r
29
+ }),
30
+ /** `operand IS NULL`. */
31
+ isNull: (e) => ({
32
+ type: "binary",
33
+ operator: "IS NULL",
34
+ left: e
35
+ }),
36
+ /** `operand IS NOT NULL`. */
37
+ isNotNull: (e) => ({
38
+ type: "binary",
39
+ operator: "IS NOT NULL",
40
+ left: e
41
+ }),
42
+ /** `left = right`. */
43
+ eq: (e, t) => ({
44
+ type: "binary",
45
+ operator: "=",
46
+ left: e,
47
+ right: t
48
+ }),
49
+ and: (...e) => ({
50
+ type: "logical",
51
+ operator: "AND",
52
+ operands: e
53
+ }),
54
+ or: (...e) => ({
55
+ type: "logical",
56
+ operator: "OR",
57
+ operands: e
58
+ }),
59
+ not: (e) => ({ type: "not", operand: e }),
60
+ /** A function call: `expr.fn('LOWER', expr.field('users', 'email'))`. */
61
+ fn: (e, ...t) => ({
62
+ type: "function",
63
+ name: e,
64
+ args: t
65
+ }),
66
+ /** Whether the outer row has related rows: `EXISTS (SELECT 1 FROM …
67
+ * WHERE <link> AND <where>)`. `link` matches them to the outer row;
68
+ * `where` names the subquery's own tables only. NOT EXISTS:
69
+ * `expr.not(expr.exists(…))`. */
70
+ exists: (e, t) => ({ type: "exists", query: { joins: [], ...e }, link: t }),
71
+ /** `left IN (…)`: the values (`[1, 2, 3]`, or a list of expressions
72
+ * such as params: `expr.list(…)`), or a sub query (`expr.subquery`).
73
+ * NOT IN: `expr.not(expr.in(…))`. */
74
+ in: (e, t) => ({
75
+ type: "binary",
76
+ operator: "IN",
77
+ left: e,
78
+ right: Array.isArray(t) ? T.list(...t) : t
79
+ }),
80
+ /** `left BETWEEN low AND high` (issue 169), both bounds included: each a
81
+ * value or an expression (a param, a relative date). NOT BETWEEN:
82
+ * `expr.not(expr.between(…))`. */
83
+ between: (e, t, r) => ({
84
+ type: "binary",
85
+ operator: "BETWEEN",
86
+ left: e,
87
+ right: T.list(t, r)
88
+ }),
89
+ /** IN's values: each a value (`expr.list(1, 2)`) or an expression
90
+ * (`expr.list(expr.param('a'), expr.param('b'))`). */
91
+ list: (...e) => ({
92
+ type: "list",
93
+ items: e.map((t) => q(t) ? t : { type: "literal", value: t })
94
+ }),
95
+ /** A query of its own for IN to compare with, selecting `select` — one
96
+ * column. Its tables are its own: it sees nothing of the query around
97
+ * it. `expr.in(expr.field('customer', 'id'), expr.subquery({ from: {
98
+ * table: 'sale_transaction' }, select: expr.field('sale_transaction',
99
+ * 'customer_id') }))`. */
100
+ subquery: ({ select: e, ...t }) => ({
101
+ type: "subquery",
102
+ id: v(),
103
+ query: { joins: [], ...t, select: [{ id: v(), expression: e }] }
104
+ })
105
+ };
106
+ function W(e, t, r) {
107
+ return i(e, t, { type: "setBaseTable", table: r });
108
+ }
109
+ function K(e, t, r, a = {}) {
110
+ const n = { type: "addJoin", table: r, ...a };
111
+ return i(e, t, n);
112
+ }
113
+ function V(e, t, r) {
114
+ return i(e, t, { type: "removeJoin", joinId: r });
115
+ }
116
+ function x(e, t, r, a = {}) {
117
+ const n = D(t), s = L(r);
118
+ if (n && s.some((l) => l !== n.alias)) {
119
+ if (s.includes(n.alias))
120
+ throw new Error("addCondition: a condition names both the union and tables of its branches: add it in two parts");
121
+ return n.query.union.forEach((l) => {
122
+ const m = l.from.table, h = new Set(A(l).map(B)), b = Q(e, m), w = s.find((E) => !h.has(E) && !b.has(E));
123
+ if (w)
124
+ throw new Error(`addCondition: "${w}" can't be reached from "${m}", one of the union's tables: a condition must reach every branch`);
125
+ }), n.query.union.reduce((l, m, h) => M(
126
+ l,
127
+ [U(n.id, h)],
128
+ (b) => x(e, b, r, a)
129
+ ), t);
130
+ }
131
+ const u = a.operator ?? "AND", { where: o } = t;
132
+ let d;
133
+ return o ? o.type === "logical" && o.operator === u ? d = { ...o, operands: [...o.operands, r] } : d = { type: "logical", operator: u, operands: [o, r] } : d = r, y(e, t, _(e, t, d));
134
+ }
135
+ function z(e, t, r, a) {
136
+ const n = i(e, t, { type: "addSelectItem" }), s = n.select[n.select.length - 1].id, u = i(e, n, {
137
+ type: "setSelectExpression",
138
+ selectId: s,
139
+ expression: r
140
+ }), o = a === void 0 ? u : i(e, u, { type: "setSelectAlias", selectId: s, alias: a });
141
+ return y(e, t, o);
142
+ }
143
+ function Z(e, t, r) {
144
+ const a = i(e, t, { type: "addGroupByItem" }), { id: n } = a.groupBy[a.groupBy.length - 1], s = i(e, a, {
145
+ type: "setGroupByExpression",
146
+ groupById: n,
147
+ expression: r
148
+ });
149
+ return y(e, t, s);
150
+ }
151
+ function ee(e, t, r) {
152
+ return y(e, t, j(e, t, r));
153
+ }
154
+ function te(e, t, r, a = "asc") {
155
+ const n = i(e, t, { type: "addOrderByItem" }), { id: s } = n.orderBy[n.orderBy.length - 1], u = i(e, n, {
156
+ type: "setOrderByExpression",
157
+ orderById: s,
158
+ expression: r
159
+ }), o = i(e, u, {
160
+ type: "setOrderByDirection",
161
+ orderById: s,
162
+ direction: a
163
+ });
164
+ return y(e, t, o);
165
+ }
166
+ function re(e, t, r) {
167
+ let a = t;
168
+ return "limit" in r && (a = i(e, a, { type: "setLimit", limit: r.limit })), "offset" in r && (a = i(e, a, { type: "setOffset", offset: r.offset })), a;
169
+ }
170
+ function ae(e, t, r) {
171
+ return i(e, t, { type: "setDistinct", distinct: r });
172
+ }
173
+ function ne(e) {
174
+ if (!O(e)) throw new Error(`query "${e.id}" has no base table yet`);
175
+ return e;
176
+ }
177
+ const S = 4;
178
+ class p extends Error {
179
+ constructor(r, a) {
180
+ super(a);
181
+ g(this, "kind");
182
+ this.name = "QueryFormatError", this.kind = r;
183
+ }
184
+ }
185
+ const c = (e) => typeof e == "object" && e !== null && !Array.isArray(e);
186
+ function C(e) {
187
+ const t = [];
188
+ let r = 0;
189
+ for (; r < e.length; ) {
190
+ for (; e[r] === " "; ) r += 1;
191
+ if (e[r] === "'") {
192
+ let a = "";
193
+ for (r += 1; r < e.length && !(e[r] === "'" && e[r + 1] !== "'"); )
194
+ a += e[r], r += e[r] === "'" ? 2 : 1;
195
+ t.push(a);
196
+ const n = e.indexOf(",", r);
197
+ r = n === -1 ? e.length : n + 1;
198
+ } else {
199
+ const a = e.indexOf(",", r), n = e.slice(r, a === -1 ? void 0 : a).trim();
200
+ n !== "" && t.push(/^-?\d+(\.\d+)?$/.test(n) ? Number(n) : n), r = a === -1 ? e.length : a + 1;
201
+ }
202
+ }
203
+ return t;
204
+ }
205
+ function R(e) {
206
+ const t = (r) => {
207
+ if (Array.isArray(r)) return r.map(t);
208
+ if (!c(r)) return r;
209
+ const a = Object.fromEntries(Object.entries(r).map(([u, o]) => [u, t(o)])), { right: n } = a;
210
+ if (a.type !== "binary" || a.operator !== "IN" || !c(n) || n.type === "subquery" || n.type === "list") return a;
211
+ const s = n.type === "literal" && typeof n.value == "string" ? C(n.value).map((u) => ({ type: "literal", value: u })) : [n];
212
+ return { ...a, right: { type: "list", items: s } };
213
+ };
214
+ return t(e);
215
+ }
216
+ const $ = (e) => e, k = (e) => e, G = [R, $, k];
217
+ function F(e, t, r) {
218
+ return r.slice(t - 1).reduce((a, n) => n(a), e);
219
+ }
220
+ function f(e, t) {
221
+ return Array.isArray(e) ? e.map((r) => f(r, t)) : c(e) ? e.type === "literal" ? t(e) : Object.fromEntries(Object.entries(e).map(([r, a]) => [r, f(a, t)])) : e;
222
+ }
223
+ function J(e) {
224
+ return e.value instanceof Date ? { ...e, value: e.value.toISOString(), valueType: "date" } : typeof e.value == "bigint" ? { ...e, value: String(e.value), valueType: "bigint" } : e;
225
+ }
226
+ function P(e) {
227
+ if (e.valueType === void 0) return e;
228
+ const { valueType: t, ...r } = e, a = String(r.value);
229
+ let n;
230
+ if (t === "date") {
231
+ if (n = new Date(a), Number.isNaN(n.getTime()))
232
+ throw new p("invalid", `not a date: ${JSON.stringify(a)}`);
233
+ } else if (t === "bigint" && /^-?\d+$/.test(a))
234
+ n = BigInt(a);
235
+ else {
236
+ const s = String(t);
237
+ throw new p("invalid", `can't read a ${s} from ${JSON.stringify(a)}`);
238
+ }
239
+ return { ...r, value: n };
240
+ }
241
+ function se(e) {
242
+ return {
243
+ version: S,
244
+ query: f(e, J)
245
+ };
246
+ }
247
+ function ie(e) {
248
+ if (!c(e))
249
+ throw new p("invalid", "a stored query is an object");
250
+ const { version: t } = e;
251
+ if (typeof t != "number" || !Number.isInteger(t) || t < 1)
252
+ throw new p("invalid", "a stored query has a whole-number version from 1");
253
+ if (t > S)
254
+ throw new p(
255
+ "newerVersion",
256
+ `stored in format ${t}; this version reads up to ${S}`
257
+ );
258
+ const r = F(e.query, t, G);
259
+ if (!c(r) || typeof r.id != "string")
260
+ throw new p("invalid", "a stored query has a query with a string id");
261
+ return f(r, P);
262
+ }
5
263
  export {
6
- e as DEFAULT_FUNCTIONS,
7
- ea as DIALECTS,
8
- ra as DIALECT_LABELS,
9
- r as EMPTY_SCHEMA,
10
- o as MAX_NAME_LENGTH,
11
- m as MAX_NUMBER_DIGITS,
12
- E as MAX_TEXT_LENGTH,
13
- T as MAX_TYPE_NAME_LENGTH,
14
- oa as QUERY_FORMAT_VERSION,
15
- y as QUERY_ISSUE_KINDS,
16
- c as QUERY_WARNING_KINDS,
17
- na as QueryFormatError,
18
- ia as ScopeError,
19
- h as SharedBaseError,
20
- da as addCondition,
21
- ta as addGroupBy,
22
- ua as addJoin,
23
- p as addMeasure,
24
- la as addOrderBy,
25
- Sa as addSelectItem,
26
- Q as addSharedQuery,
27
- _ as addUnionBranch,
28
- U as addUnionJoin,
29
- b as addUnionTable,
30
- ma as astToParameterizedSql,
31
- Ea as astToSql,
32
- n as branchesOf,
33
- Z as calendarDay,
34
- A as createEmptyQuery,
35
- M as createUnion,
36
- Ta as expr,
37
- i as filterSchema,
38
- $ as fromIsoDay,
39
- d as functionsForDialect,
40
- t as hasBaseTable,
41
- u as isUnion,
42
- aa as isoDay,
43
- N as issueLocation,
44
- D as joinMultiplicity,
45
- I as joinSharedQuery,
46
- B as keepMeasuresInStep,
47
- ya as loadQuery,
48
- f as makeShared,
49
- v as makeSubQuery,
50
- L as measureFacts,
51
- C as queryParams,
52
- R as relativeDateLabel,
53
- ca as removeJoin,
54
- F as removeSharedQuery,
55
- G as removeUnionTable,
56
- q as renameSharedQuery,
57
- x as renameUnionColumn,
58
- H as repeatedReads,
59
- P as repeatedTables,
60
- ha as requireBaseTable,
61
- g as rowsPerBase,
62
- pa as saveQuery,
63
- Qa as scopeQuery,
64
- _a as setBaseTable,
65
- Ua as setDistinct,
66
- ba as setHaving,
67
- Aa as setPaging,
68
- k as setSharedBase,
69
- O as setUnionAll,
70
- X as sharedQueryName,
71
- Y as sharedUses,
72
- j as unionName,
73
- J as unionTableColumns,
74
- w as unionWithQuery,
75
- K as unionableTables,
76
- Ma as unscopedBodies,
77
- z as unwrapUnion,
78
- W as validateQuery,
79
- l as validateSchema
264
+ le as DEFAULT_FUNCTIONS,
265
+ lt as DIALECTS,
266
+ pt as DIALECT_LABELS,
267
+ pe as EMPTY_SCHEMA,
268
+ ce as MAX_NAME_LENGTH,
269
+ Se as MAX_NUMBER_DIGITS,
270
+ we as MAX_TEXT_LENGTH,
271
+ Ee as MAX_TYPE_NAME_LENGTH,
272
+ S as QUERY_FORMAT_VERSION,
273
+ Fe as QUERY_ISSUE_KINDS,
274
+ Je as QUERY_WARNING_KINDS,
275
+ p as QueryFormatError,
276
+ ct as ScopeError,
277
+ Pe as SharedBaseError,
278
+ x as addCondition,
279
+ Z as addGroupBy,
280
+ K as addJoin,
281
+ ge as addMeasure,
282
+ te as addOrderBy,
283
+ z as addSelectItem,
284
+ He as addSharedQuery,
285
+ ve as addUnionBranch,
286
+ Te as addUnionJoin,
287
+ Ne as addUnionTable,
288
+ yt as astToParameterizedSql,
289
+ dt as astToSql,
290
+ ye as branchesOf,
291
+ Re as calendarDay,
292
+ Ie as createEmptyQuery,
293
+ Ae as createUnion,
294
+ T as expr,
295
+ de as filterSchema,
296
+ $e as fromIsoDay,
297
+ fe as functionsForDialect,
298
+ O as hasBaseTable,
299
+ me as isUnion,
300
+ ke as isoDay,
301
+ Xe as issueLocation,
302
+ Ye as joinMultiplicity,
303
+ We as joinSharedQuery,
304
+ Be as keepMeasuresInStep,
305
+ ie as loadQuery,
306
+ Ke as makeShared,
307
+ Ve as makeSubQuery,
308
+ Oe as measureFacts,
309
+ De as queryParams,
310
+ ze as relativeDateLabel,
311
+ V as removeJoin,
312
+ Ze as removeSharedQuery,
313
+ Le as removeUnionTable,
314
+ et as renameSharedQuery,
315
+ Qe as renameUnionColumn,
316
+ tt as repeatedReads,
317
+ rt as repeatedTables,
318
+ ne as requireBaseTable,
319
+ at as rowsPerBase,
320
+ se as saveQuery,
321
+ ft as scopeQuery,
322
+ W as setBaseTable,
323
+ ae as setDistinct,
324
+ ee as setHaving,
325
+ re as setPaging,
326
+ nt as setSharedBase,
327
+ Me as setUnionAll,
328
+ st as sharedQueryName,
329
+ it as sharedUses,
330
+ Ue as unionName,
331
+ _e as unionTableColumns,
332
+ je as unionWithQuery,
333
+ qe as unionableTables,
334
+ mt as unscopedBodies,
335
+ xe as unwrapUnion,
336
+ ot as validateQuery,
337
+ he as validateSchema
80
338
  };
@@ -0,0 +1,165 @@
1
+ import { a as M, m as Q } from "./schema-dP_ISylQ.js";
2
+ import { r as B } from "./params-MMOdKWnW.js";
3
+ import { s as F, a as I } from "./sqlGen-B7-2-i9V.js";
4
+ const L = 0.05, S = (e) => typeof e == "object" && e !== null && !Array.isArray(e);
5
+ function O(e) {
6
+ let r = typeof e == "string" ? JSON.parse(e) : e;
7
+ if (Array.isArray(r) && ([r] = r), S(r) && "QUERY PLAN" in r) return O(r["QUERY PLAN"]);
8
+ if (S(r) && S(r.Plan)) return r.Plan;
9
+ throw new TypeError("explainQuery: not a PostgreSQL plan from EXPLAIN (FORMAT JSON)");
10
+ }
11
+ const z = (e) => e + Math.max(0, 1 - 0.3 * e), E = (e) => {
12
+ var r;
13
+ return e["Parallel Aware"] === !0 || ((r = e.Plans) == null ? void 0 : r[0]) !== void 0 && E(e.Plans[0]);
14
+ }, v = (e, r) => r.reduce(
15
+ (s, o) => s[o],
16
+ e
17
+ ), R = (e) => e.type === "exists" ? [] : M(e);
18
+ function $(e, r, s) {
19
+ return e.type === "field" ? e.table === r && s.includes(e.column) : R(e).some((o) => $(o, r, s));
20
+ }
21
+ function k(e, r, s) {
22
+ return e.type === "field" && e.table === r && s.add(e.column), R(e).forEach((o) => k(o, r, s)), s;
23
+ }
24
+ const _ = (e) => new Set(
25
+ [...e.replace(/'(?:[^']|'')*'/g, " ").matchAll(/"((?:[^"]|"")+)"|([A-Za-z_][\w$]*)/g)].map((r) => (r[1] ?? r[2]).replace(/""/g, '"'))
26
+ );
27
+ function C(e, r, s, o) {
28
+ const { where: l } = v(o.named, s.body);
29
+ if (!l) return;
30
+ const h = _(e), b = (n) => s.table && o.resolveName ? o.resolveName(s.table, n) : n, m = [...k(l, r, /* @__PURE__ */ new Set())].filter((n) => h.has(b(n)));
31
+ if (m.length === 0) return;
32
+ const t = (l.type === "logical" && l.operator === "AND" ? l.operands.map((n, p) => ({ operand: n, path: ["where", "operands", p] })) : [{ operand: l, path: ["where"] }]).filter(({ operand: n }) => $(n, r, m)), a = t.length === 1 ? t[0].path : ["where"];
33
+ return { columns: m, path: [...s.body, ...a] };
34
+ }
35
+ function T(e, r) {
36
+ const s = (e["Sort Key"] ?? []).join(" ").match(/\b_qb\d+\b/);
37
+ return s ? r.places.get(s[0]) : e.Alias && r.places.has(e.Alias) ? r.places.get(e.Alias) : (e.Plans ?? []).map((o) => T(o, r)).find(Boolean);
38
+ }
39
+ function J(e, r) {
40
+ const s = r.minRows ?? 1e4, o = (t) => {
41
+ var n;
42
+ const a = typeof r.tableRows == "function" ? r.tableRows(t) : (n = r.tableRows) == null ? void 0 : n[t];
43
+ return a !== void 0 && a >= 0 ? a : void 0;
44
+ }, l = [], h = (t, a) => {
45
+ const n = t.Alias === void 0 ? void 0 : r.places.get(t.Alias);
46
+ if (!n) return;
47
+ const p = t["Relation Name"], c = o(p), { table: d } = n;
48
+ if (t.Filter && c !== void 0 && c >= s && a <= c * L) {
49
+ const f = C(t.Filter, t.Alias, n, r);
50
+ if (f) {
51
+ const { columns: i, path: g } = f;
52
+ l.push({
53
+ kind: "missingIndex",
54
+ pathSegments: g,
55
+ ...d !== void 0 && { table: d },
56
+ columns: i,
57
+ rows: c,
58
+ message: `${p} is read whole for ${t.Filter}: no index for ${i.join(", ")}`
59
+ });
60
+ return;
61
+ }
62
+ }
63
+ const y = c ?? (t.Filter ? void 0 : a);
64
+ (y ?? a) < s || l.push({
65
+ kind: "fullScan",
66
+ pathSegments: n.path,
67
+ ...d !== void 0 && { table: d },
68
+ ...y !== void 0 && { rows: y },
69
+ message: `${p} is read whole`
70
+ });
71
+ }, b = (t, a, n) => {
72
+ if (n < s) return;
73
+ const p = T(t, r);
74
+ if (!p) return;
75
+ const c = v(r.named, p.body), d = a !== void 0 && ["Aggregate", "Group", "Unique"].includes(a["Node Type"]);
76
+ let y;
77
+ d && (c.groupBy ?? []).length > 0 ? y = "groupBy" : !d && (c.orderBy ?? []).length > 0 && (y = "orderBy"), y && l.push({
78
+ kind: "sort",
79
+ pathSegments: [...p.body, y],
80
+ rows: n,
81
+ message: `Sorts ${n} rows on ${(t["Sort Key"] ?? []).join(", ")}`
82
+ });
83
+ }, m = (t, a, n) => {
84
+ const p = Math.round((t["Plan Rows"] ?? 0) * (E(t) ? n : 1));
85
+ t["Node Type"] === "Seq Scan" && h(t, p), (t["Node Type"] === "Sort" || t["Node Type"] === "Incremental Sort") && b(t, a, p);
86
+ const c = t["Workers Planned"];
87
+ (t.Plans ?? []).forEach((d) => m(
88
+ d,
89
+ t,
90
+ c === void 0 ? n : z(c)
91
+ ));
92
+ };
93
+ m(O(e), void 0, 1);
94
+ const u = /* @__PURE__ */ new Set();
95
+ return l.filter((t) => {
96
+ const a = `${t.kind}:${JSON.stringify(t.pathSegments)}`;
97
+ return u.has(a) ? !1 : (u.add(a), !0);
98
+ });
99
+ }
100
+ const P = (e) => Object.prototype.toString.call(e) === "[object Object]", U = (e) => Array.isArray(e.joins) && P(e.from);
101
+ function N(e, r = /* @__PURE__ */ new Set()) {
102
+ return Array.isArray(e) ? e.forEach((s) => N(s, r)) : P(e) && (["table", "alias", "name"].forEach((s) => {
103
+ typeof e[s] == "string" && r.add(e[s]);
104
+ }), Object.values(e).forEach((s) => N(s, r))), r;
105
+ }
106
+ function D(e) {
107
+ const r = N(e), s = /* @__PURE__ */ new Map();
108
+ let o = 0;
109
+ const l = () => {
110
+ do
111
+ o += 1;
112
+ while (r.has(`_qb${o}`));
113
+ return `_qb${o}`;
114
+ }, h = /* @__PURE__ */ new WeakMap(), b = (m, u) => {
115
+ if (Array.isArray(m)) return m.map((f, i) => b(f, [...u, i]));
116
+ if (!P(m)) return m;
117
+ const t = Object.fromEntries(
118
+ Object.entries(m).map(([f, i]) => [f, b(i, [...u, f])])
119
+ ), a = t.type === "exists" && h.get(t.query);
120
+ if (a) {
121
+ const f = (i) => i.type === "field" && i.table !== void 0 && a.has(i.table) ? { ...i, table: a.get(i.table) } : Q(i, f);
122
+ return { ...t, link: f(t.link) };
123
+ }
124
+ if (!U(t)) return t;
125
+ const n = /* @__PURE__ */ new Map(), p = Array.isArray(t.select);
126
+ let c = p ? t : { ...t, select: [] };
127
+ [c.from, ...c.joins].forEach((f, i) => {
128
+ const g = f.alias ?? f.table;
129
+ if (g === void 0) return;
130
+ const A = l();
131
+ n.set(g, A), s.set(A, {
132
+ path: i === 0 ? [...u, "from"] : [...u, "joins", i - 1],
133
+ body: u,
134
+ ...f.table !== void 0 && { table: f.table }
135
+ });
136
+ const w = B(c, g, A);
137
+ c = i === 0 ? { ...w, from: { ...w.from, alias: A } } : {
138
+ ...w,
139
+ joins: w.joins.map((j, q) => q === i - 1 ? { ...j, alias: A } : j)
140
+ };
141
+ });
142
+ const y = p ? c : (({ select: f, ...i }) => i)(c);
143
+ return h.set(y, n), y;
144
+ };
145
+ return { named: b(e, []), places: s };
146
+ }
147
+ function Y(e, r, s = {}) {
148
+ const { scope: o, ...l } = s, { named: h, places: b } = D(e);
149
+ if (o && !l.schema)
150
+ throw new TypeError("explainQuery: `scope` needs `schema`");
151
+ const m = o ? F(l.schema, h, o) : h, { sql: u, params: t } = I(m, r, l);
152
+ return {
153
+ sql: `EXPLAIN (FORMAT JSON) ${u}`,
154
+ params: t,
155
+ findings: (a, n = {}) => J(a, {
156
+ places: b,
157
+ named: h,
158
+ resolveName: l.resolveName,
159
+ ...n
160
+ })
161
+ };
162
+ }
163
+ export {
164
+ Y as explainQuery
165
+ };