@kiri-orm/core 0.1.7 → 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 (99) hide show
  1. package/README.md +27 -15
  2. package/dist/types/client/model-handle.d.ts +4 -1
  3. package/dist/types/connection.d.ts +39 -0
  4. package/dist/types/crud/database-errors.d.ts +61 -0
  5. package/dist/types/crud/errors.d.ts +10 -0
  6. package/dist/types/crud/fast-path.d.ts +73 -0
  7. package/dist/types/crud/index.d.ts +4 -1
  8. package/dist/types/crud/insert-many.d.ts +1 -1
  9. package/dist/types/crud/order.d.ts +28 -0
  10. package/dist/types/crud/repository.d.ts +5 -3
  11. package/dist/types/crud/upsert.d.ts +39 -0
  12. package/dist/types/crud/value.d.ts +39 -0
  13. package/dist/types/dialect/index.d.ts +1 -1
  14. package/dist/types/dialect/transaction-guard.d.ts +19 -18
  15. package/dist/types/domain/compile.d.ts +17 -0
  16. package/dist/types/fields/filter-value.d.ts +21 -0
  17. package/dist/types/fields/registry.d.ts +1 -0
  18. package/dist/types/fields/storage.d.ts +28 -0
  19. package/dist/types/fields/types/date.d.ts +5 -0
  20. package/dist/types/fields/types/decimal.d.ts +40 -0
  21. package/dist/types/global/index.d.ts +1 -0
  22. package/dist/types/global/transaction.d.ts +10 -13
  23. package/dist/types/index.d.ts +2 -0
  24. package/dist/types/meta/snapshot.d.ts +10 -0
  25. package/dist/types/meta/upsert.d.ts +16 -0
  26. package/dist/types/migrations/diff.d.ts +25 -2
  27. package/dist/types/models/constraints.d.ts +27 -0
  28. package/dist/types/schema/alter-column.d.ts +46 -0
  29. package/dist/types/schema/build-column.d.ts +11 -0
  30. package/dist/types/schema/introspect-indexes.d.ts +9 -0
  31. package/dist/types/transaction/after-commit.d.ts +42 -0
  32. package/dist/types/transaction/context.d.ts +39 -0
  33. package/dist/types/uow/entity.d.ts +39 -29
  34. package/dist/types/uow/hooks.d.ts +6 -1
  35. package/dist/types/uow/lifecycle.d.ts +82 -0
  36. package/dist/types/uow/unit-of-work.d.ts +11 -7
  37. package/package.json +5 -4
  38. package/src/client/model-handle.js +14 -4
  39. package/src/client/orm-client.js +10 -5
  40. package/src/connection.js +34 -4
  41. package/src/crud/aggregate-filter.js +8 -2
  42. package/src/crud/aggregate-spec.js +2 -2
  43. package/src/crud/aggregate.js +16 -5
  44. package/src/crud/create-many.js +52 -29
  45. package/src/crud/database-errors.js +107 -0
  46. package/src/crud/errors.js +14 -0
  47. package/src/crud/fast-path.js +449 -0
  48. package/src/crud/index.js +4 -1
  49. package/src/crud/insert-many.js +25 -7
  50. package/src/crud/map-filter.js +2 -1
  51. package/src/crud/order.js +59 -9
  52. package/src/crud/repository.js +106 -38
  53. package/src/crud/row-mapping.js +32 -7
  54. package/src/crud/upsert.js +203 -0
  55. package/src/crud/value.js +71 -0
  56. package/src/dialect/index.js +1 -1
  57. package/src/dialect/transaction-guard.js +216 -45
  58. package/src/domain/compile.js +85 -12
  59. package/src/dto/field-schema.js +5 -0
  60. package/src/fields/default-registry.js +3 -1
  61. package/src/fields/filter-value.js +87 -0
  62. package/src/fields/registry.js +1 -0
  63. package/src/fields/storage.js +50 -0
  64. package/src/fields/types/date.js +16 -3
  65. package/src/fields/types/decimal.js +147 -0
  66. package/src/fields/types/integer.js +7 -0
  67. package/src/global/connect.js +2 -2
  68. package/src/global/create-model.js +59 -57
  69. package/src/global/errors.js +1 -1
  70. package/src/global/index.js +1 -0
  71. package/src/global/transaction.js +12 -14
  72. package/src/index.js +2 -0
  73. package/src/meta/schema.js +10 -0
  74. package/src/meta/snapshot.js +5 -0
  75. package/src/meta/upsert.js +28 -0
  76. package/src/migrations/describe.js +49 -0
  77. package/src/migrations/diff.js +50 -7
  78. package/src/migrations/generate.js +38 -2
  79. package/src/migrations/render.js +30 -12
  80. package/src/migrations/runner.js +2 -1
  81. package/src/models/constraints.js +96 -0
  82. package/src/models/define-model.js +4 -0
  83. package/src/models/inheritance.js +4 -1
  84. package/src/models/registry.js +2 -1
  85. package/src/relations/cascade-delete.js +2 -1
  86. package/src/relations/eager-load.js +45 -40
  87. package/src/reports/report-handle.js +2 -1
  88. package/src/schema/alter-column.js +219 -0
  89. package/src/schema/build-column.js +28 -2
  90. package/src/schema/default-column-builders.js +16 -2
  91. package/src/schema/introspect-indexes.js +22 -0
  92. package/src/schema/sync.js +15 -1
  93. package/src/transaction/after-commit.js +142 -0
  94. package/src/transaction/context.js +84 -0
  95. package/src/uow/entity.js +133 -133
  96. package/src/uow/hooks.js +9 -0
  97. package/src/uow/lifecycle.js +162 -0
  98. package/src/uow/unit-of-work.js +44 -56
  99. package/src/uow/with-unit-of-work.js +2 -1
