dsqlbase 0.1.5 → 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 (208) hide show
  1. package/CHANGELOG.md +208 -0
  2. package/LICENSE +21 -0
  3. package/README.md +206 -2
  4. package/dist/client/create.d.ts +24 -4
  5. package/dist/client/create.d.ts.map +1 -1
  6. package/dist/client/create.js +21 -9
  7. package/dist/client/create.js.map +1 -1
  8. package/dist/client/database/base.d.ts +92 -1
  9. package/dist/client/database/base.d.ts.map +1 -1
  10. package/dist/client/database/base.js +196 -1
  11. package/dist/client/database/base.js.map +1 -1
  12. package/dist/client/database/client.d.ts +21 -5
  13. package/dist/client/database/client.d.ts.map +1 -1
  14. package/dist/client/database/client.js +39 -1
  15. package/dist/client/database/client.js.map +1 -1
  16. package/dist/client/database/index.d.ts +60 -4
  17. package/dist/client/database/index.d.ts.map +1 -1
  18. package/dist/client/database/index.js.map +1 -1
  19. package/dist/client/index.d.ts +4 -2
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/index.js +4 -2
  22. package/dist/client/index.js.map +1 -1
  23. package/dist/client/model/base.d.ts +553 -136
  24. package/dist/client/model/base.d.ts.map +1 -1
  25. package/dist/client/model/base.js +1 -6
  26. package/dist/client/model/base.js.map +1 -1
  27. package/dist/client/model/client.d.ts +45 -8
  28. package/dist/client/model/client.d.ts.map +1 -1
  29. package/dist/client/model/client.js +58 -2
  30. package/dist/client/model/client.js.map +1 -1
  31. package/dist/client/model/filters.d.ts +276 -0
  32. package/dist/client/model/filters.d.ts.map +1 -0
  33. package/dist/client/model/filters.js +470 -0
  34. package/dist/client/model/filters.js.map +1 -0
  35. package/dist/client/model/normalizer.d.ts +127 -3
  36. package/dist/client/model/normalizer.d.ts.map +1 -1
  37. package/dist/client/model/normalizer.js +526 -106
  38. package/dist/client/model/normalizer.js.map +1 -1
  39. package/dist/client/nodes.d.ts +62 -0
  40. package/dist/client/nodes.d.ts.map +1 -0
  41. package/dist/client/nodes.js +378 -0
  42. package/dist/client/nodes.js.map +1 -0
  43. package/dist/client/pagination/cursor.d.ts +40 -0
  44. package/dist/client/pagination/cursor.d.ts.map +1 -0
  45. package/dist/client/pagination/cursor.js +79 -0
  46. package/dist/client/pagination/cursor.js.map +1 -0
  47. package/dist/client/pagination/page.d.ts +23 -0
  48. package/dist/client/pagination/page.d.ts.map +1 -0
  49. package/dist/client/pagination/page.js +37 -0
  50. package/dist/client/pagination/page.js.map +1 -0
  51. package/dist/client/transaction/index.js.map +1 -1
  52. package/dist/client/transaction/occ-retry.d.ts +2 -2
  53. package/dist/client/transaction/occ-retry.d.ts.map +1 -1
  54. package/dist/client/transaction/occ-retry.js.map +1 -1
  55. package/dist/client/transaction/transaction-client.d.ts +4 -6
  56. package/dist/client/transaction/transaction-client.d.ts.map +1 -1
  57. package/dist/client/transaction/transaction-client.js +7 -18
  58. package/dist/client/transaction/transaction-client.js.map +1 -1
  59. package/dist/client/union/client.d.ts +55 -0
  60. package/dist/client/union/client.d.ts.map +1 -0
  61. package/dist/client/union/client.js +74 -0
  62. package/dist/client/union/client.js.map +1 -0
  63. package/dist/index.d.ts +5 -2
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +5 -2
  66. package/dist/index.js.map +1 -1
  67. package/dist/pg/index.d.ts +13 -1
  68. package/dist/pg/index.d.ts.map +1 -1
  69. package/dist/pg/index.js +52 -5
  70. package/dist/pg/index.js.map +1 -1
  71. package/dist/pglite/index.d.ts +7 -6
  72. package/dist/pglite/index.d.ts.map +1 -1
  73. package/dist/pglite/index.js +18 -4
  74. package/dist/pglite/index.js.map +1 -1
  75. package/dist/schema/columns/array.d.ts +12 -8
  76. package/dist/schema/columns/array.d.ts.map +1 -1
  77. package/dist/schema/columns/array.js +11 -14
  78. package/dist/schema/columns/array.js.map +1 -1
  79. package/dist/schema/columns/bigint.d.ts +1 -1
  80. package/dist/schema/columns/bigint.d.ts.map +1 -1
  81. package/dist/schema/columns/bigint.js +1 -0
  82. package/dist/schema/columns/bigint.js.map +1 -1
  83. package/dist/schema/columns/boolean.d.ts +1 -1
  84. package/dist/schema/columns/boolean.d.ts.map +1 -1
  85. package/dist/schema/columns/boolean.js +1 -0
  86. package/dist/schema/columns/boolean.js.map +1 -1
  87. package/dist/schema/columns/bytea.d.ts +1 -1
  88. package/dist/schema/columns/bytea.d.ts.map +1 -1
  89. package/dist/schema/columns/bytea.js +1 -0
  90. package/dist/schema/columns/bytea.js.map +1 -1
  91. package/dist/schema/columns/char.d.ts +1 -1
  92. package/dist/schema/columns/char.d.ts.map +1 -1
  93. package/dist/schema/columns/char.js +1 -0
  94. package/dist/schema/columns/char.js.map +1 -1
  95. package/dist/schema/columns/date.d.ts +3 -3
  96. package/dist/schema/columns/date.d.ts.map +1 -1
  97. package/dist/schema/columns/date.js +1 -0
  98. package/dist/schema/columns/date.js.map +1 -1
  99. package/dist/schema/columns/double.d.ts +1 -1
  100. package/dist/schema/columns/double.d.ts.map +1 -1
  101. package/dist/schema/columns/double.js +1 -0
  102. package/dist/schema/columns/double.js.map +1 -1
  103. package/dist/schema/columns/guid.d.ts +57 -0
  104. package/dist/schema/columns/guid.d.ts.map +1 -0
  105. package/dist/schema/columns/guid.js +53 -0
  106. package/dist/schema/columns/guid.js.map +1 -0
  107. package/dist/schema/columns/identity.d.ts +6 -6
  108. package/dist/schema/columns/identity.d.ts.map +1 -1
  109. package/dist/schema/columns/identity.js +2 -0
  110. package/dist/schema/columns/identity.js.map +1 -1
  111. package/dist/schema/columns/int.d.ts +1 -1
  112. package/dist/schema/columns/int.d.ts.map +1 -1
  113. package/dist/schema/columns/int.js +1 -0
  114. package/dist/schema/columns/int.js.map +1 -1
  115. package/dist/schema/columns/interval.d.ts +4 -3
  116. package/dist/schema/columns/interval.d.ts.map +1 -1
  117. package/dist/schema/columns/interval.js +1 -0
  118. package/dist/schema/columns/interval.js.map +1 -1
  119. package/dist/schema/columns/json.d.ts +79 -2
  120. package/dist/schema/columns/json.d.ts.map +1 -1
  121. package/dist/schema/columns/json.js +158 -8
  122. package/dist/schema/columns/json.js.map +1 -1
  123. package/dist/schema/columns/numeric.d.ts +20 -3
  124. package/dist/schema/columns/numeric.d.ts.map +1 -1
  125. package/dist/schema/columns/numeric.js +60 -4
  126. package/dist/schema/columns/numeric.js.map +1 -1
  127. package/dist/schema/columns/real.d.ts +1 -1
  128. package/dist/schema/columns/real.d.ts.map +1 -1
  129. package/dist/schema/columns/real.js +1 -0
  130. package/dist/schema/columns/real.js.map +1 -1
  131. package/dist/schema/columns/record.d.ts +20 -0
  132. package/dist/schema/columns/record.d.ts.map +1 -0
  133. package/dist/schema/columns/record.js +21 -0
  134. package/dist/schema/columns/record.js.map +1 -0
  135. package/dist/schema/columns/smallint.d.ts +1 -1
  136. package/dist/schema/columns/smallint.d.ts.map +1 -1
  137. package/dist/schema/columns/smallint.js +1 -0
  138. package/dist/schema/columns/smallint.js.map +1 -1
  139. package/dist/schema/columns/text.d.ts +1 -1
  140. package/dist/schema/columns/text.d.ts.map +1 -1
  141. package/dist/schema/columns/text.js +1 -0
  142. package/dist/schema/columns/text.js.map +1 -1
  143. package/dist/schema/columns/time.d.ts +3 -3
  144. package/dist/schema/columns/time.d.ts.map +1 -1
  145. package/dist/schema/columns/time.js +1 -0
  146. package/dist/schema/columns/time.js.map +1 -1
  147. package/dist/schema/columns/timestamp.d.ts +6 -6
  148. package/dist/schema/columns/timestamp.d.ts.map +1 -1
  149. package/dist/schema/columns/timestamp.js +1 -0
  150. package/dist/schema/columns/timestamp.js.map +1 -1
  151. package/dist/schema/columns/uuid.d.ts +1 -1
  152. package/dist/schema/columns/uuid.d.ts.map +1 -1
  153. package/dist/schema/columns/uuid.js +1 -0
  154. package/dist/schema/columns/uuid.js.map +1 -1
  155. package/dist/schema/columns/varchar.d.ts +1 -1
  156. package/dist/schema/columns/varchar.d.ts.map +1 -1
  157. package/dist/schema/columns/varchar.js +1 -0
  158. package/dist/schema/columns/varchar.js.map +1 -1
  159. package/dist/schema/domain.d.ts +2 -2
  160. package/dist/schema/domain.d.ts.map +1 -1
  161. package/dist/schema/domain.js +2 -0
  162. package/dist/schema/domain.js.map +1 -1
  163. package/dist/schema/embedded.d.ts +31 -0
  164. package/dist/schema/embedded.d.ts.map +1 -0
  165. package/dist/schema/embedded.js +33 -0
  166. package/dist/schema/embedded.js.map +1 -0
  167. package/dist/schema/index.d.ts +8 -1
  168. package/dist/schema/index.d.ts.map +1 -1
  169. package/dist/schema/index.js +6 -1
  170. package/dist/schema/index.js.map +1 -1
  171. package/dist/schema/namespace.js.map +1 -1
  172. package/dist/schema/relations.d.ts +17 -5
  173. package/dist/schema/relations.d.ts.map +1 -1
  174. package/dist/schema/relations.js +9 -0
  175. package/dist/schema/relations.js.map +1 -1
  176. package/dist/schema/sequence.js.map +1 -1
  177. package/dist/schema/table.d.ts +2 -2
  178. package/dist/schema/table.d.ts.map +1 -1
  179. package/dist/schema/table.js.map +1 -1
  180. package/dist/schema/tenant.d.ts +31 -0
  181. package/dist/schema/tenant.d.ts.map +1 -0
  182. package/dist/schema/tenant.js +33 -0
  183. package/dist/schema/tenant.js.map +1 -0
  184. package/dist/schema/union.d.ts +25 -0
  185. package/dist/schema/union.d.ts.map +1 -0
  186. package/dist/schema/union.js +27 -0
  187. package/dist/schema/union.js.map +1 -0
  188. package/dist/schema/utils/column-validation.d.ts +19 -0
  189. package/dist/schema/utils/column-validation.d.ts.map +1 -0
  190. package/dist/schema/utils/column-validation.js +37 -0
  191. package/dist/schema/utils/column-validation.js.map +1 -0
  192. package/dist/schema/utils/date.js.map +1 -1
  193. package/dist/schema/utils/duration.d.ts +2 -2
  194. package/dist/schema/utils/duration.d.ts.map +1 -1
  195. package/dist/schema/utils/duration.js.map +1 -1
  196. package/dist/schema/utils/global-id.d.ts +67 -0
  197. package/dist/schema/utils/global-id.d.ts.map +1 -0
  198. package/dist/schema/utils/global-id.js +99 -0
  199. package/dist/schema/utils/global-id.js.map +1 -0
  200. package/dist/schema/utils/standard-schema.d.ts +30 -0
  201. package/dist/schema/utils/standard-schema.d.ts.map +1 -0
  202. package/dist/schema/utils/standard-schema.js +2 -0
  203. package/dist/schema/utils/standard-schema.js.map +1 -0
  204. package/package.json +21 -16
  205. package/dist/schema/utils/json.d.ts +0 -2
  206. package/dist/schema/utils/json.d.ts.map +0 -1
  207. package/dist/schema/utils/json.js +0 -12
  208. package/dist/schema/utils/json.js.map +0 -1
