@dsqlbase/core 0.1.6 → 0.2.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 (134) hide show
  1. package/CHANGELOG.md +195 -0
  2. package/LICENSE +21 -0
  3. package/README.md +4 -0
  4. package/dist/definition/base.d.ts +50 -3
  5. package/dist/definition/base.d.ts.map +1 -1
  6. package/dist/definition/base.js +34 -1
  7. package/dist/definition/base.js.map +1 -1
  8. package/dist/definition/column.d.ts +87 -14
  9. package/dist/definition/column.d.ts.map +1 -1
  10. package/dist/definition/column.js +99 -5
  11. package/dist/definition/column.js.map +1 -1
  12. package/dist/definition/constraint.d.ts +16 -15
  13. package/dist/definition/constraint.d.ts.map +1 -1
  14. package/dist/definition/constraint.js +4 -1
  15. package/dist/definition/constraint.js.map +1 -1
  16. package/dist/definition/domain.d.ts +12 -8
  17. package/dist/definition/domain.d.ts.map +1 -1
  18. package/dist/definition/domain.js +10 -2
  19. package/dist/definition/domain.js.map +1 -1
  20. package/dist/definition/embedded.d.ts +131 -0
  21. package/dist/definition/embedded.d.ts.map +1 -0
  22. package/dist/definition/embedded.js +133 -0
  23. package/dist/definition/embedded.js.map +1 -0
  24. package/dist/definition/index.d.ts +7 -4
  25. package/dist/definition/index.d.ts.map +1 -1
  26. package/dist/definition/index.js +4 -1
  27. package/dist/definition/index.js.map +1 -1
  28. package/dist/definition/indexes.d.ts +49 -19
  29. package/dist/definition/indexes.d.ts.map +1 -1
  30. package/dist/definition/indexes.js +38 -9
  31. package/dist/definition/indexes.js.map +1 -1
  32. package/dist/definition/namespace.d.ts +2 -2
  33. package/dist/definition/namespace.d.ts.map +1 -1
  34. package/dist/definition/namespace.js.map +1 -1
  35. package/dist/definition/relations.d.ts +47 -15
  36. package/dist/definition/relations.d.ts.map +1 -1
  37. package/dist/definition/relations.js +17 -12
  38. package/dist/definition/relations.js.map +1 -1
  39. package/dist/definition/sequence.d.ts +4 -4
  40. package/dist/definition/sequence.d.ts.map +1 -1
  41. package/dist/definition/sequence.js.map +1 -1
  42. package/dist/definition/table.d.ts +118 -13
  43. package/dist/definition/table.d.ts.map +1 -1
  44. package/dist/definition/table.js +137 -4
  45. package/dist/definition/table.js.map +1 -1
  46. package/dist/definition/tenant.d.ts +50 -0
  47. package/dist/definition/tenant.d.ts.map +1 -0
  48. package/dist/definition/tenant.js +73 -0
  49. package/dist/definition/tenant.js.map +1 -0
  50. package/dist/definition/union.d.ts +84 -0
  51. package/dist/definition/union.d.ts.map +1 -0
  52. package/dist/definition/union.js +89 -0
  53. package/dist/definition/union.js.map +1 -0
  54. package/dist/definition/view.js.map +1 -1
  55. package/dist/index.d.ts +3 -3
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +2 -2
  58. package/dist/index.js.map +1 -1
  59. package/dist/runtime/base.d.ts +22 -4
  60. package/dist/runtime/base.d.ts.map +1 -1
  61. package/dist/runtime/base.js.map +1 -1
  62. package/dist/runtime/column.d.ts +54 -3
  63. package/dist/runtime/column.d.ts.map +1 -1
  64. package/dist/runtime/column.js +75 -7
  65. package/dist/runtime/column.js.map +1 -1
  66. package/dist/runtime/context.d.ts +30 -2
  67. package/dist/runtime/context.d.ts.map +1 -1
  68. package/dist/runtime/context.js +6 -0
  69. package/dist/runtime/context.js.map +1 -1
  70. package/dist/runtime/errors.d.ts +14 -0
  71. package/dist/runtime/errors.d.ts.map +1 -0
  72. package/dist/runtime/errors.js +19 -0
  73. package/dist/runtime/errors.js.map +1 -0
  74. package/dist/runtime/executor.d.ts +29 -1
  75. package/dist/runtime/executor.d.ts.map +1 -1
  76. package/dist/runtime/executor.js +23 -0
  77. package/dist/runtime/executor.js.map +1 -1
  78. package/dist/runtime/group.d.ts +54 -0
  79. package/dist/runtime/group.d.ts.map +1 -0
  80. package/dist/runtime/group.js +96 -0
  81. package/dist/runtime/group.js.map +1 -0
  82. package/dist/runtime/index.d.ts +9 -6
  83. package/dist/runtime/index.d.ts.map +1 -1
  84. package/dist/runtime/index.js +6 -3
  85. package/dist/runtime/index.js.map +1 -1
  86. package/dist/runtime/operation.d.ts +227 -29
  87. package/dist/runtime/operation.d.ts.map +1 -1
  88. package/dist/runtime/operation.js +525 -49
  89. package/dist/runtime/operation.js.map +1 -1
  90. package/dist/runtime/query.d.ts +102 -34
  91. package/dist/runtime/query.d.ts.map +1 -1
  92. package/dist/runtime/query.js +140 -31
  93. package/dist/runtime/query.js.map +1 -1
  94. package/dist/runtime/registry.d.ts +114 -4
  95. package/dist/runtime/registry.d.ts.map +1 -1
  96. package/dist/runtime/registry.js +366 -9
  97. package/dist/runtime/registry.js.map +1 -1
  98. package/dist/runtime/session.d.ts +10 -4
  99. package/dist/runtime/session.d.ts.map +1 -1
  100. package/dist/runtime/session.js.map +1 -1
  101. package/dist/runtime/table.d.ts +87 -8
  102. package/dist/runtime/table.d.ts.map +1 -1
  103. package/dist/runtime/table.js +142 -5
  104. package/dist/runtime/table.js.map +1 -1
  105. package/dist/runtime/union.d.ts +33 -0
  106. package/dist/runtime/union.d.ts.map +1 -0
  107. package/dist/runtime/union.js +69 -0
  108. package/dist/runtime/union.js.map +1 -0
  109. package/dist/sql/index.d.ts +1 -1
  110. package/dist/sql/index.d.ts.map +1 -1
  111. package/dist/sql/index.js.map +1 -1
  112. package/dist/sql/nodes.d.ts +33 -6
  113. package/dist/sql/nodes.d.ts.map +1 -1
  114. package/dist/sql/nodes.js +25 -0
  115. package/dist/sql/nodes.js.map +1 -1
  116. package/dist/sql/tag.d.ts +17 -0
  117. package/dist/sql/tag.d.ts.map +1 -1
  118. package/dist/sql/tag.js +95 -0
  119. package/dist/sql/tag.js.map +1 -1
  120. package/dist/sql/utils.d.ts +2 -2
  121. package/dist/sql/utils.d.ts.map +1 -1
  122. package/dist/sql/utils.js.map +1 -1
  123. package/dist/utils/index.d.ts +1 -1
  124. package/dist/utils/index.d.ts.map +1 -1
  125. package/dist/utils/index.js.map +1 -1
  126. package/dist/utils/thenable.js.map +1 -1
  127. package/dist/utils/types.d.ts +50 -2
  128. package/dist/utils/types.d.ts.map +1 -1
  129. package/dist/utils/types.js.map +1 -1
  130. package/package.json +27 -22
  131. package/dist/sql/expressions.d.ts +0 -25
  132. package/dist/sql/expressions.d.ts.map +0 -1
  133. package/dist/sql/expressions.js +0 -79
  134. package/dist/sql/expressions.js.map +0 -1
