@nongt/visql 0.9.0 → 0.10.1

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,7 +1,7 @@
1
1
  var Ct = Object.defineProperty;
2
2
  var Lt = (o, T, D) => T in o ? Ct(o, T, { enumerable: !0, configurable: !0, writable: !0, value: D }) : o[T] = D;
3
3
  var It = (o, T, D) => Lt(o, typeof T != "symbol" ? T + "" : T, D);
4
- import { l as Dt, n as nt, p as gt, D as Ut, o as bt, d as Rt, r as Mt, q as qt, k as Nt, u as wt, w as xt, x as Ft, t as $t, m as Bt, a as Wt } from "./schema-dP_ISylQ.js";
4
+ import { k as Dt, l as nt, p as gt, D as Ut, n as bt, d as Rt, o as Mt, q as qt, j as Nt, u as wt, w as xt, x as Ft, t as $t, m as Bt, y as Wt } from "./schema-CgL10bid.js";
5
5
  import { t as Pt, f as _t, a as Gt } from "./calendarDate-CYlr9TvX.js";
6
6
  function kt(o, T, D = T) {
7
7
  const k = o.slice(0, T);
@@ -1,8 +1,8 @@
1
1
  var bt = Object.defineProperty;
2
2
  var Mt = (t, r, e) => r in t ? bt(t, r, { enumerable: !0, configurable: !0, writable: !0, value: e }) : t[r] = e;
3
3
  var w = (t, r, e) => Mt(t, typeof r != "symbol" ? r + "" : r, e);
4
- import { q as _, d as F, e as Lt, s as wt, m as X, g as st, j as Ft, t as Ut, k as qt, b as _t, i as Yt } from "./schema-dP_ISylQ.js";
5
- import { t as K, v as Z, w as Ht, x as jt, y as Pt, z as ot, A as vt, B as Bt } from "./params-MMOdKWnW.js";
4
+ import { q as _, d as F, a as Lt, s as wt, m as X, e as st, g as Ft, t as Ut, j as qt, b as _t, i as Yt } from "./schema-CgL10bid.js";
5
+ import { p as K, t as Z, v as Ht, w as jt, x as Pt, y as ot, z as vt, A as Bt } from "./params-DkVFbMQn.js";
6
6
  import { s as it } from "./calendarDate-CYlr9TvX.js";
7
7
  class Gt extends Error {
8
8
  constructor(e, n, s, i) {
@@ -60,34 +60,34 @@ function $t(t, r, e, n, s = new Set(at(r))) {
60
60
  const c = /* @__PURE__ */ new Map([[e.table, e.ref]]), f = /* @__PURE__ */ new Map(), $ = [], l = new Set(s), A = (g) => {
61
61
  const O = f.get(g);
62
62
  return O ? [...A(O.ref), O.tie] : [];
63
- }, D = (g, O, j) => {
63
+ }, y = (g, O, j) => {
64
64
  if (O === g.length) return d(A(c.get(j)));
65
- const y = g[O], M = wt(t, [...c.keys()], y);
65
+ const D = g[O], M = wt(t, [...c.keys()], D, { anyShape: !0 });
66
66
  if (!M) return !1;
67
- const Q = c.get(Z(M.on).find((T) => T !== y)), V = (T) => B(M.on, new Map([...c, [y, T]])), J = i.includes(y), z = (T, I) => {
68
- c.set(y, T), f.set(T, { ref: Q, tie: I });
69
- }, Ct = (T, I) => (z(T, I), d(A(T)) && D(g, O + 1, j) ? !0 : (c.delete(y), f.delete(T), !1));
67
+ const Q = c.get(Z(M.on).find((T) => T !== D)), V = (T) => B(M.on, new Map([...c, [D, T]])), J = i.includes(D), z = (T, I) => {
68
+ c.set(D, T), f.set(T, { ref: Q, tie: I });
69
+ }, Ct = (T, I) => (z(T, I), d(A(T)) && y(g, O + 1, j) ? !0 : (c.delete(D), f.delete(T), !1));
70
70
  if (u.some((T) => {
71
- if (T.table !== y) return !1;
72
- const I = T.alias ?? y, P = kt(r, V(I), Q, I, J);
71
+ if (T.table !== D) return !1;
72
+ const I = T.alias ?? D, P = kt(r, V(I), Q, I, J);
73
73
  return (P.forward || P.back) && Ct(I, P);
74
74
  })) return !0;
75
75
  if (!a) return !1;
76
- let p = y;
77
- for (let T = 2; l.has(p); T += 1) p = `${y}_${T}`;
76
+ let p = D;
77
+ for (let T = 2; l.has(p); T += 1) p = `${D}_${T}`;
78
78
  return l.add(p), z(p, { back: !0, forward: M.joinType === "inner" || J }), $.push({
79
79
  id: Ht(),
80
- table: y,
81
- ...p !== y ? { alias: p } : {},
80
+ table: D,
81
+ ...p !== D ? { alias: p } : {},
82
82
  joinType: M.joinType,
83
83
  on: V(p)
84
- }), D(g, O + 1, j);
84
+ }), y(g, O + 1, j);
85
85
  };
86
86
  let R;
87
87
  if (i.every((g) => {
88
88
  if (R || c.has(g)) return !0;
89
- const O = Lt(t, [...c.keys()], g);
90
- return O ? D(O, 0, g) : (R = g, !0);
89
+ const O = Lt(t, [...c.keys()], g, { anyShape: !0 });
90
+ return O ? y(O, 0, g) : (R = g, !0);
91
91
  }))
92
92
  return l.forEach((g) => s.add(g)), { joins: $, condition: B(n.condition, c), ...R ? { missing: R } : {} };
93
93
  };
@@ -275,12 +275,12 @@ function Tt(t, r) {
275
275
  };
276
276
  return { query: n(t), params: e };
277
277
  }
