@nanobpm/urban 0.99.1 → 0.99.2

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.
@@ -228,7 +228,12 @@ export function compileToSqlSelect(expr, options = {}) {
228
228
  alias = `_${alias}`;
229
229
  return alias;
230
230
  };
231
- const walk = (node, projTable, existsDepth) => {
231
+ // `filter` marks a pure boolean-filter position (an EXISTS `WHERE`, a CASE `WHEN`, or an AND/OR clause
232
+ // nested in one). There NULL already behaves like false, so the COALESCE 0/1 normalisation is
233
+ // semantically redundant — and harmful: SQLite cannot use an index through `COALESCE((a = b), 0)`,
234
+ // turning every correlated EXISTS into a full scan per outer row (#625). The normalisation is kept
235
+ // wherever the value is *projected* (`filter === false`), so the TS/SQL 0/1 parity is unchanged.
236
+ const walk = (node, projTable, existsDepth, filter = false) => {
232
237
  switch (node.kind) {
233
238
  case "lit":
234
239
  return sqlLiteral(node.value);
@@ -247,16 +252,23 @@ export function compileToSqlSelect(expr, options = {}) {
247
252
  case "compare":
248
253
  // SQLite comparisons against NULL yield NULL, but the TS backend (compareValues) collapses any
249
254
  // nullish operand to `false`/0. COALESCE the SQL result to 0 so both backends agree on NULL inputs.
250
- return `COALESCE((${walk(node.left, projTable, existsDepth)} ${SQL_COMPARE[node.op]} ${walk(node.right, projTable, existsDepth)}), 0)`;
255
+ {
256
+ const cmp = `${walk(node.left, projTable, existsDepth)} ${SQL_COMPARE[node.op]} ${walk(node.right, projTable, existsDepth)}`;
257
+ return filter ? `(${cmp})` : `COALESCE((${cmp}), 0)`;
258
+ }
251
259
  case "and":
252
260
  // `NULL AND 0`/`NULL OR 0` can yield NULL in SQLite, but the TS backend coerces each clause through
253
261
  // `truthy(...)` (NULL → false), so COALESCE the boolean expression to 0 to keep the 0/1 domain aligned.
254
262
  return node.clauses.length
255
- ? `COALESCE((${node.clauses.map((c) => walk(c, projTable, existsDepth)).join(" AND ")}), 0)`
263
+ ? filter
264
+ ? `(${node.clauses.map((c) => walk(c, projTable, existsDepth, true)).join(" AND ")})`
265
+ : `COALESCE((${node.clauses.map((c) => walk(c, projTable, existsDepth)).join(" AND ")}), 0)`
256
266
  : "1";
257
267
  case "or":
258
268
  return node.clauses.length
259
- ? `COALESCE((${node.clauses.map((c) => walk(c, projTable, existsDepth)).join(" OR ")}), 0)`
269
+ ? filter
270
+ ? `(${node.clauses.map((c) => walk(c, projTable, existsDepth, true)).join(" OR ")})`
271
+ : `COALESCE((${node.clauses.map((c) => walk(c, projTable, existsDepth)).join(" OR ")}), 0)`
260
272
  : "0";
261
273
  case "not":
262
274
  // `NOT NULL` is NULL in SQLite, while the TS backend returns `!truthy(NULL)` → true. Compile as
@@ -267,7 +279,7 @@ export function compileToSqlSelect(expr, options = {}) {
267
279
  return `(${walk(node.expr, projTable, existsDepth)} IS NULL)`;
268
280
  case "case": {
269
281
  const whens = node.whens
270
- .map((w) => `WHEN ${walk(w.when, projTable, existsDepth)} THEN ${walk(w.then, projTable, existsDepth)}`)
282
+ .map((w) => `WHEN ${walk(w.when, projTable, existsDepth, true)} THEN ${walk(w.then, projTable, existsDepth)}`)
271
283
  .join(" ");
272
284
  return `CASE ${whens} ELSE ${walk(node.else, projTable, existsDepth)} END`;
273
285
  }
@@ -277,7 +289,7 @@ export function compileToSqlSelect(expr, options = {}) {
277
289
  // predicate always correlates to the OUTER base row (via `pcol` binds to this alias). The closed
278
290
  // AST keeps the correlation explicit and injection-free.
279
291
  const projAlias = projAliasAt(existsDepth);
280
- return `EXISTS (SELECT 1 FROM ${quoteIdent(table)} AS ${quoteIdent(projAlias)} WHERE ${walk(node.where, projAlias, existsDepth + 1)})`;
292
+ return `EXISTS (SELECT 1 FROM ${quoteIdent(table)} AS ${quoteIdent(projAlias)} WHERE ${walk(node.where, projAlias, existsDepth + 1, true)})`;
281
293
  }
282
294
  }
283
295
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nanobpm/urban",
3
- "version": "0.99.1",
3
+ "version": "0.99.2",
4
4
  "description": "Urban: build and run code-first apps on Nano — runtime, derivation toolkit, and CLI in one. Author durable processes with @nanobpm/workflow (defineFlow), a typed datasource, forms, triggers and surfaces from a nano.app.json manifest, on Node or Deno.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -332,7 +332,7 @@ test("EXISTS aliases the projection relation distinctly from the base alias so c
332
332
  baseAlias: "base",
333
333
  resolveProjectionTable: () => "base", // physical projection table collides with the base alias
334
334
  });
335
- assert.match(sql, /FROM "base" AS "__urban_proj_0" WHERE COALESCE\(\("__urban_proj_0"\."k" = "base"\."k"\), 0\)/);
335
+ assert.match(sql, /FROM "base" AS "__urban_proj_0" WHERE \("__urban_proj_0"\."k" = "base"\."k"\)\)/);
336
336
 
337
337
  // If the base alias IS the reserved alias itself, the projection alias is prefixed further so the two
338
338
  // stay distinct — the derivation is collision-free for any base alias.
@@ -340,7 +340,7 @@ test("EXISTS aliases the projection relation distinctly from the base alias so c
340
340
  baseAlias: "__urban_proj_0",
341
341
  resolveProjectionTable: () => "__urban_proj_0",
342
342
  });
