dsqlbase 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 (160) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +41 -60
  3. package/dist/client/clients/base.d.ts +20 -0
  4. package/dist/client/clients/base.d.ts.map +1 -0
  5. package/dist/client/clients/base.js +52 -0
  6. package/dist/client/clients/base.js.map +1 -0
  7. package/dist/client/clients/dsql.d.ts +24 -0
  8. package/dist/client/clients/dsql.d.ts.map +1 -0
  9. package/dist/client/clients/dsql.js +31 -0
  10. package/dist/client/clients/dsql.js.map +1 -0
  11. package/dist/client/clients/index.d.ts +6 -0
  12. package/dist/client/clients/index.d.ts.map +1 -0
  13. package/dist/client/clients/index.js +6 -0
  14. package/dist/client/clients/index.js.map +1 -0
  15. package/dist/client/clients/model.d.ts +169 -0
  16. package/dist/client/clients/model.d.ts.map +1 -0
  17. package/dist/client/{model/client.js → clients/model.js} +82 -53
  18. package/dist/client/clients/model.js.map +1 -0
  19. package/dist/client/clients/transaction.d.ts +9 -0
  20. package/dist/client/clients/transaction.d.ts.map +1 -0
  21. package/dist/client/{transaction/transaction-client.js → clients/transaction.js} +7 -7
  22. package/dist/client/clients/transaction.js.map +1 -0
  23. package/dist/client/clients/union.d.ts +39 -0
  24. package/dist/client/clients/union.d.ts.map +1 -0
  25. package/dist/client/clients/union.js +54 -0
  26. package/dist/client/clients/union.js.map +1 -0
  27. package/dist/client/create.d.ts +15 -18
  28. package/dist/client/create.d.ts.map +1 -1
  29. package/dist/client/create.js +10 -27
  30. package/dist/client/create.js.map +1 -1
  31. package/dist/client/index.d.ts +4 -8
  32. package/dist/client/index.d.ts.map +1 -1
  33. package/dist/client/index.js +3 -6
  34. package/dist/client/index.js.map +1 -1
  35. package/dist/client/normalizers/base.d.ts +467 -0
  36. package/dist/client/normalizers/base.d.ts.map +1 -0
  37. package/dist/client/normalizers/base.js.map +1 -0
  38. package/dist/client/normalizers/context.d.ts +14 -0
  39. package/dist/client/normalizers/context.d.ts.map +1 -0
  40. package/dist/client/normalizers/context.js +16 -0
  41. package/dist/client/normalizers/context.js.map +1 -0
  42. package/dist/client/normalizers/index.d.ts +8 -0
  43. package/dist/client/normalizers/index.d.ts.map +1 -0
  44. package/dist/client/normalizers/index.js +8 -0
  45. package/dist/client/normalizers/index.js.map +1 -0
  46. package/dist/client/normalizers/pagination.d.ts +87 -0
  47. package/dist/client/normalizers/pagination.d.ts.map +1 -0
  48. package/dist/client/normalizers/pagination.js +245 -0
  49. package/dist/client/normalizers/pagination.js.map +1 -0
  50. package/dist/client/normalizers/request.d.ts +41 -0
  51. package/dist/client/normalizers/request.d.ts.map +1 -0
  52. package/dist/client/normalizers/request.js +346 -0
  53. package/dist/client/normalizers/request.js.map +1 -0
  54. package/dist/client/normalizers/rules.d.ts +132 -0
  55. package/dist/client/normalizers/rules.d.ts.map +1 -0
  56. package/dist/client/normalizers/rules.js +82 -0
  57. package/dist/client/normalizers/rules.js.map +1 -0
  58. package/dist/client/normalizers/utils.d.ts +6 -0
  59. package/dist/client/normalizers/utils.d.ts.map +1 -0
  60. package/dist/client/normalizers/utils.js +18 -0
  61. package/dist/client/normalizers/utils.js.map +1 -0
  62. package/dist/client/normalizers/where.d.ts +39 -0
  63. package/dist/client/normalizers/where.d.ts.map +1 -0
  64. package/dist/client/normalizers/where.js +230 -0
  65. package/dist/client/normalizers/where.js.map +1 -0
  66. package/dist/client/utils/occ-retry.d.ts.map +1 -0
  67. package/dist/client/utils/occ-retry.js.map +1 -0
  68. package/dist/index.d.ts +2 -3
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +2 -3
  71. package/dist/index.js.map +1 -1
  72. package/dist/schema/columns/guid.d.ts +21 -21
  73. package/dist/schema/columns/guid.d.ts.map +1 -1
  74. package/dist/schema/columns/guid.js +24 -25
  75. package/dist/schema/columns/guid.js.map +1 -1
  76. package/dist/schema/index.d.ts +0 -2
  77. package/dist/schema/index.d.ts.map +1 -1
  78. package/dist/schema/index.js +0 -2
  79. package/dist/schema/index.js.map +1 -1
  80. package/dist/schema/relations.d.ts +22 -13
  81. package/dist/schema/relations.d.ts.map +1 -1
  82. package/dist/schema/relations.js +9 -1
  83. package/dist/schema/relations.js.map +1 -1
  84. package/dist/schema/table.d.ts +2 -2
  85. package/dist/schema/table.d.ts.map +1 -1
  86. package/dist/schema/table.js.map +1 -1
  87. package/dist/schema/union.d.ts +13 -8
  88. package/dist/schema/union.d.ts.map +1 -1
  89. package/dist/schema/union.js +14 -9
  90. package/dist/schema/union.js.map +1 -1
  91. package/dist/schema/utils/global-id.d.ts +3 -3
  92. package/dist/schema/utils/global-id.js +3 -3
  93. package/dist/schema/utils/global-id.js.map +1 -1
  94. package/dist/schema/utils/guid-hooks.d.ts +49 -0
  95. package/dist/schema/utils/guid-hooks.d.ts.map +1 -0
  96. package/dist/schema/utils/guid-hooks.js +155 -0
  97. package/dist/schema/utils/guid-hooks.js.map +1 -0
  98. package/package.json +8 -6
  99. package/dist/client/database/base.d.ts +0 -99
  100. package/dist/client/database/base.d.ts.map +0 -1
  101. package/dist/client/database/base.js +0 -216
  102. package/dist/client/database/base.js.map +0 -1
  103. package/dist/client/database/client.d.ts +0 -26
  104. package/dist/client/database/client.d.ts.map +0 -1
  105. package/dist/client/database/client.js +0 -47
  106. package/dist/client/database/client.js.map +0 -1
  107. package/dist/client/database/index.d.ts +0 -65
  108. package/dist/client/database/index.d.ts.map +0 -1
  109. package/dist/client/database/index.js +0 -3
  110. package/dist/client/database/index.js.map +0 -1
  111. package/dist/client/model/base.d.ts +0 -747
  112. package/dist/client/model/base.d.ts.map +0 -1
  113. package/dist/client/model/base.js.map +0 -1
  114. package/dist/client/model/client.d.ts +0 -139
  115. package/dist/client/model/client.d.ts.map +0 -1
  116. package/dist/client/model/client.js.map +0 -1
  117. package/dist/client/model/filters.d.ts +0 -276
  118. package/dist/client/model/filters.d.ts.map +0 -1
  119. package/dist/client/model/filters.js +0 -470
  120. package/dist/client/model/filters.js.map +0 -1
  121. package/dist/client/model/normalizer.d.ts +0 -143
  122. package/dist/client/model/normalizer.d.ts.map +0 -1
  123. package/dist/client/model/normalizer.js +0 -641
  124. package/dist/client/model/normalizer.js.map +0 -1
  125. package/dist/client/nodes.d.ts +0 -62
  126. package/dist/client/nodes.d.ts.map +0 -1
  127. package/dist/client/nodes.js +0 -378
  128. package/dist/client/nodes.js.map +0 -1
  129. package/dist/client/pagination/cursor.d.ts +0 -40
  130. package/dist/client/pagination/cursor.d.ts.map +0 -1
  131. package/dist/client/pagination/cursor.js +0 -79
  132. package/dist/client/pagination/cursor.js.map +0 -1
  133. package/dist/client/pagination/page.d.ts +0 -23
  134. package/dist/client/pagination/page.d.ts.map +0 -1
  135. package/dist/client/pagination/page.js +0 -37
  136. package/dist/client/pagination/page.js.map +0 -1
  137. package/dist/client/transaction/index.d.ts +0 -2
  138. package/dist/client/transaction/index.d.ts.map +0 -1
  139. package/dist/client/transaction/index.js +0 -2
  140. package/dist/client/transaction/index.js.map +0 -1
  141. package/dist/client/transaction/occ-retry.d.ts.map +0 -1
  142. package/dist/client/transaction/occ-retry.js.map +0 -1
  143. package/dist/client/transaction/transaction-client.d.ts +0 -9
  144. package/dist/client/transaction/transaction-client.d.ts.map +0 -1
  145. package/dist/client/transaction/transaction-client.js.map +0 -1
  146. package/dist/client/union/client.d.ts +0 -55
  147. package/dist/client/union/client.d.ts.map +0 -1
  148. package/dist/client/union/client.js +0 -74
  149. package/dist/client/union/client.js.map +0 -1
  150. package/dist/schema/embedded.d.ts +0 -31
  151. package/dist/schema/embedded.d.ts.map +0 -1
  152. package/dist/schema/embedded.js +0 -33
  153. package/dist/schema/embedded.js.map +0 -1
  154. package/dist/schema/tenant.d.ts +0 -31
  155. package/dist/schema/tenant.d.ts.map +0 -1
  156. package/dist/schema/tenant.js +0 -33
  157. package/dist/schema/tenant.js.map +0 -1
  158. /package/dist/client/{model → normalizers}/base.js +0 -0
  159. /package/dist/client/{transaction → utils}/occ-retry.d.ts +0 -0
  160. /package/dist/client/{transaction → utils}/occ-retry.js +0 -0