@@ -1,136 +1,213 @@
1
- import { sql, } from "@dsqlbase/core";
2
- import { isFilterType, } from "./base.js";
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");
3
10
  export class RequestNormalizer {
4
11
  _ctx;
12
+ _where = new WhereBuilder();
5
13
  constructor(context) {
6
14
  this._ctx = context;
7
15
  }
8
- _getWhereExpression(table, where) {
9
- if (!where) {
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") {
10
20
  return undefined;
11
21
  }
12
- const expressions = [];
13
- for (const [fieldName, condition] of Object.entries(where)) {
14
- if (fieldName === "and" && Array.isArray(condition)) {
15
- const exp = sql.and(condition
16
- .map((expr) => this._getWhereExpression(table, expr))
17
- .filter(Boolean));
18
- expressions.push(sql.wrap(exp));
19
- continue;
20
- }
21
- if (fieldName === "or" && Array.isArray(condition)) {
22
- const exp = sql.or(condition
23
- .map((expr) => this._getWhereExpression(table, expr))
24
- .filter(Boolean));
25
- expressions.push(sql.wrap(exp));
26
- continue;
27
- }
28
- if (fieldName === "not" &&
29
- typeof condition === "object" &&
30
- condition !== null &&
31
- !Array.isArray(condition)) {
32
- const shouldWrapNot = Object.keys(condition).length > 1;
33
- const expr = this._getWhereExpression(table, condition);
34
- if (expr) {
35
- expressions.push(shouldWrapNot ? sql.wrap(sql.not(expr)) : sql.not(expr));
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}".`);
36
27
  }
37
- continue;
28
+ entries.push(this._getFieldSelection(table, fieldName, field, isSelected));
38
29
  }
39
- const column = table.getColumn(fieldName);
40
- if (!column) {
41
- throw new Error(`Invalid field "${fieldName}" in where clause for table "${table.name}".`);
42
- }
43
- if (isFilterType(condition, "eq")) {
44
- expressions.push(sql.eq(column, condition.eq));
45
- continue;
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.`);
46
41
  }
47
- if (isFilterType(condition, "neq")) {
48
- expressions.push(sql.ne(column, condition.neq));
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) {
49
61
  continue;
50
62
  }
51
- if (isFilterType(condition, "gt")) {
52
- expressions.push(sql.gt(column, condition.gt));
53
- continue;
63
+ const field = group.getColumn(member);
64
+ if (!field) {
65
+ throw new Error(`Invalid field "${path}.${member}" in selection for table "${table.name}".`);
54
66
  }
55
- if (isFilterType(condition, "gte")) {
56
- expressions.push(sql.gte(column, condition.gte));
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) {
57
85
  continue;
58
86
  }
59
- if (isFilterType(condition, "lt")) {
60
- expressions.push(sql.lt(column, condition.lt));
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
+ }
61
92
  continue;
62
93
  }
63
- if (isFilterType(condition, "lte")) {
64
- expressions.push(sql.lte(column, condition.lte));
65
- continue;
94
+ if (column || !this._isRelation(table, fieldName)) {
95
+ throw new Error(`Invalid field "${fieldName}" in selection for table "${table.name}".`);
66
96
  }
67
- if (isFilterType(condition, "in")) {
68
- expressions.push(sql.in(column, condition.in));
69
- continue;
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.`);
70
101
  }
71
- if (isFilterType(condition, "between")) {
72
- expressions.push(sql `${column} BETWEEN ${sql.param(condition.between[0])} AND ${sql.param(condition.between[1])}`);
73
- continue;
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;
74
109
  }
75
- if (isFilterType(condition, "exists")) {
76
- if (condition.exists) {
77
- expressions.push(sql.isNotNull(column));
78
- }
79
- else {
80
- expressions.push(sql.isNull(column));
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" } }.`);
81
138
  }
139
+ keys.push(...this._getFieldOrderKeys(table, column, direction, [...path, name]));
82
140
  continue;
83
141
  }
84
- if (isFilterType(condition, "beginsWith")) {
85
- expressions.push(sql.like(column, `${condition.beginsWith}%`));
86
- continue;
142
+ if (!(column instanceof Column)) {
143
+ throw new Error(`Invalid field "${field}" in orderBy for table "${table.name}".`);
87
144
  }
88
- if (isFilterType(condition, "endsWith")) {
89
- expressions.push(sql.like(column, `%${condition.endsWith}`));
90
- continue;
145
+ if (!rulesOf(column).orderable) {
146
+ throw new Error(`Cannot order by the ${column.runtimeType} column "${field}" of "${table.name}".`);
91
147
  }
92
- if (isFilterType(condition, "contains")) {
93
- expressions.push(sql.like(column, `%${condition.contains}%`));
94
- continue;
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".`);
95
154
  }
96
- expressions.push(sql.eq(column, condition));
97
155
  }
98
- return sql.and(expressions);
156
+ return keys;
99
157
  }
100
- _getSelectionEntries(table, selection) {
101
- const entries = [];
102
- if (!selection || typeof selection === "boolean") {
103
- return entries;
104
- }
105
- for (const [fieldName, isSelected] of Object.entries(selection)) {
106
- if (isSelected) {
107
- const column = table.getColumn(fieldName);
108
- if (!column) {
109
- throw new Error(`Invalid field "${fieldName}" in selection for table "${table.name}".`);
110
- }
111
- entries.push([fieldName, column]);
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`;
112
168
  }
113
- }
114
- return entries;
169
+ return direction === "asc" ? sql `${column} ASC NULLS LAST` : sql `${column} DESC NULLS FIRST`;
170
+ });
115
171
  }
116
172
  _getOrderByEntries(table, orderBy) {
117
173
  if (!orderBy) {
118
174
  return undefined;
119
175
  }
120
- const entries = [];
121
- for (const [fieldName, direction] of Object.entries(orderBy)) {
122
- const column = table.getColumn(fieldName);
123
- if (!column) {
124
- throw new Error(`Invalid field "${fieldName}" in orderBy for table "${table.name}".`);
125
- }
126
- if (direction === "asc") {
127
- entries.push(sql `${column} ASC`);
128
- }
129
- else if (direction === "desc") {
130
- entries.push(sql `${column} DESC`);
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 });
131
193
  }
132
194
  }
133
- return entries;
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;
134
211
  }
135
212
  _getJoinEntries(table, join) {
136
213
  const entries = [];
@@ -145,29 +222,223 @@ export class RequestNormalizer {
145
222
  if (!targetTable) {
146
223
  throw new Error(`Relation "${fieldName}" in table "${table.name}" does not have a valid target table.`);
147
224
  }
225
+ if (targetTable instanceof Union) {
226
+ entries.push([
227
+ fieldName,
228
+ this._getUnionArgs(targetTable, query === true ? {} : query),
229
+ ]);
230
+ continue;
231
+ }
148
232
  const params = this._getSelectArgs(targetTable, query === true ? {} : query);
149
233
  entries.push([fieldName, params]);
150
234
  }
151
235
  return entries;
152
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
+ }
153
333
  _getMutationEntries(table, values) {
154
334
  const entries = [];
155
335
  for (const [fieldName, value] of Object.entries(values)) {
156
336
  const column = table.getColumn(fieldName);
157
- if (!column) {
337
+ if (column instanceof ColumnGroup) {
338
+ entries.push(...this._getGroupMutations(table, [fieldName], column, value));
339
+ continue;
340
+ }
341
+ if (!(column instanceof Column)) {
158
342
  throw new Error(`Invalid field "${fieldName}" in update values for table "${table.name}".`);
159
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
+ }
160
349
  entries.push([fieldName, value]);
161
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
+ }
162
390
  return entries;
163
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
+ }
164
432
  _getSelectArgs(table, args) {
165
- const selection = this._getSelectionEntries(table, args.select);
166
- const where = this._getWhereExpression(table, args.where);
167
- const join = this._getJoinEntries(table, args.join);
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);
168
436
  const orderBy = this._getOrderByEntries(table, args.orderBy);
437
+ if (args.distinct) {
438
+ this._assertDistinct(table, selection.select);
439
+ }
169
440
  return {
170
- select: selection,
441
+ select: selection.select,
171
442
  where,
172
443
  join,
173
444
  orderBy,
@@ -177,9 +448,158 @@ export class RequestNormalizer {
177
448
  };
178
449
  }
179
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;
180
490
  return {
181
- mode,
182
- args: this._getSelectArgs(table, args),
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) },
183
603
  };
184
604
  }
185
605
  normalizeInsert(table, args, mode) {
@@ -195,7 +615,7 @@ export class RequestNormalizer {
195
615
  }
196
616
  normalizeUpdate(table, args, mode) {
197
617
  const values = this._getMutationEntries(table, args.set);
198
- const where = this._getWhereExpression(table, args.where);
618
+ const where = this._where.buildRequired(table, args.where, "update");
199
619
  const returning = this._getSelectionEntries(table, args.return);
200
620
  return {
201
621
  mode,
@@ -207,7 +627,7 @@ export class RequestNormalizer {
207
627
  };
208
628
  }
209
629
  normalizeDelete(table, args, mode) {
210
- const where = this._getWhereExpression(table, args.where);
630
+ const where = this._where.buildRequired(table, args.where, "delete");
211
631
  const returning = this._getSelectionEntries(table, args.return);
212
632
  return {
213
633
  mode,