@nongt/visql-core 0.8.0 → 0.10.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.
@@ -0,0 +1,356 @@
1
+ import { y as Y, m as G } from "./schema-KDJ1rpG5.js";
2
+ import { B as V } from "./params-kc6eNrpu.js";
3
+ import { s as Z, b as tt, a as et } from "./sqlGen-Crgheqys.js";
4
+ const C = (t, e) => e.reduce(
5
+ (s, i) => s[i],
6
+ t
7
+ );
8
+ function v(t, e) {
9
+ var i;
10
+ const s = typeof t.tableRows == "function" ? t.tableRows(e) : (i = t.tableRows) == null ? void 0 : i[e];
11
+ return s !== void 0 && s >= 0 ? s : void 0;
12
+ }
13
+ const B = (t) => t.type === "exists" ? [] : Y(t);
14
+ function Q(t, e, s) {
15
+ return t.type === "field" ? t.table === e && s.includes(t.column) : B(t).some((i) => Q(i, e, s));
16
+ }
17
+ function X(t, e, s) {
18
+ return t.type === "field" && t.table === e && s.add(t.column), B(t).forEach((i) => X(i, e, s)), s;
19
+ }
20
+ function $(t, e, s, i) {
21
+ const { where: f } = C(s.named, e.body);
22
+ if (!f) return;
23
+ const l = (o) => e.table && s.resolveName ? s.resolveName(e.table, o) : o, h = [...X(f, t, /* @__PURE__ */ new Set())].filter((o) => i(l(o)));
24
+ if (h.length === 0) return;
25
+ const c = (f.type === "logical" && f.operator === "AND" ? f.operands.map((o, a) => ({ operand: o, path: ["where", "operands", a] })) : [{ operand: f, path: ["where"] }]).filter(({ operand: o }) => Q(o, t, h)), n = c.length === 1 ? c[0].path : ["where"];
26
+ return { columns: h, path: [...e.body, ...n] };
27
+ }
28
+ function L(t, e, s) {
29
+ const i = C(e.named, t.body);
30
+ if (s && (i.groupBy ?? []).length > 0) return [...t.body, "groupBy"];
31
+ if (!s && (i.orderBy ?? []).length > 0) return [...t.body, "orderBy"];
32
+ }
33
+ function k(t) {
34
+ const e = /* @__PURE__ */ new Set();
35
+ return t.filter((s) => {
36
+ const i = `${s.kind}:${JSON.stringify(s.pathSegments)}`;
37
+ return e.has(i) ? !1 : (e.add(i), !0);
38
+ });
39
+ }
40
+ const st = ["ALL", "index"], rt = 5, A = (t) => typeof t == "object" && t !== null && !Array.isArray(t), F = (t) => typeof t.table_name == "string" && typeof t.access_type == "string";
41
+ function x(t) {
42
+ const e = typeof t == "string" ? JSON.parse(t) : t;
43
+ if (A(e) && A(e.query_block)) return e;
44
+ const s = Array.isArray(e) ? e[0] : A(e) && e.EXPLAIN;
45
+ if (s) return x(s);
46
+ throw new TypeError("explainQuery: not a MySQL plan from EXPLAIN FORMAT=JSON (explain_json_format_version 1)");
47
+ }
48
+ function j(t, e = []) {
49
+ return Array.isArray(t) ? t.forEach((s) => j(s, e)) : A(t) && (F(t) ? e.push(t) : Object.values(t).forEach((s) => j(s, e))), e;
50
+ }
51
+ const nt = (t, e) => new Set(
52
+ [...t.matchAll(/`((?:[^`]|``)+)`\.(?=`((?:[^`]|``)+)`)/g)].filter((s) => s[1].replace(/``/g, "`") === e).map((s) => s[2].replace(/``/g, "`"))
53
+ );
54
+ function it(t, e) {
55
+ const s = e.minRows ?? 1e4, i = [], f = (r) => {
56
+ const c = e.places.get(r.table_name), n = c == null ? void 0 : c.table;
57
+ if (!c || !n || !st.includes(r.access_type)) return;
58
+ const o = r.rows_examined_per_scan ?? 0;
59
+ if (o < s) return;
60
+ const a = Number(r.filtered ?? 100);
61
+ if (r.attached_condition && a <= rt) {
62
+ const u = nt(r.attached_condition, r.table_name), p = $(r.table_name, c, e, (g) => u.has(g));
63
+ if (p) {
64
+ i.push({
65
+ kind: "missingIndex",
66
+ pathSegments: p.path,
67
+ table: n,
68
+ columns: p.columns,
69
+ rows: o,
70
+ message: `${n} is read whole: no index for ${p.columns.join(", ")}`
71
+ });
72
+ return;
73
+ }
74
+ }
75
+ i.push({
76
+ kind: "fullScan",
77
+ pathSegments: c.path,
78
+ table: n,
79
+ rows: o,
80
+ message: `${n} is read whole`
81
+ });
82
+ }, l = (r, c) => {
83
+ var g;
84
+ if (!r.using_filesort && !r.using_temporary_table) return;
85
+ const n = j(r), o = ((g = n[n.length - 1]) == null ? void 0 : g.rows_produced_per_join) ?? 0;
86
+ if (o < s) return;
87
+ const a = n.map((b) => e.places.get(b.table_name)).find((b) => b !== void 0), u = a && L(a, e, c);
88
+ if (!u) return;
89
+ const p = r.using_filesort ? "sort" : "temporaryTable";
90
+ i.push({
91
+ kind: p,
92
+ pathSegments: u,
93
+ rows: o,
94
+ message: p === "sort" ? `Sorts ${o} rows` : `Puts ${o} rows in a temporary table`
95
+ });
96
+ }, h = (r) => {
97
+ Array.isArray(r) && r.forEach(h), A(r) && (F(r) && f(r), A(r.ordering_operation) && l(r.ordering_operation, !1), A(r.grouping_operation) && l(r.grouping_operation, !0), Object.values(r).forEach(h));
98
+ };
99
+ return h(x(t)), k(i);
100
+ }
101
+ const ot = 0.05, _ = (t) => typeof t == "object" && t !== null && !Array.isArray(t);
102
+ function W(t) {
103
+ let e = typeof t == "string" ? JSON.parse(t) : t;
104
+ if (Array.isArray(e) && ([e] = e), _(e) && "QUERY PLAN" in e) return W(e["QUERY PLAN"]);
105
+ if (_(e) && _(e.Plan)) return e.Plan;
106
+ throw new TypeError("explainQuery: not a PostgreSQL plan from EXPLAIN (FORMAT JSON)");
107
+ }
108
+ const at = (t) => t + Math.max(0, 1 - 0.3 * t), J = (t) => {
109
+ var e;
110
+ return t["Parallel Aware"] === !0 || ((e = t.Plans) == null ? void 0 : e[0]) !== void 0 && J(t.Plans[0]);
111
+ }, ct = (t) => new Set(
112
+ [...t.replace(/'(?:[^']|'')*'/g, " ").matchAll(/"((?:[^"]|"")+)"|([A-Za-z_][\w$]*)/g)].map((e) => (e[1] ?? e[2]).replace(/""/g, '"'))
113
+ );
114
+ function U(t, e) {
115
+ const s = (t["Sort Key"] ?? []).join(" ").match(/\b_qb\d+\b/);
116
+ return s ? e.places.get(s[0]) : t.Alias && e.places.has(t.Alias) ? e.places.get(t.Alias) : (t.Plans ?? []).map((i) => U(i, e)).find(Boolean);
117
+ }
118
+ function lt(t, e) {
119
+ const s = e.minRows ?? 1e4, i = [], f = (r, c) => {
120
+ const n = r.Alias === void 0 ? void 0 : e.places.get(r.Alias);
121
+ if (!n) return;
122
+ const o = r["Relation Name"], a = v(e, o), { table: u } = n;
123
+ if (r.Filter && a !== void 0 && a >= s && c <= a * ot) {
124
+ const g = ct(r.Filter), b = $(r.Alias, n, e, (d) => g.has(d));
125
+ if (b) {
126
+ const { columns: d, path: m } = b;
127
+ i.push({
128
+ kind: "missingIndex",
129
+ pathSegments: m,
130
+ ...u !== void 0 && { table: u },
131
+ columns: d,
132
+ rows: a,
133
+ message: `${o} is read whole for ${r.Filter}: no index for ${d.join(", ")}`
134
+ });
135
+ return;
136
+ }
137
+ }
138
+ const p = a ?? (r.Filter ? void 0 : c);
139
+ (p ?? c) < s || i.push({
140
+ kind: "fullScan",
141
+ pathSegments: n.path,
142
+ ...u !== void 0 && { table: u },
143
+ ...p !== void 0 && { rows: p },
144
+ message: `${o} is read whole`
145
+ });
146
+ }, l = (r, c, n) => {
147
+ if (n < s) return;
148
+ const o = U(r, e);
149
+ if (!o) return;
150
+ const a = c !== void 0 && ["Aggregate", "Group", "Unique"].includes(c["Node Type"]), u = L(o, e, a);
151
+ u && i.push({
152
+ kind: "sort",
153
+ pathSegments: u,
154
+ rows: n,
155
+ message: `Sorts ${n} rows on ${(r["Sort Key"] ?? []).join(", ")}`
156
+ });
157
+ }, h = (r, c, n) => {
158
+ const o = Math.round((r["Plan Rows"] ?? 0) * (J(r) ? n : 1));
159
+ r["Node Type"] === "Seq Scan" && f(r, o), (r["Node Type"] === "Sort" || r["Node Type"] === "Incremental Sort") && l(r, c, o);
160
+ const a = r["Workers Planned"];
161
+ (r.Plans ?? []).forEach((u) => h(
162
+ u,
163
+ r,
164
+ a === void 0 ? n : at(a)
165
+ ));
166
+ };
167
+ return h(W(t), void 0, 1), k(i);
168
+ }
169
+ const ft = {
170
+ lt: "<",
171
+ gt: ">",
172
+ amp: "&",
173
+ quot: '"',
174
+ apos: "'"
175
+ }, ut = /&(#x[\da-f]+|#\d+|\w+);/gi, pt = (t) => t.replace(ut, (e, s) => {
176
+ if (s[0] !== "#") return ft[s] ?? e;
177
+ const i = s[1] === "x" || s[1] === "X";
178
+ return String.fromCodePoint(i ? parseInt(s.slice(2), 16) : Number(s.slice(1)));
179
+ }), q = (t) => t.slice(t.indexOf(":") + 1), mt = new RegExp([
180
+ /<(\/?)([\w:.-]+)((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>/.source,
181
+ /<!--[\s\S]*?-->/.source,
182
+ /<!\[CDATA\[[\s\S]*?\]\]>/.source,
183
+ /<[?!][^>]*>/.source
184
+ ].join("|"), "g"), dt = /([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
185
+ function ht(t) {
186
+ const e = { name: "", attributes: {}, children: [] }, s = [e];
187
+ return [...t.matchAll(mt)].forEach(([, i, f, l, h]) => {
188
+ if (f === void 0) return;
189
+ if (i) {
190
+ s.length > 1 && s.pop();
191
+ return;
192
+ }
193
+ const r = {
194
+ name: q(f),
195
+ attributes: Object.fromEntries([...l.matchAll(dt)].map(
196
+ ([, c, n, o]) => [q(c), pt(n ?? o)]
197
+ )),
198
+ children: []
199
+ };
200
+ s[s.length - 1].children.push(r), h || s.push(r);
201
+ }), e.children[0];
202
+ }
203
+ const bt = ["Table Scan", "Clustered Index Scan", "Index Scan"], S = (t) => t.startsWith("[") ? t.slice(1, -1).replace(/]]/g, "]") : t;
204
+ function z(t) {
205
+ if (typeof t == "string") return t.trimStart().startsWith("<") ? t : void 0;
206
+ if (!(typeof t != "object" || t === null))
207
+ return Object.values(t).map(z).find((e) => e !== void 0);
208
+ }
209
+ const E = (t, e, s = []) => (t.name === e && s.push(t), t.children.forEach((i) => E(i, e, s)), s), N = (t) => t.children.flatMap(
210
+ (e) => e.name === "RelOp" ? [e] : N(e)
211
+ ), T = (t, e) => t.children.flatMap((s) => s.children).find((s) => s.name === e), D = (t) => {
212
+ const e = T(t, "OrderBy");
213
+ return e ? E(e, "ColumnReference") : [];
214
+ }, P = (t, e) => {
215
+ const s = t == null ? void 0 : t.attributes[e];
216
+ return s === void 0 ? void 0 : Math.round(Number(s));
217
+ };
218
+ function gt(t) {
219
+ const e = /* @__PURE__ */ new Map();
220
+ return E(t, "MissingIndex").forEach((s) => {
221
+ const i = S(s.attributes.Table), f = e.get(i) ?? /* @__PURE__ */ new Set();
222
+ s.children.filter((l) => l.attributes.Usage !== "INCLUDE").flatMap((l) => E(l, "Column")).forEach((l) => f.add(S(l.attributes.Name))), e.set(i, f);
223
+ }), e;
224
+ }
225
+ function H(t, e) {
226
+ const s = D(t).map((l) => l.attributes.Alias && e.places.get(S(l.attributes.Alias))).find(Boolean);
227
+ if (s) return s;
228
+ const i = T(t, "Object"), f = i == null ? void 0 : i.attributes.Alias;
229
+ return f && e.places.has(S(f)) ? e.places.get(S(f)) : N(t).map((l) => H(l, e)).find(Boolean);
230
+ }
231
+ function yt(t) {
232
+ const e = z(t), s = e === void 0 ? void 0 : ht(e);
233
+ if ((s == null ? void 0 : s.name) !== "ShowPlanXML")
234
+ throw new TypeError("explainQuery: not a SQL Server plan from SET SHOWPLAN_XML");
235
+ return s;
236
+ }
237
+ function wt(t, e) {
238
+ const s = e.minRows ?? 1e4, i = yt(t), f = gt(i), l = [], h = (n) => {
239
+ const o = T(n, "Object"), a = (o == null ? void 0 : o.attributes.Alias) && S(o.attributes.Alias), u = a ? e.places.get(a) : void 0;
240
+ if (!o || !a || !u) return;
241
+ const p = S(o.attributes.Table), g = P(n, "TableCardinality") ?? v(e, p) ?? P(n, "EstimateRows");
242
+ if (g < s) return;
243
+ const { table: b } = u, d = f.get(p), m = T(n, "Predicate"), O = new Set(m && d ? E(m, "ColumnReference").filter((y) => y.attributes.Alias && S(y.attributes.Alias) === a).map((y) => S(y.attributes.Column)).filter((y) => d.has(y)) : []), w = $(a, u, e, (y) => O.has(y));
244
+ if (w) {
245
+ l.push({
246
+ kind: "missingIndex",
247
+ pathSegments: w.path,
248
+ ...b !== void 0 && { table: b },
249
+ columns: w.columns,
250
+ rows: g,
251
+ message: `${p} is read whole: no index for ${w.columns.join(", ")}`
252
+ });
253
+ return;
254
+ }
255
+ l.push({
256
+ kind: "fullScan",
257
+ pathSegments: u.path,
258
+ ...b !== void 0 && { table: b },
259
+ rows: g,
260
+ message: `${p} is read whole`
261
+ });
262
+ }, r = (n, o) => {
263
+ const a = P(N(n)[0], "EstimateRows") ?? P(n, "EstimateRows") ?? 0;
264
+ if (a < s) return;
265
+ const u = H(n, e);
266
+ if (!u) return;
267
+ const p = L(u, e, (o == null ? void 0 : o.attributes.PhysicalOp) === "Stream Aggregate");
268
+ if (!p) return;
269
+ const g = D(n).map((b) => b.attributes.Column);
270
+ l.push({
271
+ kind: "sort",
272
+ pathSegments: p,
273
+ rows: a,
274
+ message: `Sorts ${a} rows on ${g.join(", ")}`
275
+ });
276
+ }, c = (n, o) => {
277
+ const a = n.attributes.PhysicalOp;
278
+ bt.includes(a) && h(n), a === "Sort" && n.attributes.LogicalOp !== "Distinct Sort" && r(n, o), N(n).forEach((u) => c(u, a === "Parallelism" ? o : n));
279
+ };
280
+ return E(i, "QueryPlan").forEach((n) => N(n).forEach((o) => c(o, void 0))), k(l);
281
+ }
282
+ const I = (t) => Object.prototype.toString.call(t) === "[object Object]", St = (t) => Array.isArray(t.joins) && I(t.from);
283
+ function R(t, e = /* @__PURE__ */ new Set()) {
284
+ return Array.isArray(t) ? t.forEach((s) => R(s, e)) : I(t) && (["table", "alias", "name"].forEach((s) => {
285
+ typeof t[s] == "string" && e.add(t[s]);
286
+ }), Object.values(t).forEach((s) => R(s, e))), e;
287
+ }
288
+ function At(t) {
289
+ const e = R(t), s = /* @__PURE__ */ new Map();
290
+ let i = 0;
291
+ const f = () => {
292
+ do
293
+ i += 1;
294
+ while (e.has(`_qb${i}`));
295
+ return `_qb${i}`;
296
+ }, l = /* @__PURE__ */ new WeakMap(), h = (r, c) => {
297
+ if (Array.isArray(r)) return r.map((d, m) => h(d, [...c, m]));
298
+ if (!I(r)) return r;
299
+ const n = Object.fromEntries(
300
+ Object.entries(r).map(([d, m]) => [d, h(m, [...c, d])])
301
+ ), o = n.type === "exists" && l.get(n.query);
302
+ if (o) {
303
+ const d = (m) => m.type === "field" && m.table !== void 0 && o.has(m.table) ? { ...m, table: o.get(m.table) } : G(m, d);
304
+ return { ...n, link: d(n.link) };
305
+ }
306
+ if (!St(n)) return n;
307
+ const a = /* @__PURE__ */ new Map(), u = Array.isArray(n.select);
308
+ let p = u ? n : { ...n, select: [] };
309
+ [p.from, ...p.joins].forEach((d, m) => {
310
+ const O = d.alias ?? d.table;
311
+ if (O === void 0) return;
312
+ const w = f();
313
+ a.set(O, w), s.set(w, {
314
+ path: m === 0 ? [...c, "from"] : [...c, "joins", m - 1],
315
+ body: c,
316
+ ...d.table !== void 0 && { table: d.table }
317
+ });
318
+ const y = V(p, O, w);
319
+ p = m === 0 ? { ...y, from: { ...y.from, alias: w } } : {
320
+ ...y,
321
+ joins: y.joins.map((M, K) => K === m - 1 ? { ...M, alias: w } : M)
322
+ };
323
+ });
324
+ const b = u ? p : (({ select: d, ...m }) => m)(p);
325
+ return l.set(b, a), b;
326
+ };
327
+ return { named: h(t, []), places: s };
328
+ }
329
+ function Pt(t, e, s = {}) {
330
+ const { scope: i, ...f } = s, { named: l, places: h } = At(t);
331
+ if (i && !f.schema)
332
+ throw new TypeError("explainQuery: `scope` needs `schema`");
333
+ const r = i ? Z(f.schema, l, i) : l, c = {
334
+ postgres: lt,
335
+ mssql: wt,
336
+ mysql: it
337
+ }[e], n = (p, g = {}) => c(p, {
338
+ places: h,
339
+ named: l,
340
+ resolveName: f.resolveName,
341
+ ...g
342
+ });
343
+ if (e === "mssql")
344
+ return {
345
+ before: "SET SHOWPLAN_XML ON",
346
+ sql: tt(r, e, f),
347
+ params: [],
348
+ after: "SET SHOWPLAN_XML OFF",
349
+ findings: n
350
+ };
351
+ const { sql: o, params: a } = et(r, e, f);
352
+ return { sql: `${e === "mysql" ? "EXPLAIN FORMAT=JSON" : "EXPLAIN (FORMAT JSON)"} ${o}`, params: a, findings: n };
353
+ }
354
+ export {
355
+ Pt as explainQuery
356
+ };