@@ -0,0 +1,449 @@
1
+ import { castValue } from "../fields/cast-value.js";
2
+ import { toStorage, DialectValue } from "../fields/storage.js";
3
+ import { parseDomain } from "../domain/parse.js";
4
+ import { castLeafValue, likeToGlob } from "../domain/compile.js";
5
+ import { filterValue } from "../fields/filter-value.js";
6
+ import { SchemaChangedError } from "./errors.js";
7
+ import { resolveOrder } from "./order.js";
8
+
9
+ /**
10
+ * The direct path for find(), findOne(), inserts, and updates / deletes by filter (since 0.2.0).
11
+ *
12
+ * Knex builds every query from scratch: a builder object, a compiler pass, then the driver parses
13
+ * the SQL text again. For the queries an application sends most - rows of one table matched on
14
+ * its own fields, sorted and paged - that work is the same every time. Here such a find is written
15
+ * as SQL text directly, and the statement the database prepared for that text is reused:
16
+ *
17
+ * - SQLite (better-sqlite3): the prepared statement, cached per connection.
18
+ * - Postgres (pg): a named prepared statement, parsed and planned once per connection.
19
+ * `createConnection({ preparedStatements: false })` sends unnamed statements instead, for
20
+ * poolers that don't keep a session per client (pgbouncer in transaction mode).
21
+ *
22
+ * Everything else still goes through Knex: relation paths in a filter ("author.name"), computed
23
+ * fields, `nulls` ordering, locks, a Knex instance configured with wrapIdentifier /
24
+ * postProcessResponse / debug, any other driver. The compile functions return null for those and
25
+ * the caller builds the query with Knex as before.
26
+ *
27
+ * Nothing a caller can see changes: the values bound are the ones the Knex path binds (the same
28
+ * casting functions produce them), the query runs on the connection Knex would use (the pool, or
29
+ * the open transaction's connection), and the connection's `query` / `query-response` /
30
+ * `query-error` events fire as they do for Knex queries, so query logging, the N+1 monitor and
31
+ * tests that count queries see these too.
32
+ */
33
+
34
+ const SQLITE_STATEMENTS_PER_CONNECTION = 500;
35
+ // Postgres keeps every named statement a session prepared until the session ends, so each pooled
36
+ // connection holds at most this many of ours (since 0.2.0); past it, new SQL runs unnamed.
37
+ export const POSTGRES_STATEMENTS_PER_CONNECTION = 256;
38
+ // The SQL text -> name map is shared by a connection's pool; it starts over past this many.
39
+ const POSTGRES_STATEMENT_NAMES = 2000;
40
+ // A statement this long (a long `in` list) is unlikely to come again: run it without caching it.
41
+ const CACHEABLE_SQL_LENGTH = 4000;
42
+
43
+ /** Per Knex config object (shared by a connection's client and its transactions' clients). */
44
+ const settingsByConfig = new WeakMap();
45
+ let statementSequence = 0;
46
+ let queryUid = 0;
47
+
48
+ /**
49
+ * What the direct path needs to know about a connection, or null when it doesn't apply to it.
50
+ *
51
+ * @param {import('knex').Knex.Client} client - the connection's own (non-transaction) client
52
+ */
53
+ function settingsOf(client) {
54
+ const config = client?.config;
55
+ if (!config) return null;
56
+ let settings = settingsByConfig.get(config);
57
+ if (settings !== undefined) return settings;
58
+ settings = null;
59
+ const name = String(config.client ?? "");
60
+ const driver = name === "better-sqlite3" ? "sqlite" : name === "pg" || name === "postgres" || name === "postgresql" ? "postgres" : null;
61
+ const plain = !config.wrapIdentifier && !config.postProcessResponse && !config.debug && config.kiriFastPath !== false;
62
+ if (driver && plain) {
63
+ settings = {
64
+ dialect: driver,
65
+ lower: config.kiriLower ? "kiri_lower" : "LOWER",
66
+ named: driver === "postgres" && config.kiriPreparedStatements !== false,
67
+ names: new Map(), // Postgres: SQL text -> statement name
68
+ generation: 0, // Postgres: bumped whenever every statement name so far is retired
69
+ nullAsDefault: Boolean(config.useNullAsDefault), // SQLite: what an unset column of a multi-row insert gets
70
+ watching: false,
71
+ };
72
+ }
73
+ settingsByConfig.set(config, settings);
74
+ // Listening needs the connection's own client: a transaction's client is thrown away with it.
75
+ if (settings?.named && !settings.watching && !client.transacting) watchSchemaChanges(client, settings);
76
+ return settings;
77
+ }
78
+
79
+ /**
80
+ * A Postgres prepared statement fails ("cached plan must not change result type") once a table it
81
+ * reads changes shape. DDL this connection runs - sync, migrations, a raw ALTER, in a transaction or
82
+ * not - retires every statement name so far; the next find prepares under a new one.
83
+ */
84
+ function watchSchemaChanges(client, settings) {
85
+ if (typeof client.on !== "function") return;
86
+ settings.watching = true;
87
+ client.on("query", (query) => {
88
+ if (typeof query?.sql === "string" && DDL.test(query.sql)) retireStatements(settings);
89
+ });
90
+ }
91
+
92
+ // DDL, after any leading whitespace and SQL comments.
93
+ const DDL = /^(?:\s+|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*(alter|drop|create|comment|truncate)\b/i;
94
+
95
+ /** Every statement name so far goes out of use; each connection deallocates its own on next use. */
96
+ function retireStatements(settings) {
97
+ settings.names.clear();
98
+ settings.generation++;
99
+ }
100
+
101
+ const quote = (identifier) => (identifier === "*" ? "*" : `"${String(identifier).replace(/"/g, '""')}"`);
102
+ const quoteTable = (name) => String(name).split(".").map(quote).join(".");
103
+
104
+ /** The quoted table and column names of a model, computed once per model descriptor. */
105
+ const quotedByModel = new WeakMap();
106
+ function quotedNames(model) {
107
+ let names = quotedByModel.get(model);
108
+ if (!names) {
109
+ const columns = {};
110
+ for (const [field, column] of Object.entries(model.columns)) columns[field] = quote(column);
111
+ names = { table: quoteTable(model.tableName), columns, all: Object.values(columns).join(", ") };
112
+ quotedByModel.set(model, names);
113
+ }
114
+ return names;
115
+ }
116
+
117
+ class Unsupported extends Error {}
118
+ const UNSUPPORTED = new Unsupported();
119
+
120
+ /** Collects bound values and writes their placeholders. */
121
+ class Bindings {
122
+ constructor(dialect) {
123
+ this.dialect = dialect;
124
+ this.values = [];
125
+ }
126
+
127
+ /** A placeholder for `value` (cast and in storage form), or throws UNSUPPORTED for a value Knex would bind differently. */
128
+ add(value) {
129
+ if (value instanceof DialectValue) value = value.resolve(this.dialect);
130
+ if (value === undefined) throw UNSUPPORTED; // Knex reports undefined bindings: let it
131
+ if (this.dialect === "sqlite") {
132
+ // What Knex's better-sqlite3 client does to bindings before it runs a statement.
133
+ if (value instanceof Date) value = value.valueOf();
134
+ else if (typeof value === "boolean") value = Number(value);
135
+ }
136
+ if (!isPlainBinding(value)) throw UNSUPPORTED;
137
+ this.values.push(value);
138
+ return this.dialect === "postgres" ? `$${this.values.length}` : "?";
139
+ }
140
+ }
141
+
142
+ /** Postgres: one array parameter for a whole `in` list (`= ANY($1)`), whatever its length. */
143
+ Bindings.prototype.addArray = function addArray(values) {
144
+ const resolved = values.map((value) => (value instanceof DialectValue ? value.resolve(this.dialect) : value));
145
+ if (!resolved.every((value) => value !== undefined && isPlainBinding(value))) throw UNSUPPORTED;
146
+ this.values.push(resolved);
147
+ return `$${this.values.length}`;
148
+ };
149
+
150
+ function isPlainBinding(value) {
151
+ const type = typeof value;
152
+ return value === null || type === "string" || type === "number" || type === "bigint" || type === "boolean" || value instanceof Date || value instanceof Uint8Array;
153
+ }
154
+
155
+ /**
156
+ * The SQL and bound values for a find(), or null when the direct path doesn't handle it (the caller
157
+ * then builds the query with Knex). Throws the errors the Knex path would for a bad filter, order or
158
+ * page - the same functions validate and cast both.
159
+ *
160
+ * @param {import('knex').Knex} baseDb - the connection (not a transaction)
161
+ * @param {object} model
162
+ * @param {Record<string, unknown>|unknown[]} filter
163
+ * @param {string[]|null} columns - planSelect().columns
164
+ * @param {{ orderBy?: unknown, limit?: number, offset?: number, lock?: unknown }} options
165
+ * @param {import('../fields/registry.js').FieldTypeRegistry} registry
166
+ * @returns {{ sql: string, values: unknown[], settings: object } | null}
167
+ */
168
+ export function compileFastFind(baseDb, model, filter, columns, options, registry) {
169
+ if (options.lock !== undefined) return null;
170
+ const settings = settingsOf(baseDb.client);
171
+ if (!settings) return null;
172
+ try {
173
+ const names = quotedNames(model);
174
+ const bindings = new Bindings(settings.dialect);
175
+ const where = condition(filter, model, names, bindings, settings, registry);
176
+
177
+ const order = resolveOrder(model, options);
178
+ let orderSql = "";
179
+ for (const { field, direction, nulls } of order) {
180
+ if (nulls !== undefined) return null; // NULLS FIRST/LAST: Knex's path (orderWithNulls)
181
+ orderSql += `${orderSql ? ", " : " order by "}${names.columns[field]} ${direction}`;
182
+ }
183
+
184
+ // Postgres prepared statements name every column: a column added to the table later (a
185
+ // migration run by another process) then doesn't change what the statement returns.
186
+ const select = columns ? columns.map(quote).join(", ") : returnedColumns(settings, names);
187
+ let sql = `select ${select} from ${names.table}${where ? ` where ${where}` : ""}${orderSql}`;
188
+ const { limit, offset } = options;
189
+ const skip = offset !== undefined && offset > 0; // OFFSET 0 is left out, as on the Knex path
190
+ if (limit !== undefined || (skip && settings.dialect === "sqlite")) sql += ` limit ${bindings.add(limit ?? -1)}`;
191
+ if (skip) sql += ` offset ${bindings.add(offset)}`;
192
+ return { sql, values: bindings.values, settings, method: "select" };
193
+ } catch (error) {
194
+ if (error === UNSUPPORTED) return null;
195
+ throw error;
196
+ }
197
+ }
198
+
199
+ /** What a Postgres statement returns for a model's rows: every column by name (see compileFastFind()). */
200
+ function returnedColumns(settings, names) {
201
+ return settings.named ? names.all : "*";
202
+ }
203
+
204
+ /**
205
+ * INSERT ... RETURNING for rows already in column form (toRow() output), or null for Knex. Unset
206
+ * columns get the column's DEFAULT on Postgres and NULL on SQLite (Knex's `useNullAsDefault`), as a
207
+ * Knex multi-row insert gives them.
208
+ *
209
+ * @param {import('knex').Knex} db - the connection or a transaction on it
210
+ * @param {object} model
211
+ * @param {Record<string, unknown>[]} rows
212
+ */
213
+ export function compileFastInsert(db, model, rows) {
214
+ const settings = settingsOf(db.client);
215
+ if (!settings || rows.length === 0 || (settings.dialect === "sqlite" && !settings.nullAsDefault)) return null;
216
+ try {
217
+ const columnSet = new Set();
218
+ for (const row of rows) for (const key of Object.keys(row)) columnSet.add(key);
219
+ if (columnSet.size === 0) return null; // DEFAULT VALUES rows: insertDefaultRows()
220
+ const columns = [...columnSet].sort();
221
+ const names = quotedNames(model);
222
+ const bindings = new Bindings(settings.dialect);
223
+ const tuples = rows.map((row) => `(${columns.map((column) => (row[column] === undefined ? (settings.dialect === "postgres" ? "DEFAULT" : bindings.add(null)) : bindings.add(row[column]))).join(", ")})`);
224
+ const sql = `insert into ${names.table} (${columns.map(quote).join(", ")}) values ${tuples.join(", ")} returning ${returnedColumns(settings, names)}`;
225
+ return { sql, values: bindings.values, settings, method: "insert" };
226
+ } catch (error) {
227
+ if (error === UNSUPPORTED) return null;
228
+ throw error;
229
+ }
230
+ }
231
+
232
+ /**
233
+ * UPDATE ... SET ... WHERE, returning the number of rows changed, or null for Knex. `row` is in
234
+ * column form; `expressions` are Value.increment() / decrement() ({ column, operator, amount }).
235
+ * Filters compile as for find(); one that compiles to no condition at all is left to Knex.
236
+ */
237
+ export function compileFastUpdate(db, model, filter, row, expressions, registry) {
238
+ const settings = settingsOf(db.client);
239
+ if (!settings) return null;
240
+ try {
241
+ const names = quotedNames(model);
242
+ const bindings = new Bindings(settings.dialect);
243
+ const sets = [];
244
+ for (const [column, value] of Object.entries(row)) if (value !== undefined) sets.push(`${quote(column)} = ${bindings.add(value)}`);
245
+ for (const { column, operator, amount } of expressions) sets.push(`${quote(column)} = ${quote(column)} ${operator} ${bindings.add(amount)}`);
246
+ if (sets.length === 0) return null;
247
+ const where = condition(filter, model, names, bindings, settings, registry);
248
+ if (!where) return null;
249
+ return { sql: `update ${names.table} set ${sets.join(", ")} where ${where}`, values: bindings.values, settings, method: "update" };
250
+ } catch (error) {
251
+ if (error === UNSUPPORTED) return null;
252
+ throw error;
253
+ }
254
+ }
255
+
256
+ /** DELETE ... WHERE, returning the number of rows deleted, or null for Knex. */
257
+ export function compileFastDelete(db, model, filter, registry) {
258
+ const settings = settingsOf(db.client);
259
+ if (!settings) return null;
260
+ try {
261
+ const names = quotedNames(model);
262
+ const bindings = new Bindings(settings.dialect);
263
+ const where = condition(filter, model, names, bindings, settings, registry);
264
+ if (!where) return null;
265
+ return { sql: `delete from ${names.table} where ${where}`, values: bindings.values, settings, method: "del" };
266
+ } catch (error) {
267
+ if (error === UNSUPPORTED) return null;
268
+ throw error;
269
+ }
270
+ }
271
+
272
+ function condition(filter, model, names, bindings, settings, registry) {
273
+ return Array.isArray(filter) ? domainCondition(filter, model, names, bindings, settings, registry) : objectCondition(filter ?? {}, model, names, bindings, registry);
274
+ }
275
+
276
+ /** `{ field: value, ... }`: equality on stored fields, ANDed (null is IS NULL). */
277
+ function objectCondition(filter, model, names, bindings, registry) {
278
+ const parts = [];
279
+ for (const [fieldName, value] of Object.entries(filter)) {
280
+ const field = Object.prototype.hasOwnProperty.call(model.fields, fieldName) ? model.fields[fieldName] : undefined;
281
+ if (!field || value === undefined) throw UNSUPPORTED; // computed field, unknown field (Knex's path reports it), undefined
282
+ const column = names.columns[fieldName];
283
+ parts.push(value === null ? `${column} is null` : `${column} = ${bindings.add(filterValue(field, "=", value, registry))}`);
284
+ }
285
+ return parts.join(" and ");
286
+ }
287
+
288
+ function domainCondition(domain, model, names, bindings, settings, registry) {
289
+ return nodeCondition(parseDomain(domain), model, names, bindings, settings, registry);
290
+ }
291
+
292
+ /** One domain node as SQL; "" for an empty AND (matches everything). Same order of casting as compileNode(). */
293
+ function nodeCondition(node, model, names, bindings, settings, registry) {
294
+ if (node.type === "leaf") return leafCondition(node, model, names, bindings, settings, registry);
295
+ if (node.type === "and" || node.type === "or") {
296
+ if (node.children.length === 0 && node.type === "and") return "";
297
+ let parts = node.children.map((child) => nodeCondition(child, model, names, bindings, settings, registry));
298
+ // An empty group matches everything: in an AND it drops out. Knex also drops one from an OR or a
299
+ // NOT rather than treating it as "true" - leave those to Knex.
300
+ if (node.type === "and") parts = parts.filter((part) => part !== "");
301
+ else if (parts.some((part) => part === "")) throw UNSUPPORTED;
302
+ if (parts.length === 0) return "";
303
+ return parts.length === 1 ? parts[0] : `(${parts.join(node.type === "and" ? " and " : " or ")})`;
304
+ }
305
+ const inner = nodeCondition(node.children[0], model, names, bindings, settings, registry);
306
+ if (inner === "") throw UNSUPPORTED;
307
+ return `not (${inner})`;
308
+ }
309
+
310
+ function leafCondition(node, model, names, bindings, settings, registry) {
311
+ const { field: fieldName, op } = node;
312
+ if (fieldName.includes(".") || !Object.prototype.hasOwnProperty.call(model.fields, fieldName)) throw UNSUPPORTED; // relation path, computed, unknown
313
+ const field = model.fields[fieldName];
314
+ const column = names.columns[fieldName];
315
+ const value = castLeafValue(field, fieldName, op, node.value, registry);
316
+ switch (op) {
317
+ case "=":
318
+ return value === null ? `${column} is null` : `${column} = ${bindings.add(value)}`;
319
+ case "!=":
320
+ return value === null ? `${column} is not null` : `${column} != ${bindings.add(value)}`;
321
+ case ">":
322
+ case ">=":
323
+ case "<":
324
+ case "<=":
325
+ return `${column} ${op} ${bindings.add(value)}`;
326
+ case "in":
327
+ case "not in":
328
+ if (value.length === 0) return op === "in" ? "1 = 0" : "1 = 1";
329
+ // Postgres: one array parameter, so every list length is the same statement (one prepared
330
+ // statement, not one per length) and lists past 65,535 values fit. Same NULL semantics as IN.
331
+ if (settings.dialect === "postgres") return `${column} ${op === "in" ? "= ANY" : "<> ALL"}(${bindings.addArray(value)})`;
332
+ return `${column} ${op} (${value.map((v) => bindings.add(v)).join(", ")})`;
333
+ case "like":
334
+ return settings.dialect === "sqlite" ? `${column} GLOB ${bindings.add(likeToGlob(value))}` : `${column} like ${bindings.add(value)}`;
335
+ case "ilike":
336
+ return settings.dialect === "postgres" ? `${column} ILIKE ${bindings.add(value)}` : `${settings.lower}(${column}) LIKE ${settings.lower}(${bindings.add(value)}) ESCAPE '\\'`;
337
+ default:
338
+ throw UNSUPPORTED;
339
+ }
340
+ }
341
+
342
+ /** Retired on a Postgres error that means the statement no longer fits the table. */
343
+ const STALE_STATEMENT = new Set(["0A000", "26000", "42703", "42P01"]);
344
+ // Of those, the ones that mean only the cached plan is stale (not a missing table or column).
345
+ const PLAN_CHANGED = new Set(["0A000", "26000"]);
346
+
347
+ /**
348
+ * Runs a compiled statement on `db` (the connection, or the transaction it resolved to): the rows
349
+ * of a select or an insert ... returning, the number of rows an update or delete changed - or
350
+ * undefined when a cached Postgres statement went stale outside a transaction (it didn't run),
351
+ * in which case the caller runs the query through Knex instead.
352
+ *
353
+ * @param {import('knex').Knex} db
354
+ * @param {{ sql: string, values: unknown[], settings: object, method: string }} compiled
355
+ * @returns {Promise<Record<string, unknown>[] | number | undefined>}
356
+ */
357
+ export async function runFast(db, { sql, values, settings, method }) {
358
+ const client = db.client;
359
+ if (db.isTransaction && db.isCompleted?.()) return undefined; // Knex raises its "already complete" error
360
+ const connection = await client.acquireConnection();
361
+ const event = {
362
+ method,
363
+ options: {},
364
+ timeout: false,
365
+ cancelOnTimeout: false,
366
+ bindings: values,
367
+ sql,
368
+ __knexQueryUid: `kiri${++queryUid}`,
369
+ __knexUid: connection.__knexUid,
370
+ __knexTxId: connection.__knexTxId,
371
+ };
372
+ try {
373
+ client.emit("query", event);
374
+ let result;
375
+ try {
376
+ result = settings.dialect === "sqlite" ? sqliteRun(connection, sql, values) : await postgresRun(connection, sql, values, settings, method);
377
+ } catch (error) {
378
+ if (settings.dialect === "postgres" && settings.named && STALE_STATEMENT.has(error?.code)) {
379
+ retireStatements(settings);
380
+ if (!db.isTransaction) return undefined; // the statement didn't run: Knex can just run it
381
+ if (PLAN_CHANGED.has(error.code)) {
382
+ client.emit("query-error", error, event);
383
+ throw new SchemaChangedError(
384
+ "A table this transaction reads was changed by another connection (a migration?) after this connection " +
385
+ "prepared a query on it, so Postgres aborted the transaction. Nothing in it was committed: retry the " +
386
+ `whole transaction. (${error.message})`,
387
+ { cause: error }
388
+ );
389
+ }
390
+ }
391
+ error.message = `${client.config?.compileSqlOnError === false ? sql : formatSql(client, sql, values, settings.dialect)} - ${error.message}`;
392
+ client.emit("query-error", error, event);
393
+ throw error;
394
+ }
395
+ client.emit("query-response", result, event, undefined);
396
+ return result;
397
+ } finally {
398
+ client.releaseConnection(connection);
399
+ }
400
+ }
401
+
402
+ const sqliteStatements = new WeakMap();
403
+
404
+ function sqliteRun(connection, sql, values) {
405
+ let statements = sqliteStatements.get(connection);
406
+ if (!statements) sqliteStatements.set(connection, (statements = new Map()));
407
+ let statement = statements.get(sql);
408
+ if (!statement) {
409
+ statement = connection.prepare(sql);
410
+ if (sql.length <= CACHEABLE_SQL_LENGTH) {
411
+ if (statements.size >= SQLITE_STATEMENTS_PER_CONNECTION) statements.delete(statements.keys().next().value);
412
+ statements.set(sql, statement);
413
+ }
414
+ }
415
+ return statement.reader ? statement.all(values) : statement.run(values).changes;
416
+ }
417
+
418
+ /** pg connection -> { generation, names } - the statements of ours this session has prepared. */
419
+ const preparedByConnection = new WeakMap();
420
+
421
+ async function postgresRun(connection, sql, values, settings, method) {
422
+ let query = { text: sql, values };
423
+ if (settings.named && sql.length <= CACHEABLE_SQL_LENGTH) {
424
+ let name = settings.names.get(sql);
425
+ if (!name) {
426
+ if (settings.names.size >= POSTGRES_STATEMENT_NAMES) retireStatements(settings);
427
+ settings.names.set(sql, (name = `kiri_${++statementSequence}`));
428
+ }
429
+ let held = preparedByConnection.get(connection);
430
+ if (!held || held.generation !== settings.generation) {
431
+ // Statements prepared under retired names are never used again: free them on the server.
432
+ if (held?.names.size) await connection.query("DEALLOCATE ALL").catch(() => {});
433
+ preparedByConnection.set(connection, (held = { generation: settings.generation, names: new Set() }));
434
+ }
435
+ if (held.names.has(name) || held.names.size < POSTGRES_STATEMENTS_PER_CONNECTION) {
436
+ held.names.add(name);
437
+ query = { name, text: sql, values };
438
+ }
439
+ }
440
+ const result = await connection.query(query);
441
+ return method === "update" || method === "del" ? result.rowCount : result.rows;
442
+ }
443
+
444
+ /** The SQL with its values written in, as Knex puts it in an error message. */
445
+ function formatSql(client, sql, values, dialect) {
446
+ if (dialect !== "sqlite" || typeof client._escapeBinding !== "function") return sql;
447
+ let index = 0;
448
+ return sql.replace(/\?/g, (match) => (index < values.length ? client._escapeBinding(values[index++], {}) : match));
449
+ }
package/src/crud/index.js CHANGED
@@ -1,12 +1,15 @@
1
1
  export { Repository, createRepository } from "./repository.js";
2
2
  export { RepositoryFactory } from "./repository-factory.js";
3
3
  export { runInTransaction } from "./transaction.js";
4
- export { ValidationError } from "./errors.js";
4
+ export { ValidationError, SchemaChangedError } from "./errors.js";
5
+ export { DatabaseConstraintError, UniqueViolationError, ForeignKeyViolationError, NotNullViolationError, CheckViolationError, OutOfRangeError, translateDatabaseError } from "./database-errors.js";
5
6
  export { fromRow, toRow } from "./row-mapping.js";
6
7
  export { prepareWrite, assertPrimaryKeyUntouched } from "./prepare-write.js";
7
8
  export { mapFilterToColumns } from "./map-filter.js";
8
9
  export { resolveWhere, isEmptyFilter } from "./resolve-where.js";
9
10
  export { createRecords } from "./create-many.js";
11
+ export { upsertRecords } from "./upsert.js";
12
+ export { Value, ValueExpression } from "./value.js";
10
13
  export { advanceSequence, syncSequence, syncRegistrySequences } from "./sequence.js";
11
14
  export { planAggregate } from "./aggregate-spec.js";
12
15
  export { runAggregate, buildAggregateQuery, countAggregateGroups } from "./aggregate.js";
@@ -1,6 +1,9 @@
1
+ import { compileFastInsert, runFast } from "./fast-path.js";
1
2
  import { fromRow, toRow } from "./row-mapping.js";
2
3
  import { primaryKeyOf } from "../models/primary-key.js";
3
4
  import { advanceSequence, isPostgres } from "./sequence.js";
5
+ import { toStorage, dialectOfClient } from "../fields/storage.js";
6
+ import { defaultFieldTypeRegistry } from "../fields/default-registry.js";
4
7
 
5
8
  /**
6
9
  * Per-statement limits, by dialect family.
@@ -146,14 +149,22 @@ export function alignToInput(model, valuesList, records) {
146
149
  * @param {import('../models/define-model.js').ModelDescriptor} model
147
150
  * @param {Record<string, unknown>} values
148
151
  */
149
- export function serializeJsonFields(model, values) {
152
+ export function serializeJsonFields(model, values, fieldTypeRegistry = defaultFieldTypeRegistry) {
150
153
  let serialized = null;
151
154
  for (const [fieldName, field] of Object.entries(model.fields)) {
152
- if (field.type !== "json") continue;
153
155
  const value = values[fieldName];
154
156
  if (value === null || value === undefined) continue;
155
- serialized ??= { ...values };
156
- serialized[fieldName] = JSON.stringify(value);
157
+ if (field.type === "json") {
158
+ serialized ??= { ...values };
159
+ serialized[fieldName] = JSON.stringify(value);
160
+ continue;
161
+ }
162
+ // Since 0.2.0: a type whose stored form differs per database (decimal) - see fields/storage.js.
163
+ const stored = toStorage(field, value, fieldTypeRegistry);
164
+ if (stored !== value) {
165
+ serialized ??= { ...values };
166
+ serialized[fieldName] = stored;
167
+ }
157
168
  }
158
169
  return serialized ?? values;
159
170
  }
@@ -188,6 +199,13 @@ async function insertDefaultRows(db, table, count) {
188
199
  return returned;
189
200
  }
190
201
 
202
+ /** One INSERT ... RETURNING: written directly when it can be (crud/fast-path.js), else by Knex. */
203
+ async function insertRows(db, model, rows) {
204
+ const fast = compileFastInsert(db, model, rows);
205
+ const returned = fast ? await runFast(db, fast) : undefined;
206
+ return returned ?? db(model.tableName).insert(rows).returning("*");
207
+ }
208
+
191
209
  export async function insertRecords(
192
210
  db,
193
211
  model,
@@ -205,13 +223,13 @@ export async function insertRecords(
205
223
 
206
224
  for (const chunk of chunkArray(valuesList, size)) {
207
225
  const rows = chunk.map((values) =>
208
- toRow(model, serializeJsonFields(model, values)),
226
+ toRow(model, serializeJsonFields(model, values, fieldTypeRegistry)),
209
227
  );
210
228
  const returned = rows.every(hasNoValues)
211
229
  ? await insertDefaultRows(db, model.tableName, rows.length)
212
- : await db(model.tableName).insert(rows).returning("*");
230
+ : await insertRows(db, model, rows);
213
231
  const records = returned.map((row) =>
214
- fromRow(model, row, fieldTypeRegistry, { jsonParsed: isPostgres(db) }),
232
+ fromRow(model, row, fieldTypeRegistry, { jsonParsed: isPostgres(db), dialect: dialectOfClient(db.client) }),
215
233
  );
216
234
  results.push(...alignToInput(model, chunk, records));
217
235
  }
@@ -1,6 +1,7 @@
1
1
  import { castValue } from "../fields/cast-value.js";
2
2
  import { defaultFieldTypeRegistry } from "../fields/default-registry.js";
3
3
  import { ValidationError } from "./errors.js";
4
+ import { filterValue } from "../fields/filter-value.js";
4
5
 
5
6
  /**
6
7
  * Converts a `{ fieldName: value }` equality filter into a
@@ -31,7 +32,7 @@ export function mapFilterToColumns(model, filter, fieldTypeRegistry = defaultFie
31
32
  }
32
33
  const columnName = model.columns[fieldName];
33
34
  columnFilter[columnName] =
34
- value === null || value === undefined ? value : castValue(field, value, fieldTypeRegistry);
35
+ value === null || value === undefined ? value : filterValue(field, "=", value, fieldTypeRegistry);
35
36
  }
36
37
 
37
38
  return columnFilter;
package/src/crud/order.js CHANGED
@@ -54,6 +54,7 @@ export function parseOrderBy(orderBy, fail) {
54
54
  for (const item of items) {
55
55
  let field;
56
56
  let direction = "asc";
57
+ let nulls;
57
58
 
58
59
  if (typeof item === "string") {
59
60
  field = item;
@@ -62,10 +63,11 @@ export function parseOrderBy(orderBy, fail) {
62
63
  direction = "desc";
63
64
  }
64
65
  } else if (Array.isArray(item)) {
65
- [field, direction = "asc"] = item;
66
+ [field, direction = "asc", nulls] = item;
66
67
  } else if (item && typeof item === "object") {
67
68
  field = item.field;
68
69
  direction = item.direction ?? "asc";
70
+ nulls = item.nulls;
69
71
  } else {
70
72
  fail(`orderBy entries must be a field name, [field, direction] or { field, direction } (got ${JSON.stringify(item)})`);
71
73
  }
@@ -80,7 +82,15 @@ export function parseOrderBy(orderBy, fail) {
80
82
  if (result.some((entry) => entry.field === field)) {
81
83
  fail(`orderBy lists "${field}" more than once`);
82
84
  }
83
- result.push({ field, direction });
85
+ if (nulls !== undefined && nulls !== "first" && nulls !== "last") {
86
+ fail(`orderBy nulls must be "first" or "last" (got ${JSON.stringify(nulls)})`);
87
+ }
88
+ // NULLs sort where the database puts them unless `nulls` says otherwise: Postgres last
89
+ // ascending / first descending, SQLite the reverse. A fixed rule would be the non-native one
90
+ // on one of the two, and that order can't be read from an index: on SQLite a sorted, LIMITed
91
+ // read of a nullable indexed column became a full sort (63x slower in a load test). So
92
+ // consistency is opt-in (since 0.2.0): ["dueAt", "asc", "last"].
93
+ result.push(nulls === undefined ? { field, direction } : { field, direction, nulls });
84
94
  }
85
95
  return result;
86
96
  }
@@ -106,6 +116,22 @@ export function validatePaging(model, { limit, offset }) {
106
116
  }
107
117
  }
108
118
 
119
+ /**
120
+ * The validated sort keys of a find(), with the primary key appended as the final tie-breaker
121
+ * whenever the caller orders or skips rows (see applyOrderAndPaging()). Validates limit/offset too.
122
+ *
123
+ * @returns {Array<{ field: string, direction: "asc"|"desc", nulls?: "first"|"last" }>}
124
+ */
125
+ export function resolveOrder(model, { orderBy, limit, offset }) {
126
+ validatePaging(model, { limit, offset });
127
+ const order = normalizeOrderBy(model, orderBy);
128
+ const key = primaryKeyOf(model);
129
+ if ((order.length > 0 || offset !== undefined) && key !== null && !order.some((entry) => entry.field === key)) {
130
+ order.push({ field: key, direction: "asc" });
131
+ }
132
+ return order;
133
+ }
134
+
109
135
  /**
110
136
  * Applies ordering and paging to a Knex query builder.
111
137
  *
@@ -117,16 +143,40 @@ export function validatePaging(model, { limit, offset }) {
117
143
  * @returns {import('knex').Knex.QueryBuilder}
118
144
  */
119
145
  export function applyOrderAndPaging(query, model, { orderBy, limit, offset }) {
120
- validatePaging(model, { limit, offset });
121
- const order = normalizeOrderBy(model, orderBy);
122
-
146
+ const order = resolveOrder(model, { orderBy, limit, offset });
123
147
  const key = primaryKeyOf(model);
124
- if ((order.length > 0 || offset !== undefined) && key !== null && !order.some((entry) => entry.field === key)) {
125
- order.push({ field: key, direction: "asc" });
126
- }
127
148
 
128
- for (const { field, direction } of order) query = query.orderBy(model.columns[field], direction);
149
+ // The primary key never holds NULL: no clause for it.
150
+ for (const { field, direction, nulls } of order) {
151
+ query = orderWithNulls(query, model.columns[field], direction, nullsClause(query, field === key ? null : model.fields[field], direction, nulls));
152
+ }
129
153
  if (limit !== undefined) query = query.limit(limit);
130
154
  if (offset !== undefined && offset > 0) query = query.offset(offset); // OFFSET 0 is a no-op; leave it out
131
155
  return query;
132
156
  }
157
+
158
+ /**
159
+ * The `nulls` argument for Knex's orderBy(), or undefined when the database already sorts NULLs that
160
+ * way, or the column can't hold any (required fields, primary keys). On SQLite Knex emulates it with
161
+ * an `(col is null)` sort key, which keeps SQLite from using an index for the ORDER BY - so it is
162
+ * only added where NULLs can actually appear.
163
+ */
164
+ export function nullsClause(query, field, direction, nulls) {
165
+ if (!nulls || !field || field.required || field.primaryKey) return undefined;
166
+ const client = String(query.client?.config?.client ?? "");
167
+ const databaseDefault = client.includes("sqlite") ? (direction === "asc" ? "first" : "last") : direction === "asc" ? "last" : "first";
168
+ return nulls === databaseDefault ? undefined : nulls;
169
+ }
170
+
171
+ /**
172
+ * query.orderBy(column, direction) with a NULLS FIRST/LAST rule. Not Knex's own `nulls` argument on
173
+ * SQLite: there Knex replaces the column's ordering with the `(col is null)` key alone, so rows come
174
+ * back sorted by nullness only. SQLite gets both keys explicitly; Postgres its native clause.
175
+ */
176
+ export function orderWithNulls(query, column, direction, nulls) {
177
+ if (!nulls) return query.orderBy(column, direction);
178
+ if (String(query.client?.config?.client ?? "").includes("sqlite")) {
179
+ return query.orderByRaw(`(?? IS NULL) ${nulls === "last" ? "ASC" : "DESC"}`, [column]).orderBy(column, direction);
180
+ }
181
+ return query.orderBy(column, direction, nulls);
182
+ }