@dsqlbase/core 0.2.1 → 0.3.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 (164) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/definition/base.d.ts +3 -30
  3. package/dist/definition/base.d.ts.map +1 -1
  4. package/dist/definition/base.js +3 -14
  5. package/dist/definition/base.js.map +1 -1
  6. package/dist/definition/column.d.ts +22 -14
  7. package/dist/definition/column.d.ts.map +1 -1
  8. package/dist/definition/column.js +11 -37
  9. package/dist/definition/column.js.map +1 -1
  10. package/dist/definition/constraint.d.ts +9 -9
  11. package/dist/definition/constraint.d.ts.map +1 -1
  12. package/dist/definition/constraint.js.map +1 -1
  13. package/dist/definition/domain.d.ts +2 -1
  14. package/dist/definition/domain.d.ts.map +1 -1
  15. package/dist/definition/domain.js +2 -1
  16. package/dist/definition/domain.js.map +1 -1
  17. package/dist/definition/index.d.ts +5 -6
  18. package/dist/definition/index.d.ts.map +1 -1
  19. package/dist/definition/index.js +3 -4
  20. package/dist/definition/index.js.map +1 -1
  21. package/dist/definition/indexes.d.ts +9 -20
  22. package/dist/definition/indexes.d.ts.map +1 -1
  23. package/dist/definition/indexes.js +3 -6
  24. package/dist/definition/indexes.js.map +1 -1
  25. package/dist/definition/namespace.d.ts +2 -2
  26. package/dist/definition/namespace.d.ts.map +1 -1
  27. package/dist/definition/namespace.js.map +1 -1
  28. package/dist/definition/policy.d.ts +35 -0
  29. package/dist/definition/policy.d.ts.map +1 -0
  30. package/dist/definition/policy.js +42 -0
  31. package/dist/definition/policy.js.map +1 -0
  32. package/dist/definition/relations.d.ts +28 -33
  33. package/dist/definition/relations.d.ts.map +1 -1
  34. package/dist/definition/relations.js +1 -4
  35. package/dist/definition/relations.js.map +1 -1
  36. package/dist/definition/table.d.ts +39 -32
  37. package/dist/definition/table.d.ts.map +1 -1
  38. package/dist/definition/table.js +57 -67
  39. package/dist/definition/table.js.map +1 -1
  40. package/dist/definition/union.d.ts +18 -61
  41. package/dist/definition/union.d.ts.map +1 -1
  42. package/dist/definition/union.js +8 -69
  43. package/dist/definition/union.js.map +1 -1
  44. package/dist/index.d.ts +5 -3
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +5 -3
  47. package/dist/index.js.map +1 -1
  48. package/dist/resolvers/codec.d.ts +16 -0
  49. package/dist/resolvers/codec.d.ts.map +1 -0
  50. package/dist/resolvers/codec.js +9 -0
  51. package/dist/resolvers/codec.js.map +1 -0
  52. package/dist/resolvers/hooks.d.ts +39 -0
  53. package/dist/resolvers/hooks.d.ts.map +1 -0
  54. package/dist/resolvers/hooks.js +2 -0
  55. package/dist/resolvers/hooks.js.map +1 -0
  56. package/dist/resolvers/index.d.ts +5 -0
  57. package/dist/resolvers/index.d.ts.map +1 -0
  58. package/dist/resolvers/index.js +2 -0
  59. package/dist/resolvers/index.js.map +1 -0
  60. package/dist/resolvers/policy.d.ts +31 -0
  61. package/dist/resolvers/policy.d.ts.map +1 -0
  62. package/dist/resolvers/policy.js +2 -0
  63. package/dist/resolvers/policy.js.map +1 -0
  64. package/dist/resolvers/validator.d.ts +14 -0
  65. package/dist/resolvers/validator.d.ts.map +1 -0
  66. package/dist/resolvers/validator.js +2 -0
  67. package/dist/resolvers/validator.js.map +1 -0
  68. package/dist/runtime/base.d.ts +7 -4
  69. package/dist/runtime/base.d.ts.map +1 -1
  70. package/dist/runtime/base.js.map +1 -1
  71. package/dist/runtime/build.d.ts +22 -0
  72. package/dist/runtime/build.d.ts.map +1 -0
  73. package/dist/runtime/build.js +184 -0
  74. package/dist/runtime/build.js.map +1 -0
  75. package/dist/runtime/column.d.ts +40 -23
  76. package/dist/runtime/column.d.ts.map +1 -1
  77. package/dist/runtime/column.js +120 -28
  78. package/dist/runtime/column.js.map +1 -1
  79. package/dist/runtime/context.d.ts +17 -26
  80. package/dist/runtime/context.d.ts.map +1 -1
  81. package/dist/runtime/context.js +4 -6
  82. package/dist/runtime/context.js.map +1 -1
  83. package/dist/runtime/errors.d.ts +31 -9
  84. package/dist/runtime/errors.d.ts.map +1 -1
  85. package/dist/runtime/errors.js +54 -11
  86. package/dist/runtime/errors.js.map +1 -1
  87. package/dist/runtime/executor.d.ts.map +1 -1
  88. package/dist/runtime/executor.js +10 -1
  89. package/dist/runtime/executor.js.map +1 -1
  90. package/dist/runtime/index.d.ts +10 -6
  91. package/dist/runtime/index.d.ts.map +1 -1
  92. package/dist/runtime/index.js +5 -3
  93. package/dist/runtime/index.js.map +1 -1
  94. package/dist/runtime/operation.d.ts +62 -83
  95. package/dist/runtime/operation.d.ts.map +1 -1
  96. package/dist/runtime/operation.js +194 -260
  97. package/dist/runtime/operation.js.map +1 -1
  98. package/dist/runtime/policy.d.ts +35 -0
  99. package/dist/runtime/policy.d.ts.map +1 -0
  100. package/dist/runtime/policy.js +72 -0
  101. package/dist/runtime/policy.js.map +1 -0
  102. package/dist/runtime/reference.d.ts +87 -0
  103. package/dist/runtime/reference.d.ts.map +1 -0
  104. package/dist/runtime/reference.js +68 -0
  105. package/dist/runtime/reference.js.map +1 -0
  106. package/dist/runtime/registry.d.ts +26 -95
  107. package/dist/runtime/registry.d.ts.map +1 -1
  108. package/dist/runtime/registry.js +29 -408
  109. package/dist/runtime/registry.js.map +1 -1
  110. package/dist/runtime/relation.d.ts +45 -0
  111. package/dist/runtime/relation.d.ts.map +1 -0
  112. package/dist/runtime/relation.js +2 -0
  113. package/dist/runtime/relation.js.map +1 -0
  114. package/dist/runtime/table.d.ts +31 -35
  115. package/dist/runtime/table.d.ts.map +1 -1
  116. package/dist/runtime/table.js +78 -47
  117. package/dist/runtime/table.js.map +1 -1
  118. package/dist/runtime/union.d.ts +11 -4
  119. package/dist/runtime/union.d.ts.map +1 -1
  120. package/dist/runtime/union.js +18 -7
  121. package/dist/runtime/union.js.map +1 -1
  122. package/dist/sql/index.d.ts +2 -2
  123. package/dist/sql/index.d.ts.map +1 -1
  124. package/dist/sql/index.js +1 -1
  125. package/dist/sql/index.js.map +1 -1
  126. package/dist/sql/nodes.d.ts +22 -0
  127. package/dist/sql/nodes.d.ts.map +1 -1
  128. package/dist/sql/nodes.js +21 -0
  129. package/dist/sql/nodes.js.map +1 -1
  130. package/dist/sql/tag.d.ts +3 -15
  131. package/dist/sql/tag.d.ts.map +1 -1
  132. package/dist/sql/tag.js +5 -71
  133. package/dist/sql/tag.js.map +1 -1
  134. package/dist/utils/index.d.ts +1 -1
  135. package/dist/utils/index.d.ts.map +1 -1
  136. package/dist/utils/index.js.map +1 -1
  137. package/dist/utils/types.d.ts +2 -14
  138. package/dist/utils/types.d.ts.map +1 -1
  139. package/dist/utils/types.js.map +1 -1
  140. package/dist/validation/index.d.ts +2 -0
  141. package/dist/validation/index.d.ts.map +1 -0
  142. package/dist/validation/index.js +2 -0
  143. package/dist/validation/index.js.map +1 -0
  144. package/dist/validation/references.d.ts +23 -0
  145. package/dist/validation/references.d.ts.map +1 -0
  146. package/dist/validation/references.js +240 -0
  147. package/dist/validation/references.js.map +1 -0
  148. package/dist/validation/validate.d.ts +40 -0
  149. package/dist/validation/validate.d.ts.map +1 -0
  150. package/dist/validation/validate.js +354 -0
  151. package/dist/validation/validate.js.map +1 -0
  152. package/package.json +13 -4
  153. package/dist/definition/embedded.d.ts +0 -131
  154. package/dist/definition/embedded.d.ts.map +0 -1
  155. package/dist/definition/embedded.js +0 -133
  156. package/dist/definition/embedded.js.map +0 -1
  157. package/dist/definition/tenant.d.ts +0 -50
  158. package/dist/definition/tenant.d.ts.map +0 -1
  159. package/dist/definition/tenant.js +0 -73
  160. package/dist/definition/tenant.js.map +0 -1
  161. package/dist/runtime/group.d.ts +0 -54
  162. package/dist/runtime/group.d.ts.map +0 -1
  163. package/dist/runtime/group.js +0 -96
  164. package/dist/runtime/group.js.map +0 -1
