sqllang 0.0.3 → 0.0.4

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.
package/dist/cjs/index.js CHANGED
@@ -12669,6 +12669,61 @@ var internal = {
12669
12669
  // One output row from `[name, value, name, value, ...]`. Compiled, it is a single
12670
12670
  // object literal, so a whole select list costs one call per row. Not
12671
12671
  // deterministic: each row needs its own object, never a folded shared one.
12672
+ // A one-table GROUP BY as one function: [alias, where | null, keys, aggregates], each
12673
+ // aggregate { kind, star, arg, filter }. The loop, the group lookup and the running
12674
+ // totals are one piece of code. Rows come in as `context.$scan`, the group table as
12675
+ // `context.$grp`. COUNT, SUM, AVG, MIN and MAX only: the incremental ones.
12676
+ GROUPSCAN: {
12677
+ method: () => {
12678
+ throw new SqlError("GROUPSCAN runs compiled only");
12679
+ },
12680
+ compile: ([alias, where, keys, aggs], bs) => {
12681
+ const raw = (text) => bs.compile([text]);
12682
+ const simple = (logic) => {
12683
+ const v = logic !== null && typeof logic === "object" ? logic.val : null;
12684
+ return Array.isArray(v) && v.length === 2 && v[0] === alias && typeof v[1] === "string" ? v[1] : null;
12685
+ };
12686
+ const read = (logic) => {
12687
+ const column = simple(logic);
12688
+ return column === null ? logic : raw(`(typeof (p = (r?.[${JSON.stringify(column)}] ?? null)) === "function" ? null : p)`);
12689
+ };
12690
+ const exprs = [...keys, ...aggs.flatMap((a) => [a.arg, a.filter])].filter((e) => e !== null);
12691
+ const needsContext = where !== null || exprs.some((e) => simple(e) === null);
12692
+ let res = raw('(() => { const rows = context["$scan"], grp = context["$grp"], root = grp.root, open = grp.open; let single = null, p, prev; const ints = []; for (let i = 0; i < rows.length; i++) { ');
12693
+ res = bs.compile`${res}if ((i & 1023) === 0) ${sync2(tick)}(Math.min(1024, rows.length - i)); const r = rows[i]; `;
12694
+ if (needsContext) res = bs.compile`${res}context[${alias}] = r; `;
12695
+ if (where !== null) res = bs.compile`${res}if (!${sync2(isTrue)}(${where})) continue; `;
12696
+ const fresh = raw(`{ ${aggs.map((_, j) => `c${j}: 0, s${j}: 0, n${j}: 0, b${j}: null`).join(", ")}${aggs.length ? ", " : ""}first: null }`);
12697
+ if (!keys.length) {
12698
+ res = bs.compile`${res}if (single === null) { single = ${fresh}; open(single, r) } const g = single; `;
12699
+ } else {
12700
+ const key = (logic) => bs.compile`(p = ${read(logic)}) === undefined ? null : (p !== null && typeof p === "object") ? ${sync2(keyOf)}(p) : p`;
12701
+ if (keys.length === 1) {
12702
+ res = bs.compile`${res}let g; { const k = ${key(keys[0])}; if (typeof k === "number" && k >= 0 && k < 1048576 && (k | 0) === k) { g = ints[k]; if (g === undefined) { g = ${fresh}; open(g, r); ints[k] = g } } else { g = root.get(k); if (g === undefined) { g = ${fresh}; open(g, r); root.set(k, g) } } } `;
12703
+ }
12704
+ res = bs.compile`${res}${raw(keys.length === 1 ? "" : "let level = root; ")}`;
12705
+ for (let d = 0; keys.length > 1 && d < keys.length - 1; d++) {
12706
+ res = bs.compile`${res}{ const k = ${key(keys[d])}; let next = level.get(k); if (next === undefined) { next = new Map(); level.set(k, next) } level = next } `;
12707
+ }
12708
+ if (keys.length > 1) res = bs.compile`${res}let g; { const k = ${key(keys[keys.length - 1])}; g = level.get(k); if (g === undefined) { g = ${fresh}; open(g, r); level.set(k, g) } } `;
12709
+ }
12710
+ aggs.forEach((a, j) => {
12711
+ let body;
12712
+ if (a.star) body = raw(`g.c${j}++; `);
12713
+ else {
12714
+ const kindCode = a.kind === SUM || a.kind === AVG ? bs.compile`${raw('const x = typeof v === "number" ? v : ')}${sync2(toNumber)}(v); if (x !== null) ${raw(`{ g.s${j} += x; g.n${j}++ }`)} ` : a.kind === MIN || a.kind === MAX ? bs.compile`${raw(`if (g.b${j} === null || (typeof v === "number" && typeof g.b${j} === "number" ? v ${a.kind === MIN ? "<" : ">"} g.b${j} : `)}${sync2(sortCompare)}(v, ${raw(`g.b${j}`)}, false, null) ${raw(a.kind === MIN ? "< 0" : "> 0")})) ${raw(`g.b${j} = v; `)}` : raw("");
12715
+ body = bs.compile`${raw("const v = ")}${read(a.arg)}; if (v !== null && v !== undefined) { ${raw(`g.c${j}++; `)}${kindCode} } `;
12716
+ }
12717
+ if (a.filter !== null) body = bs.compile`if (${sync2(isTrue)}(${read(a.filter)})) { ${body} } `;
12718
+ res = bs.compile`${res}{ ${body} } `;
12719
+ });
12720
+ return bs.compile`${res}} })()`;
12721
+ },
12722
+ traverse: false,
12723
+ deterministic: false
12724
+ },
12725
+ // (Both scans declare their own `prev`, the engine's scratch variable, so the snippets inside
12726
+ // them use a local instead of the enclosing function's, which a closure would keep in memory.)
12672
12727
  // A whole single-table scan as one function: [alias, where | null, row]. Compiled, the
12673
12728
  // loop, the filter and the projection are one piece of code, with the rows passed in
12674
12729
  // as `context.$scan`. Only used compiled; the interpreted path runs the loop itself.
@@ -12678,7 +12733,7 @@ var internal = {
12678
12733
  },
12679
12734
  compile: ([alias, where, row], bs) => {
12680
12735
  const skip = where === null ? bs.compile`` : bs.compile`if (!${sync2(isTrue)}(${where})) continue;`;
12681
- return bs.compile`(() => { const rows = context["$scan"]; const out = []; for (let i = 0; i < rows.length; i++) { if ((i & 1023) === 0) ${sync2(tick)}(Math.min(1024, rows.length - i)); context[${alias}] = rows[i]; ${skip} out.push(${row}) } return out })()`;
12736
+ return bs.compile`(() => { let prev; const rows = context["$scan"]; const out = []; for (let i = 0; i < rows.length; i++) { if ((i & 1023) === 0) ${sync2(tick)}(Math.min(1024, rows.length - i)); context[${alias}] = rows[i]; ${skip} out.push(${row}) } return out })()`;
12682
12737
  },
12683
12738
  traverse: false,
12684
12739
  deterministic: false
@@ -13033,8 +13088,9 @@ function extend(env, aliases, alias, row) {
13033
13088
  }
13034
13089
  function runSelect(p, state, outer, keep = null) {
13035
13090
  const base = outer ? Object.create(outer) : {};
13036
- const projector = makeProjector(p, state);
13037
13091
  const orderFns = p.orderBy ? p.orderBy.map((o) => fnOf(state, o.expr)) : null;
13092
+ const scan = orderFns === null && !p.grouped && p.having === null && scannable(p, state);
13093
+ const projector = makeProjector(p, state, scan);
13038
13094
  const top = orderFns && keep !== null && !p.distinct ? topK(keep, comparatorFor(p.orderBy)) : null;
13039
13095
  let items;
13040
13096
  let plain = null;
@@ -13051,8 +13107,8 @@ function runSelect(p, state, outer, keep = null) {
13051
13107
  });
13052
13108
  items = top.best;
13053
13109
  } else if (orderFns === null) {
13054
- plain = scanRows(p, state, base);
13055
- if (plain === null) {
13110
+ if (scan) plain = scanRows(p, state, base);
13111
+ else {
13056
13112
  plain = [];
13057
13113
  streamRows(p, state, base, (env) => {
13058
13114
  plain.push(projector.project(env));
@@ -13072,7 +13128,7 @@ function runSelect(p, state, outer, keep = null) {
13072
13128
  } else {
13073
13129
  let envs;
13074
13130
  if (single && p.grouped) {
13075
- envs = group(p, state, base, (visit) => streamRows(p, state, base, visit));
13131
+ envs = groupScannable(p, state) ? groupScan(p, state, base) : group(p, state, base, (visit) => streamRows(p, state, base, visit));
13076
13132
  } else {
13077
13133
  envs = [base];
13078
13134
  for (const step2 of p.steps) envs = joinStep(step2, envs, base, state);
@@ -13137,9 +13193,47 @@ function sourceRows(p, state, base) {
13137
13193
  const source = p.steps[0].source;
13138
13194
  return source.kind === "expr" ? toRows(fnOf(state, source.expr)(base), false) : materialize(source, state);
13139
13195
  }
13196
+ var groupLogics = /* @__PURE__ */ new WeakMap();
13197
+ function groupScannable(p, state) {
13198
+ return !state.interpreted && p.aggregates.every((spec) => INCREMENTAL.has(spec.name) && !spec.distinct && !spec.orderBy);
13199
+ }
13200
+ function groupScan(p, state, base) {
13201
+ let logic = groupLogics.get(p);
13202
+ if (!logic) {
13203
+ const aggs2 = p.aggregates.map((spec) => ({
13204
+ kind: KIND[spec.name],
13205
+ star: spec.star,
13206
+ arg: spec.star ? null : spec.args[0],
13207
+ filter: spec.filter
13208
+ }));
13209
+ groupLogics.set(p, logic = { GROUPSCAN: [p.steps[0].alias, p.where, p.groupBy ?? [], aggs2] });
13210
+ }
13211
+ const alias = p.steps[0].alias;
13212
+ const aggs = p.aggregates.map((spec) => ({ incremental: true, kind: KIND[spec.name] }));
13213
+ const list = [];
13214
+ const open = (g, row) => {
13215
+ g.first = snapshot(base);
13216
+ g.first[alias] = row;
13217
+ list.push(g);
13218
+ rows(list.length);
13219
+ };
13220
+ const env = snapshot(base);
13221
+ env.$scan = sourceRows(p, state, base);
13222
+ env.$grp = { root: /* @__PURE__ */ new Map(), open };
13223
+ fnOf(state, logic)(env);
13224
+ if (!(p.groupBy && p.groupBy.length) && list.length === 0) list.push({ first: base, accs: newAccumulators(aggs) });
13225
+ for (let i = 0; i < list.length; i++) {
13226
+ const g = list[i];
13227
+ if (g.accs) continue;
13228
+ g.accs = aggs.map((_, j) => ({ count: g[`c${j}`], sum: g[`s${j}`], numeric: g[`n${j}`], best: g[`b${j}`] }));
13229
+ }
13230
+ return finishGroups(list, aggs);
13231
+ }
13140
13232
  var scanLogics = /* @__PURE__ */ new WeakMap();
13233
+ function scannable(p, state) {
13234
+ return !state.interpreted && p.row !== null && p.steps.length === 1 && p.steps[0].join === "FROM" && !p.windows.length;
13235
+ }
13141
13236
  function scanRows(p, state, base) {
13142
- if (state.interpreted || !p.row) return null;
13143
13237
  let logic = scanLogics.get(p);
13144
13238
  if (!logic) scanLogics.set(p, logic = { SCAN: [p.steps[0].alias, p.where, p.row] });
13145
13239
  const env = snapshot(base);
@@ -13166,10 +13260,11 @@ function orderKeys(p, env, row, projector, orderFns) {
13166
13260
  for (let k = 0; k < orderFns.length; k++) keys[k] = orderFns[k](env);
13167
13261
  return keys;
13168
13262
  }
13169
- function makeProjector(p, state) {
13263
+ function makeProjector(p, state, skipBuild = false) {
13170
13264
  const cols = p.columns;
13171
- const exprFns = cols.map((c) => c.kind === "expr" ? fnOf(state, c.expr) : null);
13172
13265
  const hasStar = cols.some((c) => c.kind === "star");
13266
+ const rowFn = !skipBuild && !hasStar && p.row ? fnOf(state, p.row) : null;
13267
+ const exprFns = skipBuild || rowFn ? [] : cols.map((c) => c.kind === "expr" ? fnOf(state, c.expr) : null);
13173
13268
  const columnSet = /* @__PURE__ */ new Set();
13174
13269
  const columns = [];
13175
13270
  const addColumn = (name) => {
@@ -13180,7 +13275,6 @@ function makeProjector(p, state) {
13180
13275
  };
13181
13276
  if (!hasStar) for (const c of cols) addColumn(c.name);
13182
13277
  const plain = cols.map((c) => c.kind === "expr" && c.name !== "__proto__");
13183
- const rowFn = !hasStar && p.row ? fnOf(state, p.row) : null;
13184
13278
  const project = rowFn ?? ((env) => {
13185
13279
  const out = {};
13186
13280
  for (let j = 0; j < cols.length; j++) {
@@ -13797,6 +13891,9 @@ function group(p, state, base, each) {
13797
13891
  for (let i = 0; i < aggs.length; i++) accumulate(aggs[i], g.accs[i], env);
13798
13892
  });
13799
13893
  }
13894
+ return finishGroups(list, aggs);
13895
+ }
13896
+ function finishGroups(list, aggs) {
13800
13897
  const out = new Array(list.length);
13801
13898
  for (let gi = 0; gi < list.length; gi++) {
13802
13899
  const g = list[gi];
@@ -14045,10 +14142,31 @@ function prepare(sql, options = {}) {
14045
14142
  };
14046
14143
  }
14047
14144
  function query(sql, data, options = {}) {
14048
- return prepare(sql, options).query(data, options.params);
14145
+ const engine2 = options.engine ?? defaultEngine;
14146
+ return asRows(last(executePlan(planFor(sql, engine2, options), data, { ...options, engine: engine2 }).results));
14049
14147
  }
14050
14148
  function execute(sql, data, options = {}) {
14051
- return prepare(sql, options).execute(data, options.params);
14149
+ const engine2 = options.engine ?? defaultEngine;
14150
+ return executePlan(planFor(sql, engine2, options), data, { ...options, engine: engine2 });
14151
+ }
14152
+ var plans = /* @__PURE__ */ new WeakMap();
14153
+ var PLAN_CACHE_SIZE = 256;
14154
+ var PLAN_CACHE_MAX_SQL = 8192;
14155
+ function planFor(sql, engine2, options) {
14156
+ const fresh = () => compile(sql, { functions: engine2.sqlFunctions, limits: options.limits });
14157
+ if (options.limits || typeof sql !== "string" || sql.length > PLAN_CACHE_MAX_SQL) return fresh();
14158
+ let cache = plans.get(engine2);
14159
+ if (!cache) plans.set(engine2, cache = /* @__PURE__ */ new Map());
14160
+ let plan = cache.get(sql);
14161
+ if (plan !== void 0) {
14162
+ cache.delete(sql);
14163
+ cache.set(sql, plan);
14164
+ return plan;
14165
+ }
14166
+ plan = fresh();
14167
+ cache.set(sql, plan);
14168
+ if (cache.size > PLAN_CACHE_SIZE) cache.delete(cache.keys().next().value);
14169
+ return plan;
14052
14170
  }
14053
14171
  function last(results) {
14054
14172
  for (let i = results.length - 1; i >= 0; i--) if (!("inserted" in results[i])) return results[i];
package/dist/esm/index.js CHANGED
@@ -12630,6 +12630,61 @@ var internal = {
12630
12630
  // One output row from `[name, value, name, value, ...]`. Compiled, it is a single
12631
12631
  // object literal, so a whole select list costs one call per row. Not
12632
12632
  // deterministic: each row needs its own object, never a folded shared one.
12633
+ // A one-table GROUP BY as one function: [alias, where | null, keys, aggregates], each
12634
+ // aggregate { kind, star, arg, filter }. The loop, the group lookup and the running
12635
+ // totals are one piece of code. Rows come in as `context.$scan`, the group table as
12636
+ // `context.$grp`. COUNT, SUM, AVG, MIN and MAX only: the incremental ones.
12637
+ GROUPSCAN: {
12638
+ method: () => {
12639
+ throw new SqlError("GROUPSCAN runs compiled only");
12640
+ },
12641
+ compile: ([alias, where, keys, aggs], bs) => {
12642
+ const raw = (text) => bs.compile([text]);
12643
+ const simple = (logic) => {
12644
+ const v = logic !== null && typeof logic === "object" ? logic.val : null;
12645
+ return Array.isArray(v) && v.length === 2 && v[0] === alias && typeof v[1] === "string" ? v[1] : null;
12646
+ };
12647
+ const read = (logic) => {
12648
+ const column = simple(logic);
12649
+ return column === null ? logic : raw(`(typeof (p = (r?.[${JSON.stringify(column)}] ?? null)) === "function" ? null : p)`);
12650
+ };
12651
+ const exprs = [...keys, ...aggs.flatMap((a) => [a.arg, a.filter])].filter((e) => e !== null);
12652
+ const needsContext = where !== null || exprs.some((e) => simple(e) === null);
12653
+ let res = raw('(() => { const rows = context["$scan"], grp = context["$grp"], root = grp.root, open = grp.open; let single = null, p, prev; const ints = []; for (let i = 0; i < rows.length; i++) { ');
12654
+ res = bs.compile`${res}if ((i & 1023) === 0) ${sync2(tick)}(Math.min(1024, rows.length - i)); const r = rows[i]; `;
12655
+ if (needsContext) res = bs.compile`${res}context[${alias}] = r; `;
12656
+ if (where !== null) res = bs.compile`${res}if (!${sync2(isTrue)}(${where})) continue; `;
12657
+ const fresh = raw(`{ ${aggs.map((_, j) => `c${j}: 0, s${j}: 0, n${j}: 0, b${j}: null`).join(", ")}${aggs.length ? ", " : ""}first: null }`);
12658
+ if (!keys.length) {
12659
+ res = bs.compile`${res}if (single === null) { single = ${fresh}; open(single, r) } const g = single; `;
12660
+ } else {
12661
+ const key = (logic) => bs.compile`(p = ${read(logic)}) === undefined ? null : (p !== null && typeof p === "object") ? ${sync2(keyOf)}(p) : p`;
12662
+ if (keys.length === 1) {
12663
+ res = bs.compile`${res}let g; { const k = ${key(keys[0])}; if (typeof k === "number" && k >= 0 && k < 1048576 && (k | 0) === k) { g = ints[k]; if (g === undefined) { g = ${fresh}; open(g, r); ints[k] = g } } else { g = root.get(k); if (g === undefined) { g = ${fresh}; open(g, r); root.set(k, g) } } } `;
12664
+ }
12665
+ res = bs.compile`${res}${raw(keys.length === 1 ? "" : "let level = root; ")}`;
12666
+ for (let d = 0; keys.length > 1 && d < keys.length - 1; d++) {
12667
+ res = bs.compile`${res}{ const k = ${key(keys[d])}; let next = level.get(k); if (next === undefined) { next = new Map(); level.set(k, next) } level = next } `;
12668
+ }
12669
+ if (keys.length > 1) res = bs.compile`${res}let g; { const k = ${key(keys[keys.length - 1])}; g = level.get(k); if (g === undefined) { g = ${fresh}; open(g, r); level.set(k, g) } } `;
12670
+ }
12671
+ aggs.forEach((a, j) => {
12672
+ let body;
12673
+ if (a.star) body = raw(`g.c${j}++; `);
12674
+ else {
12675
+ const kindCode = a.kind === SUM || a.kind === AVG ? bs.compile`${raw('const x = typeof v === "number" ? v : ')}${sync2(toNumber)}(v); if (x !== null) ${raw(`{ g.s${j} += x; g.n${j}++ }`)} ` : a.kind === MIN || a.kind === MAX ? bs.compile`${raw(`if (g.b${j} === null || (typeof v === "number" && typeof g.b${j} === "number" ? v ${a.kind === MIN ? "<" : ">"} g.b${j} : `)}${sync2(sortCompare)}(v, ${raw(`g.b${j}`)}, false, null) ${raw(a.kind === MIN ? "< 0" : "> 0")})) ${raw(`g.b${j} = v; `)}` : raw("");
12676
+ body = bs.compile`${raw("const v = ")}${read(a.arg)}; if (v !== null && v !== undefined) { ${raw(`g.c${j}++; `)}${kindCode} } `;
12677
+ }
12678
+ if (a.filter !== null) body = bs.compile`if (${sync2(isTrue)}(${read(a.filter)})) { ${body} } `;
12679
+ res = bs.compile`${res}{ ${body} } `;
12680
+ });
12681
+ return bs.compile`${res}} })()`;
12682
+ },
12683
+ traverse: false,
12684
+ deterministic: false
12685
+ },
12686
+ // (Both scans declare their own `prev`, the engine's scratch variable, so the snippets inside
12687
+ // them use a local instead of the enclosing function's, which a closure would keep in memory.)
12633
12688
  // A whole single-table scan as one function: [alias, where | null, row]. Compiled, the
12634
12689
  // loop, the filter and the projection are one piece of code, with the rows passed in
12635
12690
  // as `context.$scan`. Only used compiled; the interpreted path runs the loop itself.
@@ -12639,7 +12694,7 @@ var internal = {
12639
12694
  },
12640
12695
  compile: ([alias, where, row], bs) => {
12641
12696
  const skip = where === null ? bs.compile`` : bs.compile`if (!${sync2(isTrue)}(${where})) continue;`;
12642
- return bs.compile`(() => { const rows = context["$scan"]; const out = []; for (let i = 0; i < rows.length; i++) { if ((i & 1023) === 0) ${sync2(tick)}(Math.min(1024, rows.length - i)); context[${alias}] = rows[i]; ${skip} out.push(${row}) } return out })()`;
12697
+ return bs.compile`(() => { let prev; const rows = context["$scan"]; const out = []; for (let i = 0; i < rows.length; i++) { if ((i & 1023) === 0) ${sync2(tick)}(Math.min(1024, rows.length - i)); context[${alias}] = rows[i]; ${skip} out.push(${row}) } return out })()`;
12643
12698
  },
12644
12699
  traverse: false,
12645
12700
  deterministic: false
@@ -12994,8 +13049,9 @@ function extend(env, aliases, alias, row) {
12994
13049
  }
12995
13050
  function runSelect(p, state, outer, keep = null) {
12996
13051
  const base = outer ? Object.create(outer) : {};
12997
- const projector = makeProjector(p, state);
12998
13052
  const orderFns = p.orderBy ? p.orderBy.map((o) => fnOf(state, o.expr)) : null;
13053
+ const scan = orderFns === null && !p.grouped && p.having === null && scannable(p, state);
13054
+ const projector = makeProjector(p, state, scan);
12999
13055
  const top = orderFns && keep !== null && !p.distinct ? topK(keep, comparatorFor(p.orderBy)) : null;
13000
13056
  let items;
13001
13057
  let plain = null;
@@ -13012,8 +13068,8 @@ function runSelect(p, state, outer, keep = null) {
13012
13068
  });
13013
13069
  items = top.best;
13014
13070
  } else if (orderFns === null) {
13015
- plain = scanRows(p, state, base);
13016
- if (plain === null) {
13071
+ if (scan) plain = scanRows(p, state, base);
13072
+ else {
13017
13073
  plain = [];
13018
13074
  streamRows(p, state, base, (env) => {
13019
13075
  plain.push(projector.project(env));
@@ -13033,7 +13089,7 @@ function runSelect(p, state, outer, keep = null) {
13033
13089
  } else {
13034
13090
  let envs;
13035
13091
  if (single && p.grouped) {
13036
- envs = group(p, state, base, (visit) => streamRows(p, state, base, visit));
13092
+ envs = groupScannable(p, state) ? groupScan(p, state, base) : group(p, state, base, (visit) => streamRows(p, state, base, visit));
13037
13093
  } else {
13038
13094
  envs = [base];
13039
13095
  for (const step2 of p.steps) envs = joinStep(step2, envs, base, state);
@@ -13098,9 +13154,47 @@ function sourceRows(p, state, base) {
13098
13154
  const source = p.steps[0].source;
13099
13155
  return source.kind === "expr" ? toRows(fnOf(state, source.expr)(base), false) : materialize(source, state);
13100
13156
  }
13157
+ var groupLogics = /* @__PURE__ */ new WeakMap();
13158
+ function groupScannable(p, state) {
13159
+ return !state.interpreted && p.aggregates.every((spec) => INCREMENTAL.has(spec.name) && !spec.distinct && !spec.orderBy);
13160
+ }
13161
+ function groupScan(p, state, base) {
13162
+ let logic = groupLogics.get(p);
13163
+ if (!logic) {
13164
+ const aggs2 = p.aggregates.map((spec) => ({
13165
+ kind: KIND[spec.name],
13166
+ star: spec.star,
13167
+ arg: spec.star ? null : spec.args[0],
13168
+ filter: spec.filter
13169
+ }));
13170
+ groupLogics.set(p, logic = { GROUPSCAN: [p.steps[0].alias, p.where, p.groupBy ?? [], aggs2] });
13171
+ }
13172
+ const alias = p.steps[0].alias;
13173
+ const aggs = p.aggregates.map((spec) => ({ incremental: true, kind: KIND[spec.name] }));
13174
+ const list = [];
13175
+ const open = (g, row) => {
13176
+ g.first = snapshot(base);
13177
+ g.first[alias] = row;
13178
+ list.push(g);
13179
+ rows(list.length);
13180
+ };
13181
+ const env = snapshot(base);
13182
+ env.$scan = sourceRows(p, state, base);
13183
+ env.$grp = { root: /* @__PURE__ */ new Map(), open };
13184
+ fnOf(state, logic)(env);
13185
+ if (!(p.groupBy && p.groupBy.length) && list.length === 0) list.push({ first: base, accs: newAccumulators(aggs) });
13186
+ for (let i = 0; i < list.length; i++) {
13187
+ const g = list[i];
13188
+ if (g.accs) continue;
13189
+ g.accs = aggs.map((_, j) => ({ count: g[`c${j}`], sum: g[`s${j}`], numeric: g[`n${j}`], best: g[`b${j}`] }));
13190
+ }
13191
+ return finishGroups(list, aggs);
13192
+ }
13101
13193
  var scanLogics = /* @__PURE__ */ new WeakMap();
13194
+ function scannable(p, state) {
13195
+ return !state.interpreted && p.row !== null && p.steps.length === 1 && p.steps[0].join === "FROM" && !p.windows.length;
13196
+ }
13102
13197
  function scanRows(p, state, base) {
13103
- if (state.interpreted || !p.row) return null;
13104
13198
  let logic = scanLogics.get(p);
13105
13199
  if (!logic) scanLogics.set(p, logic = { SCAN: [p.steps[0].alias, p.where, p.row] });
13106
13200
  const env = snapshot(base);
@@ -13127,10 +13221,11 @@ function orderKeys(p, env, row, projector, orderFns) {
13127
13221
  for (let k = 0; k < orderFns.length; k++) keys[k] = orderFns[k](env);
13128
13222
  return keys;
13129
13223
  }
13130
- function makeProjector(p, state) {
13224
+ function makeProjector(p, state, skipBuild = false) {
13131
13225
  const cols = p.columns;
13132
- const exprFns = cols.map((c) => c.kind === "expr" ? fnOf(state, c.expr) : null);
13133
13226
  const hasStar = cols.some((c) => c.kind === "star");
13227
+ const rowFn = !skipBuild && !hasStar && p.row ? fnOf(state, p.row) : null;
13228
+ const exprFns = skipBuild || rowFn ? [] : cols.map((c) => c.kind === "expr" ? fnOf(state, c.expr) : null);
13134
13229
  const columnSet = /* @__PURE__ */ new Set();
13135
13230
  const columns = [];
13136
13231
  const addColumn = (name) => {
@@ -13141,7 +13236,6 @@ function makeProjector(p, state) {
13141
13236
  };
13142
13237
  if (!hasStar) for (const c of cols) addColumn(c.name);
13143
13238
  const plain = cols.map((c) => c.kind === "expr" && c.name !== "__proto__");
13144
- const rowFn = !hasStar && p.row ? fnOf(state, p.row) : null;
13145
13239
  const project = rowFn ?? ((env) => {
13146
13240
  const out = {};
13147
13241
  for (let j = 0; j < cols.length; j++) {
@@ -13758,6 +13852,9 @@ function group(p, state, base, each) {
13758
13852
  for (let i = 0; i < aggs.length; i++) accumulate(aggs[i], g.accs[i], env);
13759
13853
  });
13760
13854
  }
13855
+ return finishGroups(list, aggs);
13856
+ }
13857
+ function finishGroups(list, aggs) {
13761
13858
  const out = new Array(list.length);
13762
13859
  for (let gi = 0; gi < list.length; gi++) {
13763
13860
  const g = list[gi];
@@ -14006,10 +14103,31 @@ function prepare(sql, options = {}) {
14006
14103
  };
14007
14104
  }
14008
14105
  function query(sql, data, options = {}) {
14009
- return prepare(sql, options).query(data, options.params);
14106
+ const engine2 = options.engine ?? defaultEngine;
14107
+ return asRows(last(executePlan(planFor(sql, engine2, options), data, { ...options, engine: engine2 }).results));
14010
14108
  }
14011
14109
  function execute(sql, data, options = {}) {
14012
- return prepare(sql, options).execute(data, options.params);
14110
+ const engine2 = options.engine ?? defaultEngine;
14111
+ return executePlan(planFor(sql, engine2, options), data, { ...options, engine: engine2 });
14112
+ }
14113
+ var plans = /* @__PURE__ */ new WeakMap();
14114
+ var PLAN_CACHE_SIZE = 256;
14115
+ var PLAN_CACHE_MAX_SQL = 8192;
14116
+ function planFor(sql, engine2, options) {
14117
+ const fresh = () => compile(sql, { functions: engine2.sqlFunctions, limits: options.limits });
14118
+ if (options.limits || typeof sql !== "string" || sql.length > PLAN_CACHE_MAX_SQL) return fresh();
14119
+ let cache = plans.get(engine2);
14120
+ if (!cache) plans.set(engine2, cache = /* @__PURE__ */ new Map());
14121
+ let plan = cache.get(sql);
14122
+ if (plan !== void 0) {
14123
+ cache.delete(sql);
14124
+ cache.set(sql, plan);
14125
+ return plan;
14126
+ }
14127
+ plan = fresh();
14128
+ cache.set(sql, plan);
14129
+ if (cache.size > PLAN_CACHE_SIZE) cache.delete(cache.keys().next().value);
14130
+ return plan;
14013
14131
  }
14014
14132
  function last(results) {
14015
14133
  for (let i = results.length - 1; i >= 0; i--) if (!("inserted" in results[i])) return results[i];