278
- const gr = ["mysql", "mssql", "postgres"], Dr = {
278
+ const gr = ["mysql", "mssql", "postgres"], yr = {
279
279
  mysql: "MySQL",
280
280
  mssql: "SQL Server",
281
281
  postgres: "PostgreSQL"
282
282
  };
283
- function S(t, r) {
283
+ function N(t, r) {
284
284
  const e = t.replace(/[\uE000-\uE003]/g, "");
285
285
  switch (r) {
286
286
  case "mysql":
@@ -295,7 +295,7 @@ function S(t, r) {
295
295
  }
296
296
  const Jt = /^[A-Za-z_][A-Za-z0-9_]*$/, At = (t) => `${t}`, zt = /\uE000(\d+)\uE000/g;
297
297
  let C;
298
- function yr(t, r) {
298
+ function Dr(t, r) {
299
299
  C = { ...t, writing: [] };
300
300
  try {
301
301
  return r();
@@ -369,7 +369,7 @@ function gt(t, r, e) {
369
369
  return typeof t == "number" || typeof t == "bigint" ? String(t) : t instanceof Date ? `'${it(t)}'` : String(t);
370
370
  }
371
371
  let q = "native";
372
- function Dt(t, r) {
372
+ function yt(t, r) {
373
373
  q = t ?? "native";
374
374
  try {
375
375
  return r();
@@ -568,15 +568,15 @@ const v = {
568
568
  STRING_AGG: ([t = "??"], r, e, n, s, i) => {
569
569
  const u = r[1] ?? { type: "literal", value: ", " }, o = u.type === "literal" && typeof u.value == "string" ? gt(u.value, e) : "??", a = s.distinct ? "DISTINCT " : "", c = (l) => {
570
570
  var A;
571
- return (A = s.orderBy) != null && A.length ? `ORDER BY ${s.orderBy.map((D) => `${l(D)} ${D.direction === "desc" ? "DESC" : "ASC"}`).join(", ")}` : "";
571
+ return (A = s.orderBy) != null && A.length ? `ORDER BY ${s.orderBy.map((y) => `${l(y)} ${y.direction === "desc" ? "DESC" : "ASC"}`).join(", ")}` : "";
572
572
  }, f = (l) => i(l.expression), $ = (l) => l ? ` ${l}` : "";
573
573
  switch (e) {
574
574
  case "mysql":
575
575
  return `GROUP_CONCAT(${a}${t}${$(c(f))} SEPARATOR ${o})`;
576
576
  case "postgres": {
577
- const l = `CAST(${t} AS TEXT)`, A = c((D) => {
578
- if (!s.distinct) return f(D);
579
- if (F(D.expression, r[0])) return l;
577
+ const l = `CAST(${t} AS TEXT)`, A = c((y) => {
578
+ if (!s.distinct) return f(y);
579
+ if (F(y.expression, r[0])) return l;
580
580
  throw new Error("PostgreSQL orders STRING_AGG of different values by the value only");
581
581
  });
582
582
  return `STRING_AGG(${a}${l}, ${o}${$(A)})`;
@@ -592,7 +592,7 @@ const v = {
592
592
  }
593
593
  }
594
594
  };
595
- function N(t) {
595
+ function S(t) {
596
596
  return t.type === "binary" || t.type === "logical" || t.type === "if" || t.type === "case";
597
597
  }
598
598
  function E(t, r, e, n) {
@@ -602,7 +602,7 @@ function nt(t, r, e, n) {
602
602
  const s = (i) => {
603
603
  if (!i) return "??";
604
604
  const u = E(i, r, e, n);
605
- return N(i) ? `(${u})` : u;
605
+ return S(i) ? `(${u})` : u;
606
606
  };
607
607
  return m(t, () => {
608
608
  const [i, u] = t.type === "list" ? t.items : [t];
@@ -623,8 +623,8 @@ function rr(t, r, e, n) {
623
623
  }
624
624
  case "field": {
625
625
  if (!t.column) return "??";
626
- const o = S(t.column, r);
627
- return t.table ? `${S(t.table, r)}.${o}` : o;
626
+ const o = N(t.column, r);
627
+ return t.table ? `${N(t.table, r)}.${o}` : o;
628
628
  }
629
629
  case "function": {
630
630
  const o = t.args.map(($) => E($, r, e, n)), a = tr[t.name.toUpperCase()];
@@ -643,18 +643,18 @@ function rr(t, r, e, n) {
643
643
  return `${c}(${f}${o.join(", ")})`;
644
644
  }
645
645
  case "binary": {
646
- const o = t.operator ? dt(t.operator, r) : "=", a = E(t.left, r, e, n), c = N(t.left) ? `(${a})` : a;
646
+ const o = t.operator ? dt(t.operator, r) : "=", a = E(t.left, r, e, n), c = S(t.left) ? `(${a})` : a;
647
647
  if (vt(t.operator)) return `${c} ${o}`;
648
648
  if (!t.right) return `${c} ${o} ??`;
649
649
  if (o === "BETWEEN")
650
650
  return `${c} BETWEEN ${nt(t.right, r, e, n)}`;
651
651
  if (o === "IN")
652
652
  return t.right.type === "list" ? `${c} IN ${E(t.right, r, e, n)}` : `${c} IN (${E(t.right, r, e, n)})`;
653
- const f = E(t.right, r, e, n), $ = N(t.right) ? `(${f})` : f;
653
+ const f = E(t.right, r, e, n), $ = S(t.right) ? `(${f})` : f;
654
654
  if (t.operator === "IS NOT DISTINCT FROM" && q === "expanded") {
655
- const l = (D) => {
656
- const R = E(D, r, e, n);
657
- return N(D) ? `(${R})` : R;
655
+ const l = (y) => {
656
+ const R = E(y, r, e, n);
657
+ return S(y) ? `(${R})` : R;
658
658
  }, A = `${l(t.left)} IS NULL AND ${l(t.right)} IS NULL`;
659
659
  return `(${c} = ${$} OR (${A}))`;
660
660
  }
@@ -682,15 +682,15 @@ ${s})`;
682
682
  const { operand: o } = t;
683
683
  if (o.type === "binary" && o.operator === "IN" && ((u = o.right) == null ? void 0 : u.type) === "subquery") {
684
684
  const a = E(o.left, r, e, n);
685
- return `${N(o.left) ? `(${a})` : a} NOT IN (${E(o.right, r, e, n)})`;
685
+ return `${S(o.left) ? `(${a})` : a} NOT IN (${E(o.right, r, e, n)})`;
686
686
  }
687
687
  if (o.type === "binary" && o.operator === "BETWEEN" && o.right) {
688
688
  const a = E(o.left, r, e, n);
689
- return `${N(o.left) ? `(${a})` : a} NOT BETWEEN ${nt(o.right, r, e, n)}`;
689
+ return `${S(o.left) ? `(${a})` : a} NOT BETWEEN ${nt(o.right, r, e, n)}`;
690
690
  }
691
691
  if (o.type === "binary" && o.operator === "IS NOT DISTINCT FROM" && o.right && q === "native") {
692
692
  if (r === "mysql") return `NOT (${E(o, r, e, n)})`;
693
- const a = E(o.left, r, e, n), c = N(o.left) ? `(${a})` : a, f = E(o.right, r, e, n), $ = N(o.right) ? `(${f})` : f;
693
+ const a = E(o.left, r, e, n), c = S(o.left) ? `(${a})` : a, f = E(o.right, r, e, n), $ = S(o.right) ? `(${f})` : f;
694
694
  return `${c} IS DISTINCT FROM ${$}`;
695
695
  }
696
696
  if (o.type === "logical" || o.type === "not") {
@@ -729,7 +729,7 @@ ${[
729
729
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
730
730
  ...o.joins.map((l) => pt(l, r, n)),
731
731
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
732
- yt(f, r, n)
732
+ Dt(f, r, n)
733
733
  ].join(`
734
734
  `).replace(/^/gm, i)}
735
735
  ${s})`;
@@ -748,7 +748,7 @@ ${s}`;
748
748
  return "/* unknown */";
749
749
  }
750
750
  }
751
- function yt(t, r, e) {
751
+ function Dt(t, r, e) {
752
752
  return `WHERE
753
753
  ${E(t, r, 1, e)}`;
754
754
  }
@@ -760,12 +760,12 @@ const er = {
760
760
  cross: "CROSS JOIN"
761
761
  };
762
762
  let Ot = /* @__PURE__ */ new Map();
763
- function Nt(t, r, e) {
764
- return t.shared !== void 0 ? S(Ot.get(t.shared) ?? "??", r) : t.query ? `(
765
- ${St(t.query, r, e).replace(/^/gm, " ")}
766
- )` : S(t.table, r);
767
- }
768
763
  function St(t, r, e) {
764
+ return t.shared !== void 0 ? N(Ot.get(t.shared) ?? "??", r) : t.query ? `(
765
+ ${Nt(t.query, r, e).replace(/^/gm, " ")}
766
+ )` : N(t.table, r);
767
+ }
768
+ function Nt(t, r, e) {
769
769
  return _t(t).map((n) => W(n, r, e).join(`
770
770
  `)).join(Yt(t) && !t.all ? `
771
771
  UNION
@@ -776,20 +776,20 @@ UNION ALL
776
776
  function nr(t, r, e) {
777
777
  return t.length === 0 ? [] : [`WITH
778
778
  ${t.map((s) => m(s, () => {
779
- const i = St(s.query, r, e).replace(/^/gm, " ");
780
- return ` ${S(s.name, r)} AS (
779
+ const i = Nt(s.query, r, e).replace(/^/gm, " ");
780
+ return ` ${N(s.name, r)} AS (
781
781
  ${i}
782
782
  )`;
783
783
  })).join(`,
784
784
  `)}`];
785
785
  }
786
786
  function Rt(t, r, e) {
787
- const n = t.alias ? ` AS ${S(t.alias, r)}` : "";
788
- return `FROM ${m(t, () => `${Nt(t, r, e)}${n}`)}`;
787
+ const n = t.alias ? ` AS ${N(t.alias, r)}` : "";
788
+ return `FROM ${m(t, () => `${St(t, r, e)}${n}`)}`;
789
789
  }
790
790
  function pt(t, r, e) {
791
791
  return m(t, () => {
792
- const n = Nt(t, r, e), s = t.alias ? ` AS ${S(t.alias, r)}` : "";
792
+ const n = St(t, r, e), s = t.alias ? ` AS ${N(t.alias, r)}` : "";
793
793
  if (t.joinType === "cross") return `CROSS JOIN ${n}${s}`;
794
794
  const i = t.on ? E(t.on, r, 1, e) : "/* unconfigured */";
795
795
  return `${er[t.joinType]} ${n}${s}
@@ -799,7 +799,7 @@ function pt(t, r, e) {
799
799
  function sr(t, r, e, n = "SELECT") {
800
800
  if (t.length === 0) return `${n} ${m(t, () => "*")}`;
801
801
  const s = t.map((i) => m(i, () => {
802
- const u = E(i.expression, r, 1, e), o = i.alias ? ` AS ${S(i.alias, r)}` : "";
802
+ const u = E(i.expression, r, 1, e), o = i.alias ? ` AS ${N(i.alias, r)}` : "";
803
803
  return `${u}${o}`;
804
804
  }));
805
805
  return `${n}
@@ -835,7 +835,7 @@ function W(t, r, e, n = `SELECT${t.distinct ? " DISTINCT" : ""}`) {
835
835
  Rt(t.from, r, e),
836
836
  ...t.joins.map((u) => pt(u, r, e))
837
837
  ];
838
- t.where && s.push(yt(t.where, r, e));
838
+ t.where && s.push(Dt(t.where, r, e));
839
839
  const i = t.groupBy ?? [];
840
840
  if (i.length > 0 && s.push(or(i, r, e)), t.having) {
841
841
  const u = r === "mysql" ? ot(t.having, t) : t.having;
@@ -861,7 +861,7 @@ function ht(t, r, e) {
861
861
  }
862
862
  function Or(t, r, e = {}) {
863
863
  const n = e.values ? Pt(t, e.values) : t, s = e.schema ? Tt(n, e.schema).query : n, i = It(s, e);
864
- return Dt(e.nullSafeEqual, () => ht(i, r));
864
+ return yt(e.nullSafeEqual, () => ht(i, r));
865
865
  }
866
866
  function ar(t, r) {
867
867
  switch (t) {
@@ -875,14 +875,14 @@ function ar(t, r) {
875
875
  return "?";
876
876
  }
877
877
  }
878
- function Nr(t, r, e = {}) {
878
+ function Sr(t, r, e = {}) {
879
879
  const n = e.schema ? Tt(t, e.schema) : { query: t, params: /* @__PURE__ */ new Map() }, s = {
880
880
  values: [],
881
881
  named: new Map(Object.entries(e.values ?? {}).map(([c, f]) => {
882
882
  const $ = n.params.get(c);
883
883
  return [c, $ ? Et(f, $) : f];
884
884
  }))
885
- }, i = It(n.query, e), u = Dt(
885
+ }, i = It(n.query, e), u = yt(
886
886
  e.nullSafeEqual,
887
887
  () => ht(i, r, s)
888
888
  ), o = [];
@@ -894,10 +894,10 @@ function Nr(t, r, e = {}) {
894
894
  export {
895
895
  gr as D,
896
896
  Gt as S,
897
- Nr as a,
897
+ Sr as a,
898
898
  Or as b,
899
- Dr as c,
899
+ yr as c,
900
900
  Ar as s,
901
901
  mr as u,
902
- yr as w
902
+ Dr as w
903
903
  };
@@ -47,9 +47,10 @@ export declare function describeLink(schema: DatabaseSchema, node: ExistsNode, o
47
47
  * derived table, left out). */
48
48
  export declare function scopeTables(schema: DatabaseSchema, tables: (FromClause | JoinClause)[]): ScopeTable[];
49
49
  /** The tables a field inside an EXISTS may name: its own, then every table
50
- * the relations reach from them (picking one joins it inside), except
51
- * those named like a table of a query around it (`taken`) and those only
52
- * reached through one — inside, that name would be ambiguous. */
50
+ * joining one of them gives an ON (reachableTables, as outside: picking
51
+ * one joins it inside), except those named like a table of a query around
52
+ * it (`taken`) and those only reached through one — inside, that name
53
+ * would be ambiguous. */
53
54
  export declare function existsFieldTables(schema: DatabaseSchema, query: ExistsQuery, taken: Set<string>): ScopeTable[];
54
55
  /** The innermost EXISTS whose conditions `path` (in the tree `root`) goes
55
56
  * into, with the names the queries around those conditions use: `outer`
@@ -140,7 +140,7 @@ export declare function referencedTables(ast: ExpressionNode | undefined): strin
140
140
  /** Auto-adds (via addJoin's own suggestJoin logic) every table referenced by
141
141
  * a field in `ast` that the pipeline doesn't already have. A table with no
142
142
  * direct relation to anything already present gets the intermediate tables
143
- * it needs added first (findJoinPath) — e.g. picking a product_category
143
+ * it needs added first (joinAlong) — e.g. picking a product_category
144
144
  * column with only sale_transaction in FROM adds product, then
145
145
  * product_category — so each added join gets a real suggested ON condition
146
146
  * instead of an unconnected one. A table nothing connects to at all is still
@@ -109,6 +109,24 @@ export declare function relationsForTable(schema: DatabaseSchema, tableName: str
109
109
  * (`fromTable`), so callers never need to know which side is "many". When
110
110
  * several keys connect the same two tables, the first declared wins. */
111
111
  export declare function findRelation(schema: DatabaseSchema, tableA: string, tableB: string): Relation | undefined;
112
+ /** How findJoinPath and reachableTables may walk the relations. */
113
+ export interface JoinPathOptions {
114
+ /** Walk any path. By default a path never takes a one-to-many step
115
+ * (down: from a relation's `toTable` to its `fromTable`) after a
116
+ * many-to-one step (up), counting how the query's own tables were
117
+ * reached: `hours → employee → punch` pairs each hours row with every
118
+ * punch of its employee, on any day. A path is up only, or down and then
119
+ * up. scopeQuery walks any path: a rule can go up to a tenant and down to
120
+ * who may see it. */
121
+ anyShape?: boolean;
122
+ /** reachableTables: tables neither reached nor walked through. */
123
+ skip?: ReadonlySet<string>;
124
+ }
125
+ /** findJoinPath's path, with the table of the query it starts from. */
126
+ export declare function joinRoute(schema: DatabaseSchema, existingTables: string[], target: string, options?: JoinPathOptions): {
127
+ start: string;
128
+ tables: string[];
129
+ } | undefined;
112
130
  /** The chain of tables connecting `target` to any of `existingTables`
113
131
  * through the relation graph (walked in both directions), as the tables
114
132
  * that would need to be added, in join order, intermediates first, ending
@@ -119,33 +137,49 @@ export declare function findRelation(schema: DatabaseSchema, tableA: string, tab
119
137
  * Of all the chains, the one with the fewest fan-out steps, then the
120
138
  * fewest steps (issue 6). A fan-out step walks a relation from its `toTable`
121
139
  * to its `fromTable`, one row to many, which repeats the rows before it.
122
- * Ties go the way a breadth-first walk would: seeded in `existingTables`
123
- * order, neighbours in `relations` order, so the result is deterministic.
124
- * A table with `passThrough: false` is never a step (see startsOf for
125
- * where it may start). Returns [] when `target` is already present,
126
- * undefined when nothing connects it. */
127
- export declare function findJoinPath(schema: DatabaseSchema, existingTables: string[], target: string): string[] | undefined;
128
- /** Every table the relation graph (walked in both directions) reaches from
129
- * `existingTables`, them included: what findJoinPath finds a path to, for
130
- * all tables in one walk. A table with `passThrough: false` is reached,
131
- * but nothing past it. */
132
- export declare function reachableTables(schema: DatabaseSchema, existingTables: string[]): Set<string>;
140
+ * None comes after a step the other way, unless `options.anyShape`
141
+ * (JoinPathOptions). Ties go the way a breadth-first walk would: seeded in
142
+ * `existingTables` order, neighbours in `relations` order, so the result
143
+ * is deterministic. A table with `passThrough: false` is never a step (see
144
+ * startsOf for where it may start). Returns [] when `target` is already
145
+ * present, undefined when nothing connects it. */
146
+ export declare function findJoinPath(schema: DatabaseSchema, existingTables: string[], target: string, options?: JoinPathOptions): string[] | undefined;
147
+ /** Every table the relation graph reaches from `existingTables`, them
148
+ * included: what findJoinPath finds a path to, for all tables in one walk.
149
+ * A table with `passThrough: false` is reached, but nothing past it. */
150
+ export declare function reachableTables(schema: DatabaseSchema, existingTables: string[], options?: JoinPathOptions): Set<string>;
133
151
  export interface JoinSuggestion {
134
152
  joinType: JoinType;
135
153
  on: ExpressionNode;
136
154
  }
155
+ export interface SuggestJoinOptions {
156
+ /** The table before `newTable` on its join path (joinRoute): the join is
157
+ * tied to it, when they're related, rather than to the first table of
158
+ * the query that is. */
159
+ after?: string;
160
+ /** The query's tables on the optional side of a LEFT or FULL join. A
161
+ * join tied to one of them is LEFT too, whatever its key: an INNER join
162
+ * there would drop the rows the LEFT join kept. */
163
+ leftJoined?: string[];
164
+ /** Tie it to a table reached by a step up even when joining it from
165
+ * there is a step down, as scopeQuery's paths may (JoinPathOptions). By
166
+ * default such a table is no tie, so a table findJoinPath finds no path
167
+ * to gets no join (issue 17). */
168
+ anyShape?: boolean;
169
+ }
137
170
  /** Suggests a join type + ON condition for adding `newTable` alongside the
138
- * tables already in the pipeline, using the relation graph. Tries each
139
- * existing table in order (base table first, then join-insertion order);
140
- * the first relation found wins, so the result is deterministic. A table
141
- * with `passThrough: false` is tried only for itself, or when the query has
142
- * no other table (startsOf). `joinType` defaults to 'left' when the
143
- * relation's FK column (`fromColumn`) is nullable (e.g.
144
- * sale_transaction.promotion_id: an INNER join there would silently drop
145
- * unpromoted sales) and 'inner' otherwise, read off the column's own
146
- * `nullable` flag. Returns undefined if no relation connects `newTable` to
147
- * anything already present. */
148
- export declare function suggestJoin(schema: DatabaseSchema, existingTables: string[], newTable: string): JoinSuggestion | undefined;
171
+ * tables already in the pipeline, using the relation graph. Tied to
172
+ * `options.after` when it's related; else tries each existing table in
173
+ * order (base table first, then join-insertion order) and the first
174
+ * relation found wins, so the result is deterministic. A table with
175
+ * `passThrough: false` is tried only for itself, or when the query has no
176
+ * other table (startsOf). `joinType` is 'left' when the relation's FK
177
+ * column (`fromColumn`) is nullable (e.g. sale_transaction.promotion_id:
178
+ * an INNER join there would silently drop unpromoted sales) or the table
179
+ * it's tied to is in `options.leftJoined`, and 'inner' otherwise. Returns
180
+ * undefined if no relation connects `newTable` to anything already
181
+ * present, or only a step down from a table reached by a step up. */
182
+ export declare function suggestJoin(schema: DatabaseSchema, existingTables: string[], newTable: string, options?: SuggestJoinOptions): JoinSuggestion | undefined;
149
183
  export type SchemaIssueKind = 'duplicateTable' | 'duplicateColumn' | 'unknownTable' | 'unknownColumn' | 'duplicateRelation' | 'invalidFormat';
150
184
  export interface SchemaIssue {
151
185
  kind: SchemaIssueKind;
@@ -14,7 +14,7 @@ export { relativeDateLabel } from './core/relativeDates.js';
14
14
  export { QUERY_FORMAT_VERSION, QueryFormatError, loadQuery, saveQuery, type StoredQuery, } from './core/storedQuery.js';
15
15
  export type { ResolveName } from './core/resolveNames.js';
16
16
  export { astToParameterizedSql, astToSql, DIALECTS, DIALECT_LABELS, type NullSafeEqual, type ParameterizedSql, type ParameterizedSqlOptions, type SqlDialect, } from './core/sqlGen.js';
17
- export { EMPTY_SCHEMA, filterSchema, validateSchema, type DatabaseColumnType, type DatabaseSchema, type ColumnOption, type Relation, type SchemaIssue, type SchemaIssueKind, type Table, type TableColumn, type TableGroup, } from './core/schema.js';
17
+ export { EMPTY_SCHEMA, filterSchema, validateSchema, type DatabaseColumnType, type DatabaseSchema, type ColumnOption, type Relation, findJoinPath, reachableTables, suggestJoin, type JoinPathOptions, type JoinSuggestion, type SuggestJoinOptions, type SchemaIssue, type SchemaIssueKind, type Table, type TableColumn, type TableGroup, } from './core/schema.js';
18
18
  export { QUERY_ISSUE_KINDS, QUERY_WARNING_KINDS, validateQuery, type QueryIssue, type QueryIssueKind, type QueryWarningKind, type QueryIssueSeverity, type ValidateQueryOptions, } from './core/queryValidation.js';
19
19
  export type { OnExplain, PlanFinding, PlanFindingKind } from './core/planFindings.js';
20
20
  export { default as issueLocation, type IssueLocationStep } from './core/issueLocation.js';
@@ -3,7 +3,7 @@ import type { QueryPipeline } from '../core/queryAst.js';
3
3
  import { type ScopeRule } from '../core/scopeQuery.js';
4
4
  import { type ParameterizedSqlOptions } from '../core/sqlGen.js';
5
5
  /** The databases whose plans can be read. */
6
- export type ExplainDialect = 'postgres';
6
+ export type ExplainDialect = 'postgres' | 'mssql' | 'mysql';
7
7
  export interface ExplainOptions extends ParameterizedSqlOptions {
8
8
  /** The rule the query runs under (see scopeQuery), so the plan is the
9
9
  * one the query really gets. Needs `schema`. */
@@ -11,20 +11,26 @@ export interface ExplainOptions extends ParameterizedSqlOptions {
11
11
  }
12
12
  export interface PlanReadOptions {
13
13
  /** How many rows each table has, by its name in the database, e.g. from
14
- * `SELECT relname, reltuples FROM pg_class`. A plan only gives the rows a
15
- * scan returns, after its filter: with the sizes, a big table read
16
- * whole for a few rows is reported as a missing index. */
14
+ * `SELECT relname, reltuples FROM pg_class`. A PostgreSQL plan only
15
+ * gives the rows a scan returns, after its filter: with the sizes, a big
16
+ * table read whole for a few rows is reported as a missing index. SQL
17
+ * Server's plan has them itself. */
17
18
  tableRows?: Record<string, number> | ((table: string) => number | undefined);
18
19
  /** Below this many rows, nothing is reported. Default 10,000. */
19
20
  minRows?: number;
20
21
  }
21
22
  export interface ExplainedQuery {
23
+ /** SQL Server: run on the same connection before `sql`, as a batch of
24
+ * its own, and `after` once the plan is back. */
25
+ before?: string;
22
26
  /** The statement to run, EXPLAIN included, with `params` bound. */
23
27
  sql: string;
24
28
  params: unknown[];
29
+ after?: string;
25
30
  /** What the plan EXPLAIN gave says, on the parts of the query given to
26
- * explainQuery. Takes the plan as the driver returns it (rows with a
27
- * `QUERY PLAN` column) or as its JSON text. */
31
+ * explainQuery. Takes the plan as the driver returns it (PostgreSQL:
32
+ * rows with a `QUERY PLAN` column; SQL Server: the showplan's row) or as
33
+ * its JSON or XML text. */
28
34
  findings: (plan: unknown, options?: PlanReadOptions) => PlanFinding[];
29
35
  }
30
36
  /** A table, sub query or shared query's place in the query, under the name
@@ -0,0 +1,4 @@
1
+ import type { PlanFinding } from '../core/planFindings.js';
2
+ import { type ReadContext } from './planPlaces.js';
3
+ /** What `plan` says about the query `context.named` was named from. */
4
+ export default function readMySqlPlan(plan: unknown, context: ReadContext): PlanFinding[];
@@ -0,0 +1,27 @@
1
+ import type { PlanFinding } from '../core/planFindings.js';
2
+ import type { QueryPipeline } from '../core/queryAst.js';
3
+ import type { ResolveName } from '../core/resolveNames.js';
4
+ import type { Place, PlanReadOptions } from './explainQuery.js';
5
+ export interface ReadContext extends PlanReadOptions {
6
+ places: Map<string, Place>;
7
+ named: QueryPipeline;
8
+ resolveName?: ResolveName;
9
+ }
10
+ /** What's at `path` in the query: a body the walk over it found. */
11
+ export declare const valueAt: (root: unknown, path: (string | number)[]) => unknown;
12
+ /** A table's size from `tableRows`, by its name in the database. A
13
+ * negative one (PostgreSQL's reltuples before ANALYZE) is not known. */
14
+ export declare function sizeOf(context: ReadContext, relation: string): number | undefined;
15
+ /** The columns of the table at `place` (named `alias`) its body's WHERE
16
+ * compares, as the query names them, among those the plan names (`named`,
17
+ * by their SQL names), and where they're compared. None: undefined. */
18
+ export declare function compared(alias: string, place: Place, context: ReadContext, named: (sqlName: string) => boolean): {
19
+ columns: string[];
20
+ path: (string | number)[];
21
+ } | undefined;
22
+ /** Where a sort of rows from `place` shows in the query: its body's GROUP
23
+ * BY for a sort for grouping, else its ORDER BY. A sort the query doesn't
24
+ * ask for (a merge join's, DISTINCT's): undefined. */
25
+ export declare function sortClause(place: Place, context: ReadContext, grouping: boolean): (string | number)[] | undefined;
26
+ /** One finding per kind and place: a table read twice is one fix. */
27
+ export declare function onePerPlace(findings: PlanFinding[]): PlanFinding[];
@@ -1,12 +1,4 @@
1
1
  import type { PlanFinding } from '../core/planFindings.js';
2
- import type { QueryPipeline } from '../core/queryAst.js';
3
- import type { ResolveName } from '../core/resolveNames.js';
4
- import type { Place, PlanReadOptions } from './explainQuery.js';
5
- interface Context extends PlanReadOptions {
6
- places: Map<string, Place>;
7
- named: QueryPipeline;
8
- resolveName?: ResolveName;
9
- }
2
+ import { type ReadContext } from './planPlaces.js';
10
3
  /** What `plan` says about the query `context.named` was named from. */
11
- export default function readPostgresPlan(plan: unknown, context: Context): PlanFinding[];
12
- export {};
4
+ export default function readPostgresPlan(plan: unknown, context: ReadContext): PlanFinding[];
@@ -0,0 +1,4 @@
1
+ import type { PlanFinding } from '../core/planFindings.js';
2
+ import { type ReadContext } from './planPlaces.js';
3
+ /** What `plan` says about the query `context.named` was named from. */
4
+ export default function readSqlServerPlan(plan: unknown, context: ReadContext): PlanFinding[];
@@ -0,0 +1,7 @@
1
+ export interface XmlElement {
2
+ name: string;
3
+ attributes: Record<string, string>;
4
+ children: XmlElement[];
5
+ }
6
+ /** The document's root element. */
7
+ export default function parseXml(text: string): XmlElement | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nongt/visql",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
4
4
  "description": "A visual SQL query editor for React: build a whole query on a node canvas, store it as JSON, turn it into SQL.",
5
5
  "keywords": [
6
6
  "sql",