343
- assert.match(collide, /FROM "__urban_proj_0" AS "___urban_proj_0" WHERE COALESCE\(\("___urban_proj_0"\."k" = "__urban_proj_0"\."k"\), 0\)/);
343
+ assert.match(collide, /FROM "__urban_proj_0" AS "___urban_proj_0" WHERE \("___urban_proj_0"\."k" = "__urban_proj_0"\."k"\)\)/);
344
344
  });
345
345
 
346
346
  test("projection alias avoids a base alias that collides only by case (SQLite idents are case-insensitive)", () => {
@@ -351,7 +351,7 @@ test("projection alias avoids a base alias that collides only by case (SQLite id
351
351
  baseAlias: "__URBAN_PROJ_0",
352
352
  resolveProjectionTable: () => "p",
353
353
  });
354
- assert.match(collide, /FROM "p" AS "___urban_proj_0" WHERE COALESCE\(\("___urban_proj_0"\."k" = "__URBAN_PROJ_0"\."k"\), 0\)/);
354
+ assert.match(collide, /FROM "p" AS "___urban_proj_0" WHERE \("___urban_proj_0"\."k" = "__URBAN_PROJ_0"\."k"\)\)/);
355
355
  });
356
356
 
357
357
  test("a base alias that is not a SQL identifier is rejected at compile time", () => {
@@ -368,7 +368,7 @@ test("nested EXISTS bind each pcol(...) to its own projection via depth-indexed
368
368
  // The outer projection is __urban_proj_0, the nested one __urban_proj_1 — so the inner pcol cannot
369
369
  // shadow the outer projection's row.
370
370
  assert.match(sql, /FROM "outer" AS "__urban_proj_0" WHERE/);
371
- assert.match(sql, /FROM "inner" AS "__urban_proj_1" WHERE COALESCE\(\("__urban_proj_1"\."ik" = "base"\."bk"\), 0\)/);
371
+ assert.match(sql, /FROM "inner" AS "__urban_proj_1" WHERE \("__urban_proj_1"\."ik" = "base"\."bk"\)\)/);
372
372
  assert.match(sql, /"__urban_proj_0"\."ok" = "base"\."bk"/);
373
373
  });
374
374
 
@@ -1035,3 +1035,57 @@ test("an invalid SQL identifier is rejected at declaration time (injection guard
1035
1035
  /invalid/,
1036
1036
  );
1037
1037
  });