@@ -1,53 +1,222 @@
1
- import { Relation } from "../definition/index.js";
2
- import { sql, SQLIdentifier, SQLWrapper } from "../sql/index.js";
1
+ import { KEY_FIELD, META_FIELD, Relation } from "../definition/index.js";
2
+ import { SQLIdentifier, sql } from "../sql/index.js";
3
+ import { TenancyError } from "./errors.js";
4
+ import { Column } from "./column.js";
5
+ import { ColumnGroup } from "./group.js";
6
+ import { Union } from "./union.js";
7
+ /**
8
+ * How a level whose rows come from several tables is resolved: each row names its member in
9
+ * `$$key`, and that member's resolvers — `$$meta` included — produce the record.
10
+ *
11
+ * Dispatch decides *which* resolvers run for a row, so it happens before any field is read,
12
+ * not after (`docs/decisions/0004-record-meta.md`). A member with no branch here was excluded
13
+ * from the query, so a row naming it is a data-integrity failure and throws.
14
+ */
15
+ /**
16
+ * The field a union's primary-key tiebreaker is addressed by in its total order, followed by the
17
+ * key column's position. Members may name their key columns differently, so a tiebreaker is
18
+ * positional; `$` keeps it from ever meeting a real field.
19
+ */
20
+ const PK_FIELD_PREFIX = "$$pk";
21
+ export class UnionResolver {
22
+ mode;
23
+ branches;
24
+ constructor(mode, branches) {
25
+ this.mode = mode;
26
+ this.branches = Object.freeze({ ...branches });
27
+ }
28
+ }
3
29
  export class OperationsFactory {
4
30
  _ctx;
5
31
  constructor(ctx) {
6
32
  this._ctx = ctx;
7
33
  }
8
- _validateWhereExpression(table, where) {
9
- if (Array.isArray(where)) {
10
- return where[0];
34
+ /**
35
+ * The tenant boundary for `table`, as a condition, or `undefined` when there is none to apply.
36
+ *
37
+ * A table with no claim columns is global and always yields `undefined`. Otherwise the
38
+ * identity on the context decides: present, every claim becomes an equality on its column;
39
+ * absent, an enforcing context refuses to build the operation at all, and a non-enforcing one
40
+ * runs unscoped.
41
+ *
42
+ * The refusal is what makes this a boundary rather than a convenience. It fires here, below
43
+ * the point where callers write queries, so it also covers a tenant table reached through a
44
+ * join — which the types cannot see, because a nested level is named by a relation rather than
45
+ * by the client.
46
+ */
47
+ _tenantPredicate(table) {
48
+ if (table.tenantKeys.length === 0) {
49
+ return undefined;
50
+ }
51
+ const identity = this._ctx.identity;
52
+ if (!identity) {
53
+ if (!this._ctx.tenancy.enforce) {
54
+ return undefined;
55
+ }
56
+ throw new TenancyError(`Table "${table.name}" is tenant-scoped and this client carries no claims. ` +
57
+ `Derive one with $identityClaims(), or create the client with ` +
58
+ `tenancy: { enforce: false } if it is meant to run unscoped.`, table.name);
59
+ }
60
+ const conditions = table.tenantKeys.map(([claim, column]) => {
61
+ const value = identity[claim];
62
+ if (value === undefined || value === null) {
63
+ throw new TenancyError(`Table "${table.name}" is scoped by claim "${claim}", which this client's identity ` +
64
+ `does not carry.`, table.name, claim);
65
+ }
66
+ // Encoded by the column's own codec, so the predicate is written the way the column
67
+ // stored the value — the same rule every other comparison follows.
68
+ return sql.eq(column, column.param(value));
69
+ });
70
+ if (conditions.length === 1) {
71
+ return conditions[0];
72
+ }
73
+ return sql.and(conditions.map((condition) => sql.wrap(condition)));
74
+ }
75
+ /**
76
+ * The single place a `WHERE` is assembled, for every select — root and every nested join
77
+ * level — every update and every delete. It is called unconditionally, even when the caller
78
+ * passed no `where`, because this is the seam predicates are injected into: a rule that only
79
+ * ran when the caller happened to filter would not be a rule.
80
+ *
81
+ * Several nodes are AND-ed, each wrapped so an `OR` among them keeps its precedence. A lone
82
+ * node is returned untouched, so the common case adds no parentheses.
83
+ *
84
+ * The tenant predicate leads, before anything the caller wrote and before anything a sibling
85
+ * feature appends afterwards (a join correlation, a keyset). Order is cosmetic to the planner
86
+ * and deliberate to a reader: the boundary is the first thing an `EXPLAIN` shows.
87
+ */
88
+ _resolveWhere(table, where) {
89
+ const conditions = [
90
+ this._tenantPredicate(table),
91
+ ...(Array.isArray(where) ? where : [where]),
92
+ ].filter((condition) => condition !== undefined && condition !== null);
93
+ if (conditions.length === 0) {
94
+ return undefined;
11
95
  }
12
- return where;
96
+ if (conditions.length === 1) {
97
+ return conditions[0];
98
+ }
99
+ return sql.and(conditions.map((condition) => sql.wrap(condition)));
13
100
  }
14
101
  _validateOrderExpression(table, order) {
15
102
  return order;
16
103
  }
104
+ /**
105
+ * Resolvers for one level of a result — the top level of a select, a join level, or a
106
+ * `return` selection. Every level is built here, which is why stamping `$$meta` once at the
107
+ * top of this function reaches all of them.
108
+ *
109
+ * No selection projects every column; an empty one projects none.
110
+ */
17
111
  _resolveFields(table, selection) {
18
112
  const columns = [];
19
113
  const resolvers = [];
20
- if (!selection || selection.length === 0) {
21
- for (const [fieldName, column] of Object.entries(table.columns)) {
114
+ // First, so `$$meta` leads every record. Resolvers only — it projects no SQL.
115
+ resolvers.push([META_FIELD, () => table.meta]);
116
+ // A column with a row decoder reads siblings of its row: they are projected with it — once,
117
+ // however many columns need them — and the field is resolved from the whole row.
118
+ const add = (fieldName, column) => {
119
+ if (!columns.includes(column)) {
22
120
  columns.push(column);
121
+ }
122
+ if (!column.rowDecoder) {
23
123
  resolvers.push([fieldName, column]);
124
+ return;
125
+ }
126
+ for (const dependency of column.rowDecoder.dependsOn) {
127
+ if (!columns.includes(dependency)) {
128
+ columns.push(dependency);
129
+ }
130
+ }
131
+ resolvers.push([fieldName, (row) => column.resolveRow(row)]);
132
+ };
133
+ // A group projects its columns and is resolved from the row as one value — the group
134
+ // decides which columns that takes (`runtime/group.ts`).
135
+ const addGroup = (fieldName, group, members) => {
136
+ const reader = group.reader(members);
137
+ for (const column of reader.columns) {
138
+ if (!columns.includes(column)) {
139
+ columns.push(column);
140
+ }
141
+ }
142
+ resolvers.push([fieldName, (row) => reader.resolve(row)]);
143
+ };
144
+ const addField = (fieldName, field, members) => {
145
+ if (field instanceof ColumnGroup) {
146
+ addGroup(fieldName, field, members);
147
+ }
148
+ else {
149
+ add(fieldName, field);
150
+ }
151
+ };
152
+ if (!selection) {
153
+ for (const [fieldName, field] of Object.entries(table.columns)) {
154
+ addField(fieldName, field);
24
155
  }
25
156
  return { columns, resolvers };
26
157
  }
27
- for (const [fieldName, selected] of selection) {
158
+ for (const [fieldName, selected, members] of selection) {
28
159
  if (selected) {
29
- const column = table.columns[fieldName];
30
- if (!column) {
160
+ const field = table.columns[fieldName];
161
+ if (!field) {
31
162
  throw new Error(`Column "${fieldName}" does not exist on table "${table.name}"`);
32
163
  }
33
- columns.push(column);
34
- resolvers.push([fieldName, column]);
164
+ addField(fieldName, field, members);
35
165
  }
36
166
  }
37
167
  return { columns, resolvers };
38
168
  }
169
+ /**
170
+ * The value a tenant claim column is inserted with, taken from the identity.
171
+ *
172
+ * Always required, in both modes: the column is `notNull` and nothing else can fill it, so an
173
+ * insert without claims would write a row into no tenant. Moving a row between tenants is not
174
+ * a model-client operation — it is raw SQL on an unscoped client, deliberately.
175
+ */
176
+ _tenantValue(table, claim) {
177
+ const value = this._ctx.identity?.[claim];
178
+ if (value === undefined || value === null) {
179
+ throw new TenancyError(`Cannot insert into "${table.name}" without claim "${claim}": it is filled from the ` +
180
+ `client's identity, and this client carries none.`, table.name, claim);
181
+ }
182
+ return value;
183
+ }
184
+ /**
185
+ * The column a mutation sets: a plain column by its field, or a column given directly, which
186
+ * must be one of the table's own — a group's member.
187
+ */
188
+ _getMutationColumn(table, target) {
189
+ const column = typeof target === "string" ? table.getColumn(target) : target;
190
+ if (!(column instanceof Column) || column.table !== table) {
191
+ const name = typeof target === "string" ? target : target.name;
192
+ throw new Error(`Column "${name}" does not exist on table "${table.name}"`);
193
+ }
194
+ return column;
195
+ }
39
196
  _resolveInsertEntries(table, data) {
40
197
  const columns = [];
41
198
  const rows = [];
42
- const columnEntries = table.getColumnEntries();
199
+ // Every real column, a group's members included: one not written takes its default.
200
+ const columnEntries = table.getLeafEntries();
43
201
  for (const [, column] of columnEntries) {
44
202
  columns.push(new SQLIdentifier(column.name));
45
203
  }
46
204
  for (const record of data) {
47
205
  const row = [];
48
- const values = Object.fromEntries(record);
49
- for (const [fieldName, column] of columnEntries) {
50
- const value = column.getInsertValue(values[fieldName]);
206
+ const values = new Map();
207
+ for (const [target, value] of record) {
208
+ values.set(this._getMutationColumn(table, target), value);
209
+ }
210
+ for (const [path, column] of columnEntries) {
211
+ const fieldName = path.join(".");
212
+ if (column.readOnly && values.get(column) !== undefined) {
213
+ throw new Error(`Cannot write read-only column "${fieldName}"`);
214
+ }
215
+ if (column.tenantKey) {
216
+ row.push(column.getInsertValue(this._tenantValue(table, fieldName)));
217
+ continue;
218
+ }
219
+ const value = column.getInsertValue(values.get(column));
51
220
  row.push(value);
52
221
  }
53
222
  rows.push(row);
@@ -56,29 +225,48 @@ export class OperationsFactory {
56
225
  }
57
226
  _resolveUpdateEntries(table, data) {
58
227
  const entries = [];
59
- for (const [key, value] of data) {
60
- const column = table.getColumn(key);
61
- if (!column) {
62
- throw new Error(`Column "${key}" does not exist on table "${table.name}"`);
63
- }
228
+ const named = new Set();
229
+ for (const [target, value] of data) {
230
+ const column = this._getMutationColumn(table, target);
231
+ const key = typeof target === "string" ? target : column.name;
64
232
  if (column.primaryKey) {
65
233
  throw new Error(`Cannot update primary key column "${key}"`);
66
234
  }
235
+ if (column.readOnly) {
236
+ throw new Error(`Cannot write read-only column "${key}"`);
237
+ }
67
238
  const param = column.getUpdateValue(value);
68
239
  entries.push([new SQLIdentifier(column.name), param]);
240
+ named.add(column);
241
+ }
242
+ // `$onUpdate` runs on every update, not only when the caller names its column — the way
243
+ // `$onCreate` runs on every insert. A read-only column is written here too: the hook is the
244
+ // owner the caller is kept out for.
245
+ for (const [, column] of table.getLeafEntries()) {
246
+ if (column.onUpdate && !named.has(column)) {
247
+ entries.push([new SQLIdentifier(column.name), column.getUpdateValue(undefined)]);
248
+ }
69
249
  }
70
250
  return entries;
71
251
  }
72
- _resolveSelectParams(table, args, mode, resolvers = []) {
252
+ _resolveSelectParams(table, args, mode, resolvers = [],
253
+ /** The level is read as JSON (a join, a union branch): see `Column.textInJson`. */
254
+ json = false) {
73
255
  const fields = this._resolveFields(table, args.select);
74
256
  resolvers.push(...fields.resolvers);
75
- const where = args.where ? this._validateWhereExpression(table, args.where) : undefined;
257
+ const where = this._resolveWhere(table, args.where);
76
258
  const order = args.orderBy ? this._validateOrderExpression(table, args.orderBy) : undefined;
77
259
  const join = args.join ? this._resolveJoinEntries(table, args.join, resolvers) : undefined;
78
260
  const limit = mode === "one" ? 1 : args.limit;
261
+ // `::text` is the database's own rendering of the value, which a cursor carries verbatim —
262
+ // a decoded JS value may have lost precision the database still compares on.
263
+ const keys = (args.keys ?? []).map((column, index) => sql `${column}::text AS ${sql.identifier(`__k${index}`)}`);
264
+ const columns = json
265
+ ? fields.columns.map((column) => column.textInJson ? sql `${column}::text AS ${sql.identifier(column.name)}` : column)
266
+ : fields.columns;
79
267
  return {
80
268
  table,
81
- select: fields.columns,
269
+ select: [...columns, ...keys],
82
270
  distinct: args.distinct,
83
271
  where,
84
272
  order,
@@ -99,45 +287,266 @@ export class OperationsFactory {
99
287
  if (!relation) {
100
288
  throw new Error(`Relation "${fieldName}" does not exist on table "${table.name}"`);
101
289
  }
102
- const targetTable = this._ctx.schema.getRelationTarget(table.name, fieldName);
103
- if (!targetTable) {
104
- throw new Error(`Target table for relation "${key}" on table "${table.name}" not found in schema`);
290
+ const target = this._ctx.schema.getRelationTarget(table.name, fieldName);
291
+ const isUnionArgs = "members" in value;
292
+ if (target instanceof Union !== isUnionArgs) {
293
+ throw new Error(`Relation "${fieldName}" on table "${table.name}" targets ` +
294
+ (target instanceof Union ? `union "${target.alias}"` : `table "${target.name}"`) +
295
+ `, but was joined with arguments for ${isUnionArgs ? "a union" : "a table"}.`);
105
296
  }
106
- const fromColumn = table.getColumn(relation.from[0].name);
107
- const toColumn = targetTable.getColumn(relation.to[0].name);
108
- if (!fromColumn || !toColumn) {
109
- throw new Error(`Invalid relation "${key}" on table "${table.name}": missing columns "${relation.from[0].name}" or "${relation.to[0].name}"`);
297
+ if (target instanceof Union) {
298
+ const mode = relation.type === Relation.HAS_MANY ? "many" : "one";
299
+ const union = this._resolveUnionParams(target, value, mode, this._ctx.schema.getUnionRelationColumns(table.name, fieldName), this._ctx.schema.getRelationDiscriminator(table.name, fieldName));
300
+ resolvers.push([fieldName, union.resolver]);
301
+ // Every member pruned: no branch can match, so there is nothing to join. The resolver
302
+ // still answers `[]` or `null` for the field.
303
+ if (union.params.branches.length === 0) {
304
+ continue;
305
+ }
306
+ joins.push({
307
+ alias: fieldName,
308
+ type: mode,
309
+ from: this._resolveFromColumns(table, fieldName, relation.from),
310
+ union: union.params,
311
+ });
312
+ continue;
313
+ }
314
+ const tableArgs = value;
315
+ if (tableArgs.keys && tableArgs.keys.length > 0) {
316
+ throw new Error(`Relation "${fieldName}" on table "${table.name}" cannot project keyset keys: only ` +
317
+ `the root level of a select is keyset-ordered.`);
318
+ }
319
+ const targetTable = target;
320
+ if (relation.from.length === 0 || relation.from.length !== relation.to.length) {
321
+ throw new Error(`Relation "${fieldName}" on table "${table.name}" must pair an equal, non-zero ` +
322
+ `number of columns (got ${relation.from.length} from, ${relation.to.length} to)`);
110
323
  }
324
+ const fromColumns = this._resolveFromColumns(table, fieldName, relation.from);
325
+ const toColumns = relation.to.map((ref) => {
326
+ const column = targetTable.getColumn(ref.name);
327
+ if (!(column instanceof Column)) {
328
+ throw new Error(`Invalid relation "${fieldName}" on table "${table.name}": missing column "${ref.name}" on target table "${targetTable.name}"`);
329
+ }
330
+ return column;
331
+ });
111
332
  const joinResolvers = [];
112
- const params = this._resolveSelectParams(targetTable, value, relation.type === Relation.HAS_MANY ? "many" : "one", joinResolvers);
113
- const connection = relation.type === Relation.BELONGS_TO
114
- ? sql.eq(fromColumn, toColumn)
115
- : sql.eq(toColumn, fromColumn);
333
+ const params = this._resolveSelectParams(targetTable, tableArgs, relation.type === Relation.HAS_MANY ? "many" : "one", joinResolvers, true);
334
+ // The correlation itself is the query builder's business: only it knows the alias each
335
+ // level renders under, and a self-join needs the two sides aliased differently.
116
336
  joins.push({
117
337
  alias: fieldName,
118
338
  type: relation.type === "has_many" ? "many" : "one",
119
- from: fromColumn,
120
- to: toColumn,
121
- params: {
122
- ...params,
123
- where: params.where
124
- ? sql.and([
125
- connection,
126
- params.where instanceof SQLWrapper ? params.where : new SQLWrapper(params.where),
127
- ])
128
- : connection,
129
- },
339
+ from: fromColumns,
340
+ to: toColumns,
341
+ params,
130
342
  });
131
343
  resolvers.push([fieldName, joinResolvers]);
132
344
  }
133
345
  return joins;
134
346
  }
347
+ _resolveFromColumns(table, fieldName, from) {
348
+ return from.map((ref) => {
349
+ const column = table.getColumn(ref.name);
350
+ if (!(column instanceof Column)) {
351
+ throw new Error(`Invalid relation "${fieldName}" on table "${table.name}": missing column "${ref.name}"`);
352
+ }
353
+ return column;
354
+ });
355
+ }
356
+ /**
357
+ * Builds the branches of a select over a union, one per member in `args.members`, each
358
+ * through {@link _resolveSelectParams} with the member's own table — so every branch passes
359
+ * the `WHERE` seam, tenant predicate included, and gets nested joins and codec-aware filters
360
+ * exactly as a single-table level would. A branch cannot skip them, which is what keeps a
361
+ * union from becoming a way around a member's tenant boundary.
362
+ *
363
+ * Each branch also projects:
364
+ * - its alias as a `$$key` literal, which lands in the row's JSON and drives dispatch;
365
+ * - when ordered, every order key as `__o<n>`, since members may name the column differently;
366
+ * - when ordered and every member's primary key lines up (same arity, same types), those
367
+ * columns as `__pk<n>`, the tiebreakers after `$$key` that make the order total.
368
+ *
369
+ * With a `limit`, each branch is also ordered and limited to `limit + offset` rows. That is
370
+ * safe because every branch sorts by the same keys the combined rows are sorted by, so no
371
+ * row a branch drops could have made the combined page.
372
+ *
373
+ * `pairs` are the join's `to` columns per member; absent at the root of a query.
374
+ */
375
+ _resolveUnionParams(union, args, mode, pairs, discriminator) {
376
+ const orderBy = args.orderBy ?? [];
377
+ const paged = args.keys === true || args.keyset !== undefined;
378
+ const ordered = orderBy.length > 0 || paged;
379
+ const limit = mode === "one" ? 1 : args.limit;
380
+ const offset = mode === "one" ? undefined : args.offset;
381
+ for (const key of orderBy) {
382
+ if (key.field !== KEY_FIELD && !union.isShared(key.field)) {
383
+ throw new Error(`Cannot order union "${union.alias}" by "${key.field}": only fields every member ` +
384
+ `shares, and ${KEY_FIELD}, order across a union.`);
385
+ }
386
+ }
387
+ const tiebreakers = ordered ? union.tiebreakers : 0;
388
+ if (paged && tiebreakers === 0) {
389
+ throw new Error(`Cannot page union "${union.alias}": its members' primary keys differ in arity or type, ` +
390
+ `so nothing can break a tie between two members' rows.`);
391
+ }
392
+ const order = ordered ? this._getUnionOrder(orderBy, tiebreakers, args.tiebreak) : [];
393
+ const backward = args.keyset?.bound === "before";
394
+ // A page read before its cursor runs every key the other way round; the keyset itself is
395
+ // written against the order as given.
396
+ const direction = (key) => {
397
+ const way = backward ? (key.direction === "asc" ? "desc" : "asc") : key.direction;
398
+ const dir = way === "asc" ? "ASC" : "DESC";
399
+ if (!key.nullable) {
400
+ return dir;
401
+ }
402
+ return way === "asc" ? `${dir} NULLS LAST` : `${dir} NULLS FIRST`;
403
+ };
404
+ const branches = [];
405
+ const resolvers = {};
406
+ for (const [alias, memberArgs] of args.members) {
407
+ const member = union.getMember(alias);
408
+ const memberResolvers = [];
409
+ const expressions = order.map((key) => this._getUnionKeyExpression(union, alias, key));
410
+ // The branch's own order, used only when it is limited. `$$key` is a constant inside a
411
+ // branch, so it orders nothing there.
412
+ const branchOrder = limit !== undefined && ordered
413
+ ? order.flatMap((key, index) => key.field === KEY_FIELD ? [] : [sql `${expressions[index]} ${sql.raw(direction(key))}`])
414
+ : undefined;
415
+ const keyset = args.keyset
416
+ ? sql.keyset(order.map((key, index) => ({
417
+ node: expressions[index],
418
+ direction: key.direction,
419
+ nullable: key.nullable,
420
+ })), args.keyset.values, args.keyset.bound)
421
+ : undefined;
422
+ const params = this._resolveSelectParams(member, {
423
+ ...memberArgs,
424
+ where: [
425
+ ...(Array.isArray(memberArgs.where) ? memberArgs.where : [memberArgs.where]),
426
+ keyset,
427
+ ].filter((node) => node !== undefined && node !== null),
428
+ orderBy: branchOrder,
429
+ limit: limit !== undefined ? limit + (offset ?? 0) : undefined,
430
+ offset: undefined,
431
+ }, "many", memberResolvers, true);
432
+ params.select = [
433
+ sql `${sql.literal(alias)} AS ${sql.identifier(KEY_FIELD)}`,
434
+ ...params.select,
435
+ ...order.flatMap((key, index) => {
436
+ const hidden = this._getUnionKeyName(key, index);
437
+ return hidden === KEY_FIELD
438
+ ? []
439
+ : [sql `${expressions[index]} AS ${sql.identifier(hidden)}`];
440
+ }),
441
+ // `::text` for the same reason as a table's keys: a cursor carries the database's own
442
+ // rendering of each value.
443
+ ...(args.keys
444
+ ? expressions.map((expression, index) => sql `${expression}::text AS ${sql.identifier(`__k${index}`)}`)
445
+ : []),
446
+ ];
447
+ const { resolvers: branchResolvers, ...select } = params;
448
+ branches.push({
449
+ params: select,
450
+ to: pairs?.[alias],
451
+ // A belongs-to row names its member in the discriminator; only that member's branch may
452
+ // match it, whatever ids the other members hold.
453
+ correlate: discriminator ? [sql.eq(discriminator, sql.literal(alias))] : undefined,
454
+ });
455
+ resolvers[alias] = branchResolvers;
456
+ }
457
+ const carry = [
458
+ ...order.map((key, index) => this._getUnionKeyName(key, index)),
459
+ ...(args.keys ? order.map((_, index) => `__k${index}`) : []),
460
+ ];
461
+ return {
462
+ params: {
463
+ branches,
464
+ carry,
465
+ order: ordered
466
+ ? order.map((key, index) => sql `${sql.identifier(this._getUnionKeyName(key, index))} ${sql.raw(direction(key))}`)
467
+ : undefined,
468
+ limit,
469
+ offset,
470
+ },
471
+ resolver: new UnionResolver(mode, resolvers),
472
+ };
473
+ }
474
+ /**
475
+ * The total order of a union: the caller's keys, then `$$key` unless they named it, then
476
+ * every primary-key column when the members' keys line up. The appended keys run in
477
+ * `tiebreak` — ascending unless a pager asks otherwise.
478
+ *
479
+ * A primary-key tiebreaker is written as the field `$$pk<n>`: members may name their key
480
+ * columns differently, so it is addressed by position rather than by field.
481
+ */
482
+ _getUnionOrder(orderBy, tiebreakers, tiebreak = "asc") {
483
+ return [
484
+ ...orderBy,
485
+ ...(orderBy.some((key) => key.field === KEY_FIELD)
486
+ ? []
487
+ : [{ field: KEY_FIELD, direction: tiebreak }]),
488
+ ...Array.from({ length: tiebreakers }, (_, index) => ({
489
+ field: `${PK_FIELD_PREFIX}${index}`,
490
+ direction: tiebreak,
491
+ })),
492
+ ];
493
+ }
494
+ /** What one order key reads inside one member's branch. */
495
+ _getUnionKeyExpression(union, alias, key) {
496
+ if (key.field === KEY_FIELD) {
497
+ return sql.literal(alias);
498
+ }
499
+ if (key.field.startsWith(PK_FIELD_PREFIX)) {
500
+ return union.getMember(alias).primaryKey[Number(key.field.slice(PK_FIELD_PREFIX.length))];
501
+ }
502
+ return union.getMemberColumn(alias, key.field);
503
+ }
504
+ /**
505
+ * The name one order key is carried under to the union level: `"$$key"` for `$$key`, which
506
+ * every branch projects anyway, `__pk<n>` for a tiebreaker, `__o<n>` for a
507
+ * caller's key — its position, since members may name the column differently.
508
+ */
509
+ _getUnionKeyName(key, index) {
510
+ if (key.field === KEY_FIELD) {
511
+ return KEY_FIELD;
512
+ }
513
+ if (key.field.startsWith(PK_FIELD_PREFIX)) {
514
+ return `__pk${key.field.slice(PK_FIELD_PREFIX.length)}`;
515
+ }
516
+ return `__o${index}`;
517
+ }
518
+ /** Resolves the rows of a union level, each by the member its `$$key` names. */
519
+ _resolveUnionRows(node, value) {
520
+ if (value === undefined || value === null) {
521
+ return node.mode === "many" ? [] : null;
522
+ }
523
+ const rows = (Array.isArray(value) ? value : [value]);
524
+ const results = rows.map((row) => {
525
+ const key = row[KEY_FIELD];
526
+ const resolvers = node.branches[key];
527
+ if (!resolvers) {
528
+ throw new Error(`A union row names member "${String(key)}", which this query did not select ` +
529
+ `(selected: ${Object.keys(node.branches).join(", ") || "none"}).`);
530
+ }
531
+ const record = this._createResultResolver(resolvers, "one")([row]);
532
+ return { [KEY_FIELD]: key, ...record };
533
+ });
534
+ return node.mode === "many" ? results : (results[0] ?? null);
535
+ }
135
536
  _createResultResolver(resolvers, mode) {
136
537
  return (rows) => {
137
538
  const results = [];
138
539
  for (const row of rows) {
139
540
  const result = {};
140
541
  for (const [fieldName, resolver] of resolvers) {
542
+ if (typeof resolver === "function") {
543
+ result[fieldName] = resolver(row);
544
+ continue;
545
+ }
546
+ if (resolver instanceof UnionResolver) {
547
+ result[fieldName] = this._resolveUnionRows(resolver, row[fieldName]);
548
+ continue;
549
+ }
141
550
  if (Array.isArray(resolver)) {
142
551
  const nestedRows = row[fieldName];
143
552
  if (typeof nestedRows === "undefined" || nestedRows === null) {
@@ -171,6 +580,73 @@ export class OperationsFactory {
171
580
  resolve: this._createResultResolver(fieldResolvers, mode),
172
581
  };
173
582
  }
583
+ /**
584
+ * `SELECT count(*)` over `table`, filtered by `where` through the same seam as every select,
585
+ * so an injected predicate bounds the count exactly as it bounds the rows.
586
+ */
587
+ createCountOperation(table, config) {
588
+ const { name, args } = config;
589
+ const query = this._ctx.dialect.buildSelectQuery({
590
+ table,
591
+ select: [sql `count(*) AS ${sql.identifier("count")}`],
592
+ where: this._resolveWhere(table, args.where),
593
+ });
594
+ return {
595
+ type: "select",
596
+ mode: "one",
597
+ name: name ?? `count_${table.name}`,
598
+ args,
599
+ query: query.toQuery(),
600
+ // `count(*)` is a `bigint`, which drivers hand back as text (node-postgres) or `bigint`.
601
+ resolve: (rows) => Number(rows[0]?.count ?? 0),
602
+ };
603
+ }
604
+ /**
605
+ * A top-level select over a union: the union's own `UNION ALL`, each row a JSON `data` value
606
+ * dispatched to its member's resolvers. With no member left to run it reads nothing, and
607
+ * resolves to `[]` or `null`.
608
+ */
609
+ createUnionSelectOperation(union, config) {
610
+ const { name, args, mode } = config;
611
+ const { params, resolver } = this._resolveUnionParams(union, args, mode);
612
+ const query = params.branches.length > 0
613
+ ? this._ctx.dialect.buildUnionSelectQuery(params)
614
+ : sql `SELECT NULL::json AS ${sql.identifier("data")} WHERE false`;
615
+ return {
616
+ type: "select",
617
+ mode,
618
+ name: name ?? `select_${union.alias}`,
619
+ args,
620
+ query: query.toQuery(),
621
+ resolve: (rows) => this._resolveUnionRows(resolver, rows.map((row) => row.data)),
622
+ };
623
+ }
624
+ /**
625
+ * Counts the rows a union's members select: one `count(*)` per member, each through the
626
+ * `WHERE` seam with that member's own table, added together.
627
+ */
628
+ createUnionCountOperation(union, config) {
629
+ const { name, args } = config;
630
+ const counts = args.members.map(([alias, memberArgs]) => {
631
+ const member = union.getMember(alias);
632
+ const query = this._ctx.dialect.buildSelectQuery({
633
+ table: member,
634
+ select: [sql `count(*)`],
635
+ where: this._resolveWhere(member, memberArgs.where),
636
+ });
637
+ return sql `(${query})`;
638
+ });
639
+ const total = counts.length > 0 ? sql.join(counts, " + ") : sql.raw("0");
640
+ const query = sql `SELECT ${total} AS ${sql.identifier("count")}`;
641
+ return {
642
+ type: "select",
643
+ mode: "one",
644
+ name: name ?? `count_${union.alias}`,
645
+ args,
646
+ query: query.toQuery(),
647
+ resolve: (rows) => Number(rows[0]?.count ?? 0),
648
+ };
649
+ }
174
650
  createInsertOperation(table, config) {
175
651
  const { name, args, mode } = config;
176
652
  const [columns, values] = this._resolveInsertEntries(table, args.data);
@@ -193,7 +669,7 @@ export class OperationsFactory {
193
669
  createUpdateOperation(table, config) {
194
670
  const { name, args, mode } = config;
195
671
  const entries = this._resolveUpdateEntries(table, args.set);
196
- const where = args.where ? this._validateWhereExpression(table, args.where) : undefined;
672
+ const where = this._resolveWhere(table, args.where);
197
673
  const selection = this._resolveFields(table, args.return);
198
674
  const query = this._ctx.dialect.buildUpdateQuery({
199
675
  table,
@@ -212,7 +688,7 @@ export class OperationsFactory {
212
688
  }
213
689
  createDeleteOperation(table, config) {
214
690
  const { name, args, mode } = config;
215
- const where = args.where ? this._validateWhereExpression(table, args.where) : undefined;
691
+ const where = this._resolveWhere(table, args.where);
216
692
  const selection = this._resolveFields(table, args.return);
217
693
  const query = this._ctx.dialect.buildDeleteQuery({
218
694
  table,