@@ -1,641 +0,0 @@
1
- import { KEY_FIELD } from "@dsqlbase/core/definition";
2
- import { decodeMemberId, getDynamicGuidBinding } from "../nodes.js";
3
- import { GlobalIdError } from "../../schema/utils/global-id.js";
4
- import { Column, ColumnGroup, sql, Union, } from "@dsqlbase/core";
5
- import { decodeCursor, InvalidCursorError, keysetSignature, } from "../pagination/cursor.js";
6
- import { rulesOf, WhereBuilder } from "./filters.js";
7
- /** The page size when neither the call nor the client names one. */
8
- export const DEFAULT_PAGE_SIZE = 100;
9
- const flip = (direction) => (direction === "asc" ? "desc" : "asc");
10
- export class RequestNormalizer {
11
- _ctx;
12
- _where = new WhereBuilder();
13
- constructor(context) {
14
- this._ctx = context;
15
- }
16
- /** The columns a `return` names, or `undefined` — every column — when it names none. */
17
- _getSelectionEntries(table, selection) {
18
- const entries = [];
19
- if (!selection || typeof selection === "boolean") {
20
- return undefined;
21
- }
22
- for (const [fieldName, isSelected] of Object.entries(selection)) {
23
- if (isSelected) {
24
- const field = table.getColumn(fieldName);
25
- if (!field) {
26
- throw new Error(`Invalid field "${fieldName}" in selection for table "${table.name}".`);
27
- }
28
- entries.push(this._getFieldSelection(table, fieldName, field, isSelected));
29
- }
30
- }
31
- return entries.length > 0 ? entries : undefined;
32
- }
33
- /**
34
- * One selected field: a column takes `true`; a group takes `true` — every member — or a map
35
- * naming some, each a member column or a nested group read the same way.
36
- */
37
- _getFieldSelection(table, path, field, selected) {
38
- if (field instanceof Column) {
39
- if (selected !== true) {
40
- throw new Error(`Invalid selection for column "${path}" of "${table.name}": a column takes true.`);
41
- }
42
- return [path.split(".").at(-1), field];
43
- }
44
- return [
45
- path.split(".").at(-1),
46
- field,
47
- this._getGroupSelection(table, path, field, selected),
48
- ];
49
- }
50
- _getGroupSelection(table, path, group, selected) {
51
- if (selected === true) {
52
- return undefined;
53
- }
54
- if (typeof selected !== "object" || selected === null || Array.isArray(selected)) {
55
- throw new Error(`Invalid selection for group "${path}" of "${table.name}": a group takes true or a ` +
56
- `map of its members.`);
57
- }
58
- const entries = [];
59
- for (const [member, value] of Object.entries(selected)) {
60
- if (value === false || value === null || value === undefined) {
61
- continue;
62
- }
63
- const field = group.getColumn(member);
64
- if (!field) {
65
- throw new Error(`Invalid field "${path}.${member}" in selection for table "${table.name}".`);
66
- }
67
- entries.push(this._getFieldSelection(table, `${path}.${member}`, field, value));
68
- }
69
- return entries;
70
- }
71
- /**
72
- * A read's `select`, split into the columns it names and the relations it names. A relation
73
- * takes `true` or a field map, and is read exactly as `join: { r: true }` or
74
- * `join: { r: { select: map } }`: it is merged into `join` here, so everything after this
75
- * sees one join form. The same relation in both is refused rather than merged.
76
- *
77
- * Which columns come back: those named; none when only relations are named (`[]`); every
78
- * column when nothing is named at all (`undefined`), as with no `select`.
79
- */
80
- _getReadSelection(table, selection, join, columns = []) {
81
- // Selected relations first, so a result's keys follow the call as written.
82
- const merged = {};
83
- for (const [fieldName, value] of Object.entries(selection ?? {})) {
84
- if (value === false || value === null || value === undefined) {
85
- continue;
86
- }
87
- const column = table.getColumn(fieldName);
88
- if (column && (value === true || column instanceof ColumnGroup)) {
89
- if (!columns.some(([name]) => name === fieldName)) {
90
- columns.push(this._getFieldSelection(table, fieldName, column, value));
91
- }
92
- continue;
93
- }
94
- if (column || !this._isRelation(table, fieldName)) {
95
- throw new Error(`Invalid field "${fieldName}" in selection for table "${table.name}".`);
96
- }
97
- const joined = join?.[fieldName];
98
- if (joined !== undefined && joined !== null && joined !== false) {
99
- throw new Error(`Relation "${fieldName}" appears in both select and join on "${table.name}"; ` +
100
- `name it in one of them.`);
101
- }
102
- merged[fieldName] = value === true ? true : { select: value };
103
- }
104
- const hasRelation = Object.keys(merged).length > 0;
105
- for (const [fieldName, entry] of Object.entries(join ?? {})) {
106
- // A selected relation is only ever beside a falsy join entry here, which it outranks.
107
- if (!(fieldName in merged)) {
108
- merged[fieldName] = entry;
109
- }
110
- }
111
- return {
112
- select: columns.length > 0 ? columns : hasRelation ? [] : undefined,
113
- join: merged,
114
- };
115
- }
116
- _isRelation(table, fieldName) {
117
- const { schema } = this._ctx;
118
- return (schema.hasRelations(table.name) && Object.hasOwn(schema.getRelations(table.name), fieldName));
119
- }
120
- /** `orderBy` as resolved keys, in the order the caller wrote them. */
121
- _getOrderKeys(table, orderBy) {
122
- return this._getFieldOrderKeys(table, undefined, orderBy ?? {}, []);
123
- }
124
- /**
125
- * Order keys over a table's fields, or a group's members: a group takes a nested order object
126
- * — never a direction of its own — and each member key is its column, named by its field path
127
- * (`netValue.amount`), which is also what a cursor's signature records.
128
- */
129
- _getFieldOrderKeys(table, group, orderBy, path) {
130
- const keys = [];
131
- for (const [name, direction] of Object.entries(orderBy)) {
132
- const column = group ? group.getColumn(name) : table.getColumn(name);
133
- const field = [...path, name].join(".");
134
- if (column instanceof ColumnGroup) {
135
- if (typeof direction !== "object" || direction === null) {
136
- throw new Error(`Cannot order by the group "${field}" of "${table.name}"; order by its members: ` +
137
- `{ ${name}: { member: "asc" } }.`);
138
- }
139
- keys.push(...this._getFieldOrderKeys(table, column, direction, [...path, name]));
140
- continue;
141
- }
142
- if (!(column instanceof Column)) {
143
- throw new Error(`Invalid field "${field}" in orderBy for table "${table.name}".`);
144
- }
145
- if (!rulesOf(column).orderable) {
146
- throw new Error(`Cannot order by the ${column.runtimeType} column "${field}" of "${table.name}".`);
147
- }
148
- if (direction === "asc" || direction === "desc") {
149
- keys.push({ field, column, direction });
150
- }
151
- else if (direction !== undefined) {
152
- throw new Error(`Invalid direction ${JSON.stringify(direction)} for "${field}" in orderBy for table ` +
153
- `"${table.name}"; use "asc" or "desc".`);
154
- }
155
- }
156
- return keys;
157
- }
158
- /**
159
- * `ORDER BY` terms. A nullable page key states its null placement — Postgres's own default,
160
- * last ascending and first descending — so the order never depends on a server setting and
161
- * always agrees with the keyset predicate. Flipping a direction flips the placement with it,
162
- * which is what makes a page read backwards the exact reverse of one read forwards.
163
- */
164
- _renderOrderKeys(keys) {
165
- return keys.map(({ column, direction, nullable }) => {
166
- if (!nullable) {
167
- return direction === "asc" ? sql `${column} ASC` : sql `${column} DESC`;
168
- }
169
- return direction === "asc" ? sql `${column} ASC NULLS LAST` : sql `${column} DESC NULLS FIRST`;
170
- });
171
- }
172
- _getOrderByEntries(table, orderBy) {
173
- if (!orderBy) {
174
- return undefined;
175
- }
176
- return this._renderOrderKeys(this._getOrderKeys(table, orderBy));
177
- }
178
- /**
179
- * The total order a page is read under: the caller's keys, then every primary-key column
180
- * they did not already name, so no two rows ever tie. An appended key follows the direction
181
- * of the last one the caller wrote — `asc` when they wrote none.
182
- */
183
- _getKeysetOrder(table, orderBy) {
184
- if (table.primaryKey.length === 0) {
185
- throw new Error(`Cannot paginate "${table.name}": it has no primary key to break ties between rows.`);
186
- }
187
- const keys = this._getOrderKeys(table, orderBy);
188
- const direction = keys.at(-1)?.direction ?? "asc";
189
- const fields = new Map(table.getColumnEntries().map(([field, column]) => [column, field]));
190
- for (const column of table.primaryKey) {
191
- if (!keys.some((key) => key.column === column)) {
192
- keys.push({ field: fields.get(column), column, direction });
193
- }
194
- }
195
- // A primary-key column cannot hold NULL, whether or not it was also marked notNull.
196
- return keys.map((key) => ({
197
- ...key,
198
- nullable: !key.column.notNull && !table.primaryKey.includes(key.column),
199
- }));
200
- }
201
- _getPageSize(limit) {
202
- const { defaultLimit = DEFAULT_PAGE_SIZE, maxLimit } = this._ctx.pagination ?? {};
203
- const size = limit ?? defaultLimit;
204
- if (!Number.isInteger(size) || size <= 0) {
205
- throw new Error(`A page size must be a positive integer (got ${String(size)}).`);
206
- }
207
- if (maxLimit !== undefined && size > maxLimit) {
208
- throw new Error(`A page size of ${size} exceeds this client's maxLimit of ${maxLimit}.`);
209
- }
210
- return size;
211
- }
212
- _getJoinEntries(table, join) {
213
- const entries = [];
214
- if (!join || Object.keys(join).length === 0) {
215
- return undefined;
216
- }
217
- for (const [fieldName, query] of Object.entries(join)) {
218
- if (query === null || query === undefined || (typeof query === "boolean" && !query)) {
219
- continue;
220
- }
221
- const targetTable = this._ctx.schema.getRelationTarget(table.name, fieldName);
222
- if (!targetTable) {
223
- throw new Error(`Relation "${fieldName}" in table "${table.name}" does not have a valid target table.`);
224
- }
225
- if (targetTable instanceof Union) {
226
- entries.push([
227
- fieldName,
228
- this._getUnionArgs(targetTable, query === true ? {} : query),
229
- ]);
230
- continue;
231
- }
232
- const params = this._getSelectArgs(targetTable, query === true ? {} : query);
233
- entries.push([fieldName, params]);
234
- }
235
- return entries;
236
- }
237
- /**
238
- * The arguments of a select over a union, one entry per member that runs.
239
- *
240
- * The shared `select` / `where` apply to every member, written against that member's own
241
- * columns; `on.<alias>` then adds to them — its `select` is merged in, its `where` AND-ed
242
- * with the shared one, its `join` walks the member's own relations — or, as `false`, drops
243
- * the member entirely. Omitted, a member runs with the shared arguments alone.
244
- */
245
- _getUnionArgs(union, args) {
246
- if (args.distinct) {
247
- throw new Error(`\`distinct\` is not supported on union "${union.alias}".`);
248
- }
249
- const on = (args.on ?? {});
250
- for (const alias of Object.keys(on)) {
251
- if (!union.hasMember(alias)) {
252
- throw new Error(`"${alias}" in \`on\` is not a member of union "${union.alias}" ` +
253
- `(members: ${union.memberAliases.join(", ")}).`);
254
- }
255
- }
256
- const sharedSelect = Object.entries(args.select ?? {})
257
- .filter(([, selected]) => selected)
258
- .map(([field]) => field);
259
- for (const field of sharedSelect) {
260
- if (!union.isShared(field)) {
261
- throw new Error(`Invalid field "${field}" in selection for union "${union.alias}": only fields every ` +
262
- `member shares select across a union. Select it for one member through \`on\`.`);
263
- }
264
- }
265
- this._where.assertShared(union, args.where);
266
- const members = [];
267
- for (const alias of union.memberAliases) {
268
- const entry = on[alias];
269
- if (entry === false) {
270
- continue;
271
- }
272
- const sharedWhere = args.where
273
- ? this._where.foldKey(union, args.where, alias)
274
- : undefined;
275
- // A `$$key` condition this member can never satisfy: no branch at all.
276
- if (sharedWhere === false) {
277
- continue;
278
- }
279
- const member = union.getMember(alias);
280
- const own = (typeof entry === "object" && entry !== null ? entry : {});
281
- const shared = sharedSelect.map((field) => [
282
- field,
283
- union.getMemberColumn(alias, field),
284
- ]);
285
- // The member's own select adds to the shared one; a relation in it becomes a member join.
286
- const selection = this._getReadSelection(member, own.select, own.join, shared);
287
- const where = [
288
- this._where.build(member, sharedWhere),
289
- this._where.build(member, own.where),
290
- ].filter((node) => node !== undefined);
291
- members.push([
292
- alias,
293
- {
294
- select: selection.select,
295
- where: where.length > 0 ? where : undefined,
296
- join: this._getJoinEntries(member, selection.join),
297
- },
298
- ]);
299
- }
300
- return {
301
- members,
302
- orderBy: this._getUnionOrderKeys(union, args.orderBy),
303
- limit: args.limit ?? undefined,
304
- offset: args.offset ?? undefined,
305
- };
306
- }
307
- _getUnionOrderKeys(union, orderBy) {
308
- if (!orderBy) {
309
- return undefined;
310
- }
311
- const keys = [];
312
- for (const [field, direction] of Object.entries(orderBy)) {
313
- if (field !== KEY_FIELD && !union.isShared(field)) {
314
- throw new Error(`Invalid field "${field}" in orderBy for union "${union.alias}": only fields every ` +
315
- `member shares, and ${KEY_FIELD}, order across a union.`);
316
- }
317
- if (field !== KEY_FIELD) {
318
- const column = union.getMemberColumn(union.memberAliases[0], field);
319
- if (!rulesOf(column).orderable) {
320
- throw new Error(`Cannot order by the ${column.runtimeType} field "${field}" of union "${union.alias}".`);
321
- }
322
- }
323
- if (direction === "asc" || direction === "desc") {
324
- keys.push({ field, direction });
325
- }
326
- else if (direction !== undefined) {
327
- throw new Error(`Invalid direction ${JSON.stringify(direction)} for "${field}" in orderBy for union ` +
328
- `"${union.alias}"; use "asc" or "desc".`);
329
- }
330
- }
331
- return keys;
332
- }
333
- _getMutationEntries(table, values) {
334
- const entries = [];
335
- for (const [fieldName, value] of Object.entries(values)) {
336
- const column = table.getColumn(fieldName);
337
- if (column instanceof ColumnGroup) {
338
- entries.push(...this._getGroupMutations(table, [fieldName], column, value));
339
- continue;
340
- }
341
- if (!(column instanceof Column)) {
342
- throw new Error(`Invalid field "${fieldName}" in update values for table "${table.name}".`);
343
- }
344
- // Read-only columns are dropped rather than refused: the types already exclude them, so a
345
- // value here arrived through an untyped spread, and whatever owns the column wins anyway.
346
- if (column.readOnly) {
347
- continue;
348
- }
349
- entries.push([fieldName, value]);
350
- }
351
- return this._fillDiscriminators(table, values, entries);
352
- }
353
- /**
354
- * A group's value as writes to its members' columns. An object writes the members it names
355
- * and leaves the rest alone — on insert they take their defaults, on update they keep their
356
- * value — and `null` sets every column `NULL`, which only a group whose members are all
357
- * nullable can take.
358
- */
359
- _getGroupMutations(table, path, group, value) {
360
- const subject = `group "${path.join(".")}" of "${table.name}"`;
361
- if (value === undefined) {
362
- return [];
363
- }
364
- if (value === null) {
365
- if (!group.nullable) {
366
- throw new Error(`Cannot set the ${subject} to null: it has a member that is not null, so it is ` +
367
- `always present.`);
368
- }
369
- return group.leafColumns().map((column) => [column, null]);
370
- }
371
- if (typeof value !== "object" || Array.isArray(value)) {
372
- throw new Error(`Write the ${subject} as an object of its members, or null.`);
373
- }
374
- const entries = [];
375
- for (const [member, memberValue] of Object.entries(value)) {
376
- const field = group.getColumn(member);
377
- if (field instanceof ColumnGroup) {
378
- entries.push(...this._getGroupMutations(table, [...path, member], field, memberValue));
379
- continue;
380
- }
381
- if (!(field instanceof Column)) {
382
- throw new Error(`Invalid field "${[...path, member].join(".")}" in values for table "${table.name}".`);
383
- }
384
- // Dropped as a plain read-only column is, for the same reason.
385
- if (field.readOnly || memberValue === undefined) {
386
- continue;
387
- }
388
- entries.push([field, memberValue]);
389
- }
390
- return entries;
391
- }
392
- /**
393
- * A polymorphic id written as a global id also says which member it names — so it fills the
394
- * discriminator when the caller left it out, and must agree with it when they did not. A raw
395
- * uuid says nothing and leaves the discriminator alone.
396
- */
397
- _fillDiscriminators(table, values, entries) {
398
- for (const [fieldName, value] of Object.entries(values)) {
399
- const binding = getDynamicGuidBinding(table.getColumn(fieldName));
400
- const member = binding ? decodeMemberId(value, binding.members) : undefined;
401
- if (!binding || !member) {
402
- continue;
403
- }
404
- const given = values[binding.discriminatorField];
405
- if (given === undefined) {
406
- entries.push([binding.discriminatorField, member.key]);
407
- continue;
408
- }
409
- if (given !== member.key) {
410
- throw new GlobalIdError("key_mismatch", `"${fieldName}" is a global id for "${member.key}", but "${binding.discriminatorField}" ` +
411
- `says "${String(given)}".`);
412
- }
413
- }
414
- return entries;
415
- }
416
- /** `distinct` compares whole rows, so every column it reads needs an equality operator. */
417
- _assertDistinct(table, select) {
418
- // Every column the read projects is compared, a group's included — a nullable group
419
- // projects all of its columns to tell whether it is present.
420
- const fields = select
421
- ? select.flatMap(([field, column, members]) => column instanceof ColumnGroup
422
- ? column.reader(members).columns.map((leaf) => [`${field} (${leaf.name})`, leaf])
423
- : [[field, column]])
424
- : table.getLeafEntries().map(([path, column]) => [path.join("."), column]);
425
- for (const [field, column] of fields) {
426
- if (column instanceof Column && !rulesOf(column).distinct) {
427
- throw new Error(`\`distinct\` cannot compare the ${column.runtimeType} column "${field}" of ` +
428
- `"${table.name}"; leave it out of the selection.`);
429
- }
430
- }
431
- }
432
- _getSelectArgs(table, args) {
433
- const selection = this._getReadSelection(table, args.select, args.join);
434
- const where = this._where.build(table, args.where);
435
- const join = this._getJoinEntries(table, selection.join);
436
- const orderBy = this._getOrderByEntries(table, args.orderBy);
437
- if (args.distinct) {
438
- this._assertDistinct(table, selection.select);
439
- }
440
- return {
441
- select: selection.select,
442
- where,
443
- join,
444
- orderBy,
445
- distinct: args.distinct,
446
- limit: args.limit,
447
- offset: args.offset,
448
- };
449
- }
450
- normalizeSelect(table, args, mode) {
451
- const request = this._getSelectArgs(table, args);
452
- // `findOne` requires a where by type; one that selects nothing in particular is refused.
453
- if (mode === "one") {
454
- request.where = this._where.buildRequired(table, args.where, "findOne");
455
- }
456
- return { mode, args: request };
457
- }
458
- /**
459
- * A page read: the select to run, plus everything needed to turn its rows into a page.
460
- *
461
- * The keyset predicate is appended to the caller's `where` as a second condition, so the
462
- * seam in core renders the tenant predicate, then the caller's filter, then the keyset. The
463
- * caller's filter alone is kept apart as `where`, for a count over the same rows.
464
- */
465
- normalizePaginate(table, args) {
466
- const { after, before } = args;
467
- if (after != null && before != null) {
468
- throw new Error("Pass either after or before, not both.");
469
- }
470
- const take = this._getPageSize(args.limit);
471
- const keys = this._getKeysetOrder(table, args.orderBy);
472
- const signature = keysetSignature(table.alias, keys);
473
- const bound = before != null ? "before" : "after";
474
- const token = after ?? before ?? undefined;
475
- let cursor;
476
- if (token !== undefined) {
477
- cursor = decodeCursor(token, signature, keys.length);
478
- if (cursor.some((value, index) => value === null && !keys[index].nullable)) {
479
- throw new InvalidCursorError("format", `"${token}" carries a null for a key that cannot hold one.`);
480
- }
481
- }
482
- const base = this._getSelectArgs(table, { select: args.select, join: args.join });
483
- const where = this._where.build(table, args.where);
484
- const keyset = cursor
485
- ? sql.keyset(keys.map(({ column, direction, nullable }) => ({ node: column, direction, nullable })), cursor, bound)
486
- : undefined;
487
- // A page before the cursor is read backwards — every direction flipped — and put back in
488
- // order once it is resolved, so the rows nearest the cursor are the ones kept.
489
- const order = bound === "before" ? keys.map((key) => ({ ...key, direction: flip(key.direction) })) : keys;
490
- return {
491
- request: {
492
- mode: "many",
493
- args: {
494
- ...base,
495
- where: [where, keyset].filter((node) => node !== undefined),
496
- orderBy: this._renderOrderKeys(order),
497
- keys: keys.map(({ column }) => column),
498
- limit: take + 1,
499
- },
500
- },
501
- where,
502
- keys: keys.map(({ field, direction }) => ({ field, direction })),
503
- signature,
504
- take,
505
- bound,
506
- cursor,
507
- };
508
- }
509
- /**
510
- * A top-level select over a union. `findOne` needs a `where`, exactly as on a table: a
511
- * union row is only "the" row when something names it.
512
- */
513
- normalizeUnionSelect(union, args, mode) {
514
- if (mode === "one" && Object.keys(args.where ?? {}).length === 0) {
515
- throw new Error(`findOne on union "${union.alias}" needs a where that names the row it reads; an ` +
516
- `empty one would match every row of every member.`);
517
- }
518
- return { mode, args: this._getUnionArgs(union, args) };
519
- }
520
- /**
521
- * A page read over a union, under a total order built the way core builds it: the caller's
522
- * keys, then `$$key` unless they named it, then each primary-key column by position
523
- * (`$$pk<n>`), the appended keys following the caller's last direction. The cursor signs
524
- * that whole list against the union's alias, so a table's cursor never reads a union's page.
525
- */
526
- normalizeUnionPaginate(union, args) {
527
- const { after, before } = args;
528
- if (after != null && before != null) {
529
- throw new Error("Pass either after or before, not both.");
530
- }
531
- const tiebreakers = union.tiebreakers;
532
- if (tiebreakers === 0) {
533
- throw new Error(`Cannot page union "${union.alias}": its members' primary keys differ in arity or type, ` +
534
- `so nothing can break a tie between two members' rows.`);
535
- }
536
- const take = this._getPageSize(args.limit ?? undefined);
537
- const orderBy = (this._getUnionOrderKeys(union, args.orderBy) ?? []).map((key) => ({
538
- ...key,
539
- nullable: key.field !== KEY_FIELD &&
540
- union.memberAliases.some((alias) => {
541
- const column = union.getMemberColumn(alias, key.field);
542
- return !column.notNull && !union.getMember(alias).primaryKey.includes(column);
543
- }),
544
- }));
545
- const tiebreak = orderBy.at(-1)?.direction ?? "asc";
546
- const keys = [
547
- ...orderBy,
548
- ...(orderBy.some((key) => key.field === KEY_FIELD)
549
- ? []
550
- : [{ field: KEY_FIELD, direction: tiebreak }]),
551
- ...Array.from({ length: tiebreakers }, (_, index) => ({
552
- field: `$$pk${index}`,
553
- direction: tiebreak,
554
- })),
555
- ];
556
- const signature = keysetSignature(union.alias, keys);
557
- const bound = before != null ? "before" : "after";
558
- const token = after ?? before ?? undefined;
559
- let cursor;
560
- if (token !== undefined) {
561
- cursor = decodeCursor(token, signature, keys.length);
562
- if (cursor.some((value, index) => value === null && !keys[index].nullable)) {
563
- throw new InvalidCursorError("format", `"${token}" carries a null for a key that cannot hold one.`);
564
- }
565
- }
566
- const base = this._getUnionArgs(union, { select: args.select, where: args.where, on: args.on });
567
- return {
568
- request: {
569
- mode: "many",
570
- args: {
571
- ...base,
572
- orderBy,
573
- tiebreak,
574
- keys: true,
575
- keyset: cursor ? { values: cursor, bound } : undefined,
576
- limit: take + 1,
577
- },
578
- },
579
- count: {
580
- mode: "one",
581
- args: { members: base.members.map(([alias, member]) => [alias, { where: member.where }]) },
582
- },
583
- keys: keys.map(({ field, direction }) => ({ field, direction })),
584
- signature,
585
- take,
586
- bound,
587
- cursor,
588
- };
589
- }
590
- /** A count over the rows a union's members select. */
591
- normalizeUnionCount(union, args = {}) {
592
- const { members } = this._getUnionArgs(union, { where: args.where });
593
- return {
594
- mode: "one",
595
- args: { members: members.map(([alias, member]) => [alias, { where: member.where }]) },
596
- };
597
- }
598
- /** A count over the rows `where` selects. */
599
- normalizeCount(table, args = {}) {
600
- return {
601
- mode: "one",
602
- args: { where: this._where.build(table, args.where) },
603
- };
604
- }
605
- normalizeInsert(table, args, mode) {
606
- const values = this._getMutationEntries(table, args.data);
607
- const returning = this._getSelectionEntries(table, args.return);
608
- return {
609
- mode,
610
- args: {
611
- data: [values],
612
- return: returning,
613
- },
614
- };
615
- }
616
- normalizeUpdate(table, args, mode) {
617
- const values = this._getMutationEntries(table, args.set);
618
- const where = this._where.buildRequired(table, args.where, "update");
619
- const returning = this._getSelectionEntries(table, args.return);
620
- return {
621
- mode,
622
- args: {
623
- set: values,
624
- where,
625
- return: returning,
626
- },
627
- };
628
- }
629
- normalizeDelete(table, args, mode) {
630
- const where = this._where.buildRequired(table, args.where, "delete");
631
- const returning = this._getSelectionEntries(table, args.return);
632
- return {
633
- mode,
634
- args: {
635
- where,
636
- return: returning,
637
- },
638
- };
639
- }
640
- }
641
- //# sourceMappingURL=normalizer.js.map