@@ -1,9 +1,7 @@
1
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";
2
+ import { SQLIdentifier, isSQLNode, sql, } from "../sql/index.js";
4
3
  import { Column } from "./column.js";
5
- import { ColumnGroup } from "./group.js";
6
- import { Union } from "./union.js";
4
+ import { ComputedDiscriminator } from "./reference.js";
7
5
  /**
8
6
  * How a level whose rows come from several tables is resolved: each row names its member in
9
7
  * `$$key`, and that member's resolvers — `$$meta` included — produce the record.
@@ -31,46 +29,82 @@ export class OperationsFactory {
31
29
  constructor(ctx) {
32
30
  this._ctx = ctx;
33
31
  }
32
+ /** Renders a statement with this context's settings, so every setting binds its value. */
33
+ _render(query) {
34
+ return query.toQuery({ claims: this._ctx.settings });
35
+ }
34
36
  /**
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.
37
+ * The rows `table`'s policies let every one of `commands` see, as a condition, or `undefined`
38
+ * when the table has none. Per command that is `(OR of permissive using) AND (each restrictive
39
+ * using)`, each part wrapped; with no permissive policy for a command its part is `false` — a
40
+ * table with any policy denies by default. Several commands (a write and `select`) are AND-ed,
41
+ * a policy that applies to more than one of them rendered once.
41
42
  *
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.
43
+ * A setting a policy reads renders `NULL` when unset, and a comparison with `NULL` is never
44
+ * true: a restrictive policy hides every row, a permissive one drops only its own branch.
46
45
  */