1038
+
1039
+ // #625: a COALESCE-wrapped predicate inside an EXISTS WHERE defeats SQLite index use, so each outer row
1040
+ // full-scanned the projection. Guard the defect CLASS: every boolean-filter shape (compare, AND, OR,
1041
+ // nested) must let the correlated subquery SEARCH an index, never SCAN the projected table.
1042
+ test("EXISTS filter predicates are index-searchable (EXPLAIN QUERY PLAN never SCANs the projection)", async () => {
1043
+ const { DatabaseSync } = await import("node:sqlite");
1044
+ const db = new DatabaseSync(":memory:");
1045
+ try {
1046
+ db.exec(`CREATE TABLE base (pr_key TEXT, flag INTEGER);
1047
+ CREATE TABLE merges (pr_key TEXT, outcome TEXT);
1048
+ CREATE INDEX idx_merges_pr ON merges(pr_key);`);
1049
+ const predicates = [
1050
+ eq(pcol("pr_key"), col("pr_key")),
1051
+ and(eq(pcol("pr_key"), col("pr_key")), eq(pcol("outcome"), lit("merged"))),
1052
+ and(eq(pcol("pr_key"), col("pr_key")), or(eq(pcol("outcome"), lit("merged")), eq(pcol("outcome"), lit("closed")))),
1053
+ ];
1054
+ for (const where of predicates) {
1055
+ const derived = caseWhen([when(exists("merges", where), lit(1))], lit(0));
1056
+ const sql = `SELECT ${compileToSqlSelect(derived, { resolveProjectionTable: (n) => n })} AS v FROM base AS "base"`;
1057
+ const plan = db.prepare(`EXPLAIN QUERY PLAN ${sql}`).all().map((r) => String(r.detail));
1058
+ assert.ok(plan.some((d) => /SEARCH __urban_proj_0 USING (COVERING )?INDEX idx_merges_pr/.test(d)), `${sql}\n${plan.join("\n")}`);
1059
+ assert.ok(!plan.some((d) => /SCAN __urban_proj_0/.test(d)), `${sql}\n${plan.join("\n")}`);
1060
+ }
1061
+ } finally {
1062
+ db.close();
1063
+ }
1064
+ });
1065
+
1066
+ test("filter-context predicates keep NULL parity with the TS backend (NULL filters like false)", async () => {
1067
+ const model = defineReadModel({
1068
+ name: "filter_null_parity_read_model",
1069
+ baseTable: "fnp_rows",
1070
+ derive: {
1071
+ any_match: caseWhen(
1072
+ [when(exists("fnp_proj", and(eq(pcol("k"), col("k")), or(eq(pcol("o"), col("f")), not(eq(pcol("o"), lit("x")))))), lit(1))],
1073
+ lit(0),
1074
+ ),
1075
+ gated: caseWhen([when(and(eq(col("f"), lit("y")), gt(col("n"), lit(0))), lit("yes"))], lit("no")),
1076
+ gated_or: caseWhen([when(or(eq(col("f"), lit("y")), gt(col("n"), lit(0))), lit("yes"))], lit("no")),
1077
+ },
1078
+ });
1079
+ const proj = [{ k: "a", o: null }, { k: "a", o: "x" }, { k: "b", o: "y" }, { k: null, o: "z" }];
1080
+ await withDb((db) => {
1081
+ assert.doesNotThrow(() =>
1082
+ assertReadModelParity(model, db, [
1083
+ { baseRow: { k: null, f: null, n: null }, projections: { fnp_proj: proj } },
1084
+ { baseRow: { k: "a", f: null, n: 1 }, projections: { fnp_proj: proj } },
1085
+ { baseRow: { k: "a", f: "x", n: null }, projections: { fnp_proj: proj } },
1086
+ { baseRow: { k: "b", f: "y", n: 0 }, projections: { fnp_proj: proj } },
1087
+ { baseRow: { k: "c", f: "y", n: 2 }, projections: { fnp_proj: [] } },
1088
+ ]),
1089
+ );
1090
+ });
1091
+ });
@@ -383,7 +383,12 @@ export function compileToSqlSelect(expr: Expr, options: SqlCompileOptions = {}):
383
383
  return alias;
384
384
  };
385
385
 