47
- _tenantPredicate(table) {
48
- if (table.tenantKeys.length === 0) {
46
+ _policyPredicate(table, commands) {
47
+ if (!table.hasPolicies() || this._ctx.policies.bypass) {
49
48
  return undefined;
50
49
  }
51
- const identity = this._ctx.identity;
52
- if (!identity) {
53
- if (!this._ctx.tenancy.enforce) {
54
- return undefined;
50
+ const parts = [];
51
+ const permissiveSets = new Set();
52
+ const restrictive = new Set();
53
+ const using = (policy) => policy.using;
54
+ for (const command of commands) {
55
+ const policies = table.getPolicies(command);
56
+ const permissive = policies.filter((policy) => policy.as === "permissive");
57
+ const key = permissive.map((policy) => policy.name).join(",");
58
+ if (!permissiveSets.has(key)) {
59
+ permissiveSets.add(key);
60
+ parts.push(permissive.length === 0
61
+ ? sql.raw("false")
62
+ : permissive.length === 1
63
+ ? using(permissive[0])
64
+ : sql.or(permissive.map((policy) => sql.wrap(using(policy)))));
65
+ }
66
+ for (const policy of policies.filter((policy) => policy.as === "restrictive")) {
67
+ restrictive.add(policy);
55
68
  }
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
69
  }
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);
70
+ parts.push(...[...restrictive].map(using));
71
+ // A lone condition stays bare, like a lone `where`; several are each wrapped.
72
+ return parts.length === 1 ? parts[0] : sql.and(parts.map((part) => sql.wrap(part)));
73
+ }
74
+ /**
75
+ * The check every row an insert or update writes must pass, as a `RETURNING` expression, or
76
+ * `undefined` when the table has no policies. One `CASE` arm per restrictive policy, then one
77
+ * for the permissive policies OR-ed; the first that fails casts its marker to `int`, which
78
+ * fails the statement — atomically, nothing written — with the marker in the message, for
79
+ * {@link PolicyViolationError} to decode. Passing rows give `NULL`.
80
+ *
81
+ * `COALESCE(…, false)` makes a `NULL` check (an unset setting) fail rather than pass. Each
82
+ * marker is suffixed with `left(<column>::text, 0)` — always empty, never `NULL` through
83
+ * `coalesce` — so it depends on the row: a check over parameters alone would otherwise be
84
+ * folded at plan time and fail an update that matched nothing.
85
+ */
86
+ _policyCheck(table, command) {
87
+ if (!table.hasPolicies() || this._ctx.policies.bypass) {
88
+ return undefined;
89
+ }
90
+ const anchor = (table.primaryKey[0] ?? table.getColumnEntries()[0]?.[1]);
91
+ const suffix = sql `coalesce(left(${anchor}::text, 0), '')`;
92
+ const marker = (as, names) => sql `${sql.literal(`dsqlbase.policy:${table.alias}:${as}:${names.join(",")}`)} || ${suffix}`;
93
+ const check = (policy) => sql.wrap(policy.check);
94
+ const arms = [];
95
+ const permissive = [];
96
+ for (const policy of table.getPolicies(command)) {
97
+ if (policy.as === "restrictive") {
98
+ arms.push(sql `WHEN NOT COALESCE(${check(policy)}, false) THEN ${marker("restrictive", [policy.name])}`);
99
+ }
100
+ else {
101
+ permissive.push(policy);
65
102
  }
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
103
  }
73
- return sql.and(conditions.map((condition) => sql.wrap(condition)));
104
+ arms.push(permissive.length === 0
105
+ ? sql `WHEN true THEN ${marker("permissive", [])}`
106
+ : sql `WHEN NOT COALESCE(${sql.or(permissive.map(check))}, false) THEN ${marker("permissive", permissive.map((policy) => policy.name))}`);
107
+ return sql `CAST(CASE ${sql.join(arms, " ")} ELSE NULL END AS int) AS ${sql.identifier("__pc")}`;
74
108
  }
75
109
  /**
76
110
  * The single place a `WHERE` is assembled, for every select — root and every nested join
@@ -81,13 +115,17 @@ export class OperationsFactory {
81
115
  * Several nodes are AND-ed, each wrapped so an `OR` among them keeps its precedence. A lone
82
116
  * node is returned untouched, so the common case adds no parentheses.
83
117
  *
84
- * The tenant predicate leads, before anything the caller wrote and before anything a sibling
118
+ * `commands` names the row policies that bound the rows: `select` for every read level,
119
+ * `update` / `delete` and `select` for a write — as in PostgreSQL, a write only reaches rows
120
+ * its reader could see.
121
+ *
122
+ * What the seam injects leads, before anything the caller wrote and before anything a sibling
85
123
  * feature appends afterwards (a join correlation, a keyset). Order is cosmetic to the planner
86
124
  * and deliberate to a reader: the boundary is the first thing an `EXPLAIN` shows.
87
125
  */
88
- _resolveWhere(table, where) {
126
+ _resolveWhere(table, commands, where) {
89
127
  const conditions = [
90
- this._tenantPredicate(table),
128
+ this._policyPredicate(table, commands),
91
129
  ...(Array.isArray(where) ? where : [where]),
92
130
  ].filter((condition) => condition !== undefined && condition !== null);
93
131
  if (conditions.length === 0) {
@@ -98,7 +136,30 @@ export class OperationsFactory {
98
136
  }
99
137
  return sql.and(conditions.map((condition) => sql.wrap(condition)));
100
138
  }
101
- _validateOrderExpression(table, order) {
139
+ _resolveOrderEntries(table, entries) {
140
+ const order = [];
141
+ for (const [fieldName, [direction, nulls]] of entries) {
142
+ let column = table.getColumn(fieldName);
143
+ if (!column) {
144
+ column = isSQLNode(fieldName) ? fieldName : sql.identifier(fieldName);
145
+ }
146
+ const item = sql `${column} ${sql.raw(direction.toUpperCase())}`;
147
+ if (nulls) {
148
+ item.append(sql ` NULLS ${sql.raw(nulls.toUpperCase())}`);
149
+ }
150
+ order.push(item);
151
+ }
152
+ return order;
153
+ }
154
+ _resolveUnionOrderEntries(entries) {
155
+ const order = [];
156
+ for (const [key, [direction, nulls]] of entries) {
157
+ const item = sql `${sql.identifier(key)} ${sql.raw(direction.toUpperCase())}`;
158
+ if (nulls) {
159
+ item.append(sql ` NULLS ${sql.raw(nulls.toUpperCase())}`);
160
+ }
161
+ order.push(item);
162
+ }
102
163
  return order;
103
164
  }
104
165
  /**
@@ -108,116 +169,58 @@ export class OperationsFactory {
108
169
  *
109
170
  * No selection projects every column; an empty one projects none.
110
171
  */
111
- _resolveFields(table, selection) {
172
+ _resolveFields(table, selection, initialResolvers = []) {
173
+ // A computed discriminator is projected as its aliased expression.
112
174
  const columns = [];
113
- const resolvers = [];
175
+ const seen = new Set();
176
+ const resolvers = [...initialResolvers];
114
177
  // 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.
178
+ resolvers.push([META_FIELD, { resolve: () => table.meta }]);
179
+ // A column's dependencies — the discriminator of a union reference — are projected with it,
180
+ // once however many columns need them. A column's `read` hook finds them in the row it is
181
+ // handed.
118
182
  const add = (fieldName, column) => {
119
- if (!columns.includes(column)) {
120
- columns.push(column);
121
- }
122
- if (!column.rowDecoder) {
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);
183
+ for (const projected of [column, ...column.dependsOn]) {
184
+ if (seen.has(projected)) {
185
+ continue;
140
186
  }
187
+ seen.add(projected);
188
+ columns.push(projected instanceof ComputedDiscriminator ? projected.projection() : projected);
141
189
  }
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
- }
190
+ resolvers.push([fieldName, column]);
151
191
  };
152
192
  if (!selection) {
153
- for (const [fieldName, field] of Object.entries(table.columns)) {
154
- addField(fieldName, field);
193
+ for (const [fieldName, column] of Object.entries(table.columns)) {
194
+ add(fieldName, column);
155
195
  }
156
196
  return { columns, resolvers };
157
197
  }
158
- for (const [fieldName, selected, members] of selection) {
198
+ for (const [fieldName, selected] of selection) {
159
199
  if (selected) {
160
- const field = table.columns[fieldName];
161
- if (!field) {
200
+ const column = table.columns[fieldName];
201
+ if (!column) {
162
202
  throw new Error(`Column "${fieldName}" does not exist on table "${table.name}"`);
163
203
  }
164
- addField(fieldName, field, members);
204
+ add(fieldName, column);
165
205
  }
166
206
  }
167
207
  return { columns, resolvers };
168
208
  }
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
- }
196
209
  _resolveInsertEntries(table, data) {
197
210
  const columns = [];
198
211
  const rows = [];
199
- // Every real column, a group's members included: one not written takes its default.
200
- const columnEntries = table.getLeafEntries();
212
+ const columnEntries = table.getColumnEntries();
201
213
  for (const [, column] of columnEntries) {
202
214
  columns.push(new SQLIdentifier(column.name));
203
215
  }
204
216
  for (const record of data) {
205
217
  const row = [];
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) {
218
+ const values = Object.fromEntries(record);
219
+ for (const [fieldName, column] of columnEntries) {
220
+ if (column.readOnly && values[fieldName] !== undefined) {
213
221
  throw new Error(`Cannot write read-only column "${fieldName}"`);
214
222
  }
215
- if (column.tenantKey) {
216
- row.push(column.getInsertValue(this._tenantValue(table, fieldName)));
217
- continue;
218
- }
219
- const value = column.getInsertValue(values.get(column));
220
- row.push(value);
223
+ row.push(column.getInsertValue(values[fieldName]));
221
224
  }
222
225
  rows.push(row);
223
226
  }
@@ -226,9 +229,11 @@ export class OperationsFactory {
226
229
  _resolveUpdateEntries(table, data) {
227
230
  const entries = [];
228
231
  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;
232
+ for (const [key, value] of data) {
233
+ const column = table.getColumn(key);
234
+ if (!column) {
235
+ throw new Error(`Column "${key}" does not exist on table "${table.name}"`);
236
+ }
232
237
  if (column.primaryKey) {
233
238
  throw new Error(`Cannot update primary key column "${key}"`);
234
239
  }
@@ -242,7 +247,7 @@ export class OperationsFactory {
242
247
  // `$onUpdate` runs on every update, not only when the caller names its column — the way
243
248
  // `$onCreate` runs on every insert. A read-only column is written here too: the hook is the
244
249
  // owner the caller is kept out for.
245
- for (const [, column] of table.getLeafEntries()) {
250
+ for (const [, column] of table.getColumnEntries()) {
246
251
  if (column.onUpdate && !named.has(column)) {
247
252
  entries.push([new SQLIdentifier(column.name), column.getUpdateValue(undefined)]);
248
253
  }
@@ -250,19 +255,21 @@ export class OperationsFactory {
250
255
  return entries;
251
256
  }
252
257
  _resolveSelectParams(table, args, mode, resolvers = [],
253
- /** The level is read as JSON (a join, a union branch): see `Column.textInJson`. */
258
+ /** The level is read as JSON (a join, a union branch): @see {Column.textInJson}. */
254
259
  json = false) {
255
- const fields = this._resolveFields(table, args.select);
260
+ const fields = this._resolveFields(table, args.select, args.resolvers);
256
261
  resolvers.push(...fields.resolvers);
257
- const where = this._resolveWhere(table, args.where);
258
- const order = args.orderBy ? this._validateOrderExpression(table, args.orderBy) : undefined;
262
+ const where = this._resolveWhere(table, ["select"], args.where);
263
+ const order = args.orderBy ? this._resolveOrderEntries(table, args.orderBy) : undefined;
259
264
  const join = args.join ? this._resolveJoinEntries(table, args.join, resolvers) : undefined;
260
265
  const limit = mode === "one" ? 1 : args.limit;
261
266
  // `::text` is the database's own rendering of the value, which a cursor carries verbatim —
262
267
  // a decoded JS value may have lost precision the database still compares on.
263
268
  const keys = (args.keys ?? []).map((column, index) => sql `${column}::text AS ${sql.identifier(`__k${index}`)}`);
264
269
  const columns = json
265
- ? fields.columns.map((column) => column.textInJson ? sql `${column}::text AS ${sql.identifier(column.name)}` : column)
270
+ ? fields.columns.map((column) => column instanceof Column && column.textInJson
271
+ ? sql `${column}::text AS ${sql.identifier(column.name)}`
272
+ : column)
266
273
  : fields.columns;
267
274
  return {
268
275
  table,
@@ -283,20 +290,21 @@ export class OperationsFactory {
283
290
  }
284
291
  for (const [key, value] of join) {
285
292
  const fieldName = typeof key === "string" ? key : key.name;
286
- const relation = table.getRelation(fieldName);
293
+ const relation = this._ctx.schema.getRelation(table, fieldName);
287
294
  if (!relation) {
288
295
  throw new Error(`Relation "${fieldName}" does not exist on table "${table.name}"`);
289
296
  }
290
- const target = this._ctx.schema.getRelationTarget(table.name, fieldName);
291
297
  const isUnionArgs = "members" in value;
292
- if (target instanceof Union !== isUnionArgs) {
298
+ if ((relation.kind === "union") !== isUnionArgs) {
293
299
  throw new Error(`Relation "${fieldName}" on table "${table.name}" targets ` +
294
- (target instanceof Union ? `union "${target.alias}"` : `table "${target.name}"`) +
300
+ (relation.kind === "union"
301
+ ? `union "${relation.target.alias}"`
302
+ : `table "${relation.target.name}"`) +
295
303
  `, but was joined with arguments for ${isUnionArgs ? "a union" : "a table"}.`);
296
304
  }
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));
305
+ const mode = relation.type === Relation.HAS_MANY ? "many" : "one";
306
+ if (relation.kind === "union") {
307
+ const union = this._resolveUnionParams(relation.target, value, mode, relation.members, relation.discriminator);
300
308
  resolvers.push([fieldName, union.resolver]);
301
309
  // Every member pruned: no branch can match, so there is nothing to join. The resolver
302
310
  // still answers `[]` or `null` for the field.
@@ -306,7 +314,7 @@ export class OperationsFactory {
306
314
  joins.push({
307
315
  alias: fieldName,
308
316
  type: mode,
309
- from: this._resolveFromColumns(table, fieldName, relation.from),
317
+ from: [...relation.from],
310
318
  union: union.params,
311
319
  });
312
320
  continue;
@@ -316,49 +324,27 @@ export class OperationsFactory {
316
324
  throw new Error(`Relation "${fieldName}" on table "${table.name}" cannot project keyset keys: only ` +
317
325
  `the root level of a select is keyset-ordered.`);
318
326
  }
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)`);
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
- });
332
327
  const joinResolvers = [];
333
- const params = this._resolveSelectParams(targetTable, tableArgs, relation.type === Relation.HAS_MANY ? "many" : "one", joinResolvers, true);
328
+ const params = this._resolveSelectParams(relation.target, tableArgs, mode, joinResolvers, true);
334
329
  // The correlation itself is the query builder's business: only it knows the alias each
335
330
  // level renders under, and a self-join needs the two sides aliased differently.
336
331
  joins.push({
337
332
  alias: fieldName,
338
- type: relation.type === "has_many" ? "many" : "one",
339
- from: fromColumns,
340
- to: toColumns,
333
+ type: mode,
334
+ from: [...relation.from],
335
+ to: [...relation.to],
341
336
  params,
342
337
  });
343
338
  resolvers.push([fieldName, joinResolvers]);
344
339
  }
345
340
  return joins;
346
341
  }
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
342
  /**
357
343
  * Builds the branches of a select over a union, one per member in `args.members`, each
358
344
  * 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.
345
+ * the `WHERE` seam and gets nested joins and codec-aware filters exactly as a single-table
346
+ * level would. A branch cannot skip them, which is what keeps a union from becoming a way
347
+ * around a member's boundary.
362
348
  *
363
349
  * Each branch also projects:
364
350
  * - its alias as a `$$key` literal, which lands in the row's JSON and drives dispatch;
@@ -374,65 +360,24 @@ export class OperationsFactory {
374
360
  */
375
361
  _resolveUnionParams(union, args, mode, pairs, discriminator) {
376
362
  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
363
  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
- };
364
+ const ordered = orderBy.length > 0;
365
+ const limit = mode === "one" ? 1 : args.limit;
404
366
  const branches = [];
405
367
  const resolvers = {};
406
368
  for (const [alias, memberArgs] of args.members) {
407
369
  const member = union.getMember(alias);
408
370
  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;
371
+ const expressions = orderBy.map((key) => this._getUnionKeyExpression(union, alias, key));
422
372
  const params = this._resolveSelectParams(member, {
423
373
  ...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
374
  limit: limit !== undefined ? limit + (offset ?? 0) : undefined,
430
375
  offset: undefined,
431
376
  }, "many", memberResolvers, true);
432
377
  params.select = [
433
378
  sql `${sql.literal(alias)} AS ${sql.identifier(KEY_FIELD)}`,
434
379
  ...params.select,
435
- ...order.flatMap((key, index) => {
380
+ ...orderBy.flatMap((key, index) => {
436
381
  const hidden = this._getUnionKeyName(key, index);
437
382
  return hidden === KEY_FIELD
438
383
  ? []
@@ -447,23 +392,28 @@ export class OperationsFactory {
447
392
  const { resolvers: branchResolvers, ...select } = params;
448
393
  branches.push({
449
394
  params: select,
450
- to: pairs?.[alias],
395
+ to: pairs?.[alias] ? [...pairs[alias]] : undefined,
451
396
  // A belongs-to row names its member in the discriminator; only that member's branch may
452
397
  // match it, whatever ids the other members hold.
453
398
  correlate: discriminator ? [sql.eq(discriminator, sql.literal(alias))] : undefined,
454
399
  });
455
400
  resolvers[alias] = branchResolvers;
456
401
  }
402
+ const hasKeyField = orderBy.some((key) => key[0] === KEY_FIELD);
457
403
  const carry = [
458
- ...order.map((key, index) => this._getUnionKeyName(key, index)),
459
- ...(args.keys ? order.map((_, index) => `__k${index}`) : []),
404
+ ...orderBy.map((key, index) => this._getUnionKeyName(key, index)),
405
+ ...(!hasKeyField ? [KEY_FIELD] : []),
406
+ ...(args.keys ? orderBy.map((_, index) => `__k${index}`) : []),
460
407
  ];
461
408
  return {
462
409
  params: {
463
410
  branches,
464
411
  carry,
465
412
  order: ordered
466
- ? order.map((key, index) => sql `${sql.identifier(this._getUnionKeyName(key, index))} ${sql.raw(direction(key))}`)
413
+ ? this._resolveUnionOrderEntries(orderBy.map((key, index) => [
414
+ this._getUnionKeyName(key, index),
415
+ key[1],
416
+ ]))
467
417
  : undefined,
468
418
  limit,
469
419
  offset,
@@ -471,35 +421,15 @@ export class OperationsFactory {
471
421
  resolver: new UnionResolver(mode, resolvers),
472
422
  };
473
423
  }
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
424
  /** What one order key reads inside one member's branch. */
495
425
  _getUnionKeyExpression(union, alias, key) {
496
- if (key.field === KEY_FIELD) {
426
+ if (key[0] === KEY_FIELD) {
497
427
  return sql.literal(alias);
498
428
  }
499
- if (key.field.startsWith(PK_FIELD_PREFIX)) {
500
- return union.getMember(alias).primaryKey[Number(key.field.slice(PK_FIELD_PREFIX.length))];
429
+ if (key[0].startsWith(PK_FIELD_PREFIX)) {
430
+ return union.getMember(alias).primaryKey[Number(key[0].slice(PK_FIELD_PREFIX.length))];
501
431
  }
502
- return union.getMemberColumn(alias, key.field);
432
+ return union.getMemberColumn(alias, key[0]);
503
433
  }
504
434
  /**
505
435
  * The name one order key is carried under to the union level: `"$$key"` for `$$key`, which
@@ -507,11 +437,11 @@ export class OperationsFactory {
507
437
  * caller's key — its position, since members may name the column differently.
508
438
  */
509
439
  _getUnionKeyName(key, index) {
510
- if (key.field === KEY_FIELD) {
440
+ if (key[0] === KEY_FIELD) {
511
441
  return KEY_FIELD;
512
442
  }
513
- if (key.field.startsWith(PK_FIELD_PREFIX)) {
514
- return `__pk${key.field.slice(PK_FIELD_PREFIX.length)}`;
443
+ if (key[0].startsWith(PK_FIELD_PREFIX)) {
444
+ return `__pk${key[0].slice(PK_FIELD_PREFIX.length)}`;
515
445
  }
516
446
  return `__o${index}`;
517
447
  }
@@ -539,8 +469,8 @@ export class OperationsFactory {
539
469
  for (const row of rows) {
540
470
  const result = {};
541
471
  for (const [fieldName, resolver] of resolvers) {
542
- if (typeof resolver === "function") {
543
- result[fieldName] = resolver(row);
472
+ if (resolver instanceof Column) {
473
+ result[fieldName] = resolver.resolve(row[resolver.name], row);
544
474
  continue;
545
475
  }
546
476
  if (resolver instanceof UnionResolver) {
@@ -557,7 +487,7 @@ export class OperationsFactory {
557
487
  result[fieldName] = nestedResolver(Array.isArray(nestedRows) ? nestedRows : [nestedRows]);
558
488
  continue;
559
489
  }
560
- result[fieldName] = resolver.resolve(row[resolver.name]);
490
+ result[fieldName] = resolver.resolve(row[fieldName], row);
561
491
  }
562
492
  results.push(result);
563
493
  }
@@ -576,7 +506,7 @@ export class OperationsFactory {
576
506
  mode: mode,
577
507
  name: name ?? `select_${table.name}`,
578
508
  args: args,
579
- query: query.toQuery(),
509
+ query: this._render(query),
580
510
  resolve: this._createResultResolver(fieldResolvers, mode),
581
511
  };
582
512
  }
@@ -589,14 +519,14 @@ export class OperationsFactory {
589
519
  const query = this._ctx.dialect.buildSelectQuery({
590
520
  table,
591
521
  select: [sql `count(*) AS ${sql.identifier("count")}`],
592
- where: this._resolveWhere(table, args.where),
522
+ where: this._resolveWhere(table, ["select"], args.where),
593
523
  });
594
524
  return {
595
525
  type: "select",
596
526
  mode: "one",
597
527
  name: name ?? `count_${table.name}`,
598
528
  args,
599
- query: query.toQuery(),
529
+ query: this._render(query),
600
530
  // `count(*)` is a `bigint`, which drivers hand back as text (node-postgres) or `bigint`.
601
531
  resolve: (rows) => Number(rows[0]?.count ?? 0),
602
532
  };
@@ -617,7 +547,7 @@ export class OperationsFactory {
617
547
  mode,
618
548
  name: name ?? `select_${union.alias}`,
619
549
  args,
620
- query: query.toQuery(),
550
+ query: this._render(query),
621
551
  resolve: (rows) => this._resolveUnionRows(resolver, rows.map((row) => row.data)),
622
552
  };
623
553
  }
@@ -632,7 +562,7 @@ export class OperationsFactory {
632
562
  const query = this._ctx.dialect.buildSelectQuery({
633
563
  table: member,
634
564
  select: [sql `count(*)`],
635
- where: this._resolveWhere(member, memberArgs.where),
565
+ where: this._resolveWhere(member, ["select"], memberArgs.where),
636
566
  });
637
567
  return sql `(${query})`;
638
568
  });
@@ -643,7 +573,7 @@ export class OperationsFactory {
643
573
  mode: "one",
644
574
  name: name ?? `count_${union.alias}`,
645
575
  args,
646
- query: query.toQuery(),
576
+ query: this._render(query),
647
577
  resolve: (rows) => Number(rows[0]?.count ?? 0),
648
578
  };
649
579
  }
@@ -651,44 +581,48 @@ export class OperationsFactory {
651
581
  const { name, args, mode } = config;
652
582
  const [columns, values] = this._resolveInsertEntries(table, args.data);
653
583
  const selection = this._resolveFields(table, args.return);
584
+ const check = this._policyCheck(table, "insert");
654
585
  const query = this._ctx.dialect.buildInsertQuery({
655
586
  table,
656
587
  columns,
657
588
  values,
658
- return: selection.columns,
589
+ // The check rides on `RETURNING`, so it runs whether or not the caller asked for rows;
590
+ // no resolver reads it, so it never reaches a record.
591
+ return: check ? [...selection.columns, check] : selection.columns,
659
592
  });
660
593
  return {
661
594
  type: "insert",
662
595
  mode: config.mode,
663
596
  name: name ?? `insert_${table.name}`,
664
597
  args: args,
665
- query: query.toQuery(),
598
+ query: this._render(query),
666
599
  resolve: this._createResultResolver(selection.resolvers, mode),
667
600
  };
668
601
  }
669
602
  createUpdateOperation(table, config) {
670
603
  const { name, args, mode } = config;
671
604
  const entries = this._resolveUpdateEntries(table, args.set);
672
- const where = this._resolveWhere(table, args.where);
605
+ const where = this._resolveWhere(table, ["update", "select"], args.where);
673
606
  const selection = this._resolveFields(table, args.return);
607
+ const check = this._policyCheck(table, "update");
674
608
  const query = this._ctx.dialect.buildUpdateQuery({
675
609
  table,
676
610
  set: entries,
677
611
  where,
678
- return: selection.columns,
612
+ return: check ? [...selection.columns, check] : selection.columns,
679
613
  });
680
614
  return {
681
615
  type: "update",
682
616
  mode,
683
617
  name: name ?? `update_${table.name}`,
684
618
  args: args,
685
- query: query.toQuery(),
619
+ query: this._render(query),
686
620
  resolve: this._createResultResolver(selection.resolvers, mode),
687
621
  };
688
622
  }
689
623
  createDeleteOperation(table, config) {
690
624
  const { name, args, mode } = config;
691
- const where = this._resolveWhere(table, args.where);
625
+ const where = this._resolveWhere(table, ["delete", "select"], args.where);
692
626
  const selection = this._resolveFields(table, args.return);
693
627
  const query = this._ctx.dialect.buildDeleteQuery({
694
628
  table,
@@ -700,7 +634,7 @@ export class OperationsFactory {
700
634
  mode: config.mode,
701
635
  name: name ?? `delete_${table.name}`,
702
636
  args: args,
703
- query: query.toQuery(),
637
+ query: this._render(query),
704
638
  resolve: this._createResultResolver(selection.resolvers, mode),
705
639
  };
706
640
  }