386
- const walk = (node: Expr, projTable: string | undefined, existsDepth: number): string => {
386
+ // `filter` marks a pure boolean-filter position (an EXISTS `WHERE`, a CASE `WHEN`, or an AND/OR clause
387
+ // nested in one). There NULL already behaves like false, so the COALESCE 0/1 normalisation is
388
+ // semantically redundant — and harmful: SQLite cannot use an index through `COALESCE((a = b), 0)`,
389
+ // turning every correlated EXISTS into a full scan per outer row (#625). The normalisation is kept
390
+ // wherever the value is *projected* (`filter === false`), so the TS/SQL 0/1 parity is unchanged.
391
+ const walk = (node: Expr, projTable: string | undefined, existsDepth: number, filter = false): string => {
387
392
  switch (node.kind) {
388
393
  case "lit":
389
394
  return sqlLiteral(node.value);
@@ -402,16 +407,23 @@ export function compileToSqlSelect(expr: Expr, options: SqlCompileOptions = {}):
402
407
  case "compare":
403
408
  // SQLite comparisons against NULL yield NULL, but the TS backend (compareValues) collapses any
404
409
  // nullish operand to `false`/0. COALESCE the SQL result to 0 so both backends agree on NULL inputs.
405
- return `COALESCE((${walk(node.left, projTable, existsDepth)} ${SQL_COMPARE[node.op]} ${walk(node.right, projTable, existsDepth)}), 0)`;
410
+ {
411
+ const cmp = `${walk(node.left, projTable, existsDepth)} ${SQL_COMPARE[node.op]} ${walk(node.right, projTable, existsDepth)}`;
412
+ return filter ? `(${cmp})` : `COALESCE((${cmp}), 0)`;
413
+ }
406
414
  case "and":
407
415
  // `NULL AND 0`/`NULL OR 0` can yield NULL in SQLite, but the TS backend coerces each clause through
408
416
  // `truthy(...)` (NULL → false), so COALESCE the boolean expression to 0 to keep the 0/1 domain aligned.
409
417
  return node.clauses.length
410
- ? `COALESCE((${node.clauses.map((c) => walk(c, projTable, existsDepth)).join(" AND ")}), 0)`
418
+ ? filter
419
+ ? `(${node.clauses.map((c) => walk(c, projTable, existsDepth, true)).join(" AND ")})`
420
+ : `COALESCE((${node.clauses.map((c) => walk(c, projTable, existsDepth)).join(" AND ")}), 0)`
411
421
  : "1";
412
422
  case "or":
413
423
  return node.clauses.length
414
- ? `COALESCE((${node.clauses.map((c) => walk(c, projTable, existsDepth)).join(" OR ")}), 0)`
424
+ ? filter
425
+ ? `(${node.clauses.map((c) => walk(c, projTable, existsDepth, true)).join(" OR ")})`
426
+ : `COALESCE((${node.clauses.map((c) => walk(c, projTable, existsDepth)).join(" OR ")}), 0)`
415
427
  : "0";
416
428
  case "not":
417
429
  // `NOT NULL` is NULL in SQLite, while the TS backend returns `!truthy(NULL)` → true. Compile as
@@ -422,7 +434,7 @@ export function compileToSqlSelect(expr: Expr, options: SqlCompileOptions = {}):
422
434
  return `(${walk(node.expr, projTable, existsDepth)} IS NULL)`;
423
435
  case "case": {
424
436
  const whens = node.whens
425
- .map((w) => `WHEN ${walk(w.when, projTable, existsDepth)} THEN ${walk(w.then, projTable, existsDepth)}`)
437
+ .map((w) => `WHEN ${walk(w.when, projTable, existsDepth, true)} THEN ${walk(w.then, projTable, existsDepth)}`)
426
438
  .join(" ");
427
439
  return `CASE ${whens} ELSE ${walk(node.else, projTable, existsDepth)} END`;
428
440
  }
@@ -432,7 +444,7 @@ export function compileToSqlSelect(expr: Expr, options: SqlCompileOptions = {}):
432
444
  // predicate always correlates to the OUTER base row (via `pcol` binds to this alias). The closed
433
445
  // AST keeps the correlation explicit and injection-free.
434
446
  const projAlias = projAliasAt(existsDepth);
435
- return `EXISTS (SELECT 1 FROM ${quoteIdent(table)} AS ${quoteIdent(projAlias)} WHERE ${walk(node.where, projAlias, existsDepth + 1)})`;
447
+ return `EXISTS (SELECT 1 FROM ${quoteIdent(table)} AS ${quoteIdent(projAlias)} WHERE ${walk(node.where, projAlias, existsDepth + 1, true)})`;
436
448
  }
437
449
  }
438
450
  };