@kiri-orm/core 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) 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 +66 -0
  4. package/dist/types/crud/chunk.d.ts +10 -0
  5. package/dist/types/crud/database-errors.d.ts +61 -0
  6. package/dist/types/crud/errors.d.ts +10 -0
  7. package/dist/types/crud/fast-path.d.ts +73 -0
  8. package/dist/types/crud/index.d.ts +4 -1
  9. package/dist/types/crud/insert-many.d.ts +12 -13
  10. package/dist/types/crud/order.d.ts +28 -0
  11. package/dist/types/crud/repository.d.ts +5 -3
  12. package/dist/types/crud/row-mapping.d.ts +9 -1
  13. package/dist/types/crud/upsert.d.ts +39 -0
  14. package/dist/types/crud/value.d.ts +39 -0
  15. package/dist/types/dialect/date-bucket.d.ts +2 -2
  16. package/dist/types/dialect/index.d.ts +1 -0
  17. package/dist/types/dialect/transaction-guard.d.ts +31 -0
  18. package/dist/types/domain/compile.d.ts +17 -0
  19. package/dist/types/fields/filter-value.d.ts +21 -0
  20. package/dist/types/fields/registry.d.ts +1 -0
  21. package/dist/types/fields/storage.d.ts +28 -0
  22. package/dist/types/fields/types/date.d.ts +6 -6
  23. package/dist/types/fields/types/decimal.d.ts +40 -0
  24. package/dist/types/global/errors.d.ts +3 -0
  25. package/dist/types/global/index.d.ts +2 -0
  26. package/dist/types/global/normalize-dates.d.ts +11 -0
  27. package/dist/types/global/state.d.ts +2 -0
  28. package/dist/types/global/transaction.d.ts +10 -13
  29. package/dist/types/index.d.ts +2 -0
  30. package/dist/types/meta/create-table-once.d.ts +15 -0
  31. package/dist/types/meta/snapshot.d.ts +10 -0
  32. package/dist/types/meta/upsert.d.ts +16 -0
  33. package/dist/types/migrations/diff.d.ts +25 -2
  34. package/dist/types/models/constraints.d.ts +27 -0
  35. package/dist/types/relations/pivot-schema.d.ts +1 -1
  36. package/dist/types/schema/alter-column.d.ts +46 -0
  37. package/dist/types/schema/build-column.d.ts +11 -0
  38. package/dist/types/schema/index.d.ts +1 -0
  39. package/dist/types/schema/introspect-indexes.d.ts +9 -0
  40. package/dist/types/schema/normalize-dates.d.ts +41 -0
  41. package/dist/types/transaction/after-commit.d.ts +42 -0
  42. package/dist/types/transaction/context.d.ts +39 -0
  43. package/dist/types/uow/entity.d.ts +39 -29
  44. package/dist/types/uow/hooks.d.ts +6 -1
  45. package/dist/types/uow/lifecycle.d.ts +82 -0
  46. package/dist/types/uow/unit-of-work.d.ts +11 -7
  47. package/package.json +8 -5
  48. package/src/client/model-handle.js +14 -4
  49. package/src/client/orm-client.js +10 -5
  50. package/src/connection.js +53 -7
  51. package/src/crud/aggregate-filter.js +8 -2
  52. package/src/crud/aggregate-spec.js +2 -2
  53. package/src/crud/aggregate.js +16 -5
  54. package/src/crud/chunk.js +10 -0
  55. package/src/crud/create-many.js +52 -29
  56. package/src/crud/database-errors.js +107 -0
  57. package/src/crud/errors.js +14 -0
  58. package/src/crud/fast-path.js +449 -0
  59. package/src/crud/index.js +4 -1
  60. package/src/crud/insert-many.js +42 -7
  61. package/src/crud/map-filter.js +2 -1
  62. package/src/crud/order.js +59 -9
  63. package/src/crud/repository.js +106 -38
  64. package/src/crud/row-mapping.js +32 -7
  65. package/src/crud/upsert.js +203 -0
  66. package/src/crud/value.js +71 -0
  67. package/src/dialect/index.js +1 -0
  68. package/src/dialect/transaction-guard.js +254 -0
  69. package/src/domain/compile.js +85 -12
  70. package/src/dto/field-schema.js +5 -0
  71. package/src/fields/default-registry.js +3 -1
  72. package/src/fields/filter-value.js +87 -0
  73. package/src/fields/registry.js +1 -0
  74. package/src/fields/storage.js +50 -0
  75. package/src/fields/types/date.js +16 -3
  76. package/src/fields/types/decimal.js +147 -0
  77. package/src/fields/types/integer.js +7 -0
  78. package/src/global/connect.js +25 -1
  79. package/src/global/create-model.js +59 -57
  80. package/src/global/errors.js +1 -1
  81. package/src/global/index.js +2 -0
  82. package/src/global/normalize-dates.js +15 -0
  83. package/src/global/state.js +3 -0
  84. package/src/global/transaction.js +12 -14
  85. package/src/index.js +2 -0
  86. package/src/meta/create-table-once.js +23 -0
  87. package/src/meta/schema.js +15 -6
  88. package/src/meta/snapshot.js +5 -0
  89. package/src/meta/upsert.js +28 -0
  90. package/src/migrations/describe.js +49 -0
  91. package/src/migrations/diff.js +50 -7
  92. package/src/migrations/generate.js +38 -2
  93. package/src/migrations/render.js +30 -12
  94. package/src/migrations/runner.js +40 -6
  95. package/src/models/constraints.js +96 -0
  96. package/src/models/define-model.js +4 -0
  97. package/src/models/inheritance.js +4 -1
  98. package/src/models/registry.js +2 -1
  99. package/src/relations/attach-detach.js +49 -18
  100. package/src/relations/cascade-delete.js +32 -7
  101. package/src/relations/eager-load.js +75 -51
  102. package/src/relations/pivot-schema.js +24 -3
  103. package/src/reports/report-handle.js +2 -1
  104. package/src/schema/alter-column.js +219 -0
  105. package/src/schema/build-column.js +28 -2
  106. package/src/schema/default-column-builders.js +16 -2
  107. package/src/schema/index.js +1 -0
  108. package/src/schema/introspect-indexes.js +22 -0
  109. package/src/schema/normalize-dates.js +58 -0
  110. package/src/schema/sync.js +16 -2
  111. package/src/transaction/after-commit.js +142 -0
  112. package/src/transaction/context.js +84 -0
  113. package/src/uow/entity.js +133 -133
  114. package/src/uow/hooks.js +9 -0
  115. package/src/uow/lifecycle.js +162 -0
  116. package/src/uow/unit-of-work.js +55 -60
  117. package/src/uow/with-unit-of-work.js +2 -1
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Constraint violations reported by the database, as the same errors on both databases (since 0.2.0).
3
+ *
4
+ * try { await User.create({ email }) }
5
+ * catch (error) {
6
+ * if (error instanceof UniqueViolationError) return reply(409, `${error.fields.join(", ")} already taken`);
7
+ * throw error;
8
+ * }
9
+ *
10
+ * Before 0.2.0 the driver's own error came through: `code` "23505" with a `detail` on Postgres,
11
+ * "SQLITE_CONSTRAINT_UNIQUE" with a message on SQLite. These errors keep the driver's `code`
12
+ * (so existing `error.code === "23505"` checks still work) and its error as `cause`.
13
+ */
14
+ export class DatabaseConstraintError extends Error {
15
+ /**
16
+ * @param {string} message
17
+ * @param {{ model: string, fields?: string[], columns?: string[], constraint?: string|null, cause: any }} info
18
+ */
19
+ constructor(message, { model, fields = [], columns = [], constraint = null, cause }) {
20
+ super(message, { cause });
21
+ this.name = this.constructor.name;
22
+ this.model = model;
23
+ this.fields = fields;
24
+ this.columns = columns;
25
+ this.constraint = constraint;
26
+ this.code = cause?.code;
27
+ }
28
+ }
29
+
30
+ /** A row with the same value(s) for a unique key exists already. `fields` names them when known. */
31
+ export class UniqueViolationError extends DatabaseConstraintError {}
32
+ /** A foreign key points at a row that doesn't exist (on insert/update) - or one is still referenced. */
33
+ export class ForeignKeyViolationError extends DatabaseConstraintError {}
34
+ /** A required (NOT NULL) column got no value - usually a raw write or a column added outside the ORM. */
35
+ export class NotNullViolationError extends DatabaseConstraintError {}
36
+ /** A CHECK constraint failed - e.g. an enum column's allowed values. */
37
+ export class CheckViolationError extends DatabaseConstraintError {}
38
+ /**
39
+ * A value doesn't fit its column's type (since 0.2.0) - e.g. 3000000000 in an `integer` column on
40
+ * Postgres, which holds 32 bits there. Postgres reports no column for it, so `fields` is empty.
41
+ */
42
+ export class OutOfRangeError extends DatabaseConstraintError {}
43
+
44
+ const PG = {
45
+ "23505": UniqueViolationError,
46
+ "23503": ForeignKeyViolationError,
47
+ "23502": NotNullViolationError,
48
+ "23514": CheckViolationError,
49
+ "22003": OutOfRangeError,
50
+ };
51
+ const SQLITE = {
52
+ SQLITE_CONSTRAINT_UNIQUE: UniqueViolationError,
53
+ SQLITE_CONSTRAINT_PRIMARYKEY: UniqueViolationError,
54
+ SQLITE_CONSTRAINT_FOREIGNKEY: ForeignKeyViolationError,
55
+ SQLITE_CONSTRAINT_NOTNULL: NotNullViolationError,
56
+ SQLITE_CONSTRAINT_CHECK: CheckViolationError,
57
+ };
58
+
59
+ /**
60
+ * The ORM error for a driver's constraint error, or the error unchanged. Columns are read from
61
+ * Postgres' `detail` ("Key (org_id, email)=(1, a@x) already exists.", or `column` for NOT NULL)
62
+ * and from SQLite's message ("UNIQUE constraint failed: member.org_id, member.email"), then mapped
63
+ * back to field names.
64
+ *
65
+ * @param {any} error
66
+ * @param {import('../models/define-model.js').ModelDescriptor} model
67
+ */
68
+ export function translateDatabaseError(error, model) {
69
+ if (!error || error instanceof DatabaseConstraintError) return error;
70
+ const ErrorClass = PG[error.code] ?? SQLITE[error.code];
71
+ if (!ErrorClass) return error;
72
+
73
+ let columns = [];
74
+ if (typeof error.detail === "string") {
75
+ const keyMatch = /Key \(([^)]+)\)=/.exec(error.detail);
76
+ if (keyMatch) columns = keyMatch[1].split(",").map((c) => c.trim().replace(/^"|"$/g, ""));
77
+ }
78
+ if (columns.length === 0 && typeof error.column === "string") columns = [error.column];
79
+ if (columns.length === 0 && typeof error.message === "string") {
80
+ const sqliteMatch = /constraint failed: (.+)$/i.exec(error.message);
81
+ if (sqliteMatch && ErrorClass !== CheckViolationError) {
82
+ columns = sqliteMatch[1].split(",").map((c) => c.trim().split(".").pop());
83
+ }
84
+ }
85
+ const byColumn = Object.fromEntries(Object.entries(model.columns).map(([field, column]) => [column, field]));
86
+ const fields = columns.map((c) => byColumn[c]).filter(Boolean);
87
+ const constraint = error.constraint ?? null;
88
+
89
+ const what = fields.length ? ` (${fields.join(", ")})` : "";
90
+ const messages = {
91
+ UniqueViolationError: `"${model.name}" already has a row with the same ${fields.length ? fields.join(" + ") : "unique key"}`,
92
+ ForeignKeyViolationError: `"${model.name}": a foreign key${what} points at a row that doesn't exist`,
93
+ NotNullViolationError: `"${model.name}": a required column${what} got no value`,
94
+ CheckViolationError: `"${model.name}": a value breaks a check constraint${constraint ? ` (${constraint})` : ""}`,
95
+ OutOfRangeError: `"${model.name}": a value is out of range for its column (${error.message})`,
96
+ };
97
+ return new ErrorClass(messages[ErrorClass.name], { model: model.name, fields, columns, constraint, cause: error });
98
+ }
99
+
100
+ /** Runs `fn`, translating a constraint error it throws. */
101
+ export async function translatingErrors(model, fn) {
102
+ try {
103
+ return await fn();
104
+ } catch (error) {
105
+ throw translateDatabaseError(error, model);
106
+ }
107
+ }
@@ -20,3 +20,17 @@ export class ValidationError extends Error {
20
20
  this.fieldErrors = fieldErrors;
21
21
  }
22
22
  }
23
+
24
+ /**
25
+ * A prepared statement stopped fitting its table while a transaction was using it (since 0.2.0):
26
+ * another process changed the table (a migration, say) after this connection prepared a query on it.
27
+ * Postgres aborts the transaction, so nothing in it can be saved; run the whole transaction again.
28
+ * Outside a transaction the ORM retries the query on its own. The driver's error is `cause`.
29
+ */
30
+ export class SchemaChangedError extends Error {
31
+ constructor(message, { cause } = {}) {
32
+ super(message, { cause });
33
+ this.name = "SchemaChangedError";
34
+ this.code = cause?.code;
35
+ }
36
+ }
@@ -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
  }
@@ -173,6 +184,28 @@ export function serializeJsonFields(model, values) {
173
184
  * @param {{ chunkSize?: number }} [options]
174
185
  * @returns {Promise<Record<string, unknown>[]>}
175
186
  */
187
+ const hasNoValues = (row) => Object.values(row).every((value) => value === undefined);
188
+
189
+ /**
190
+ * Rows with no column values at all (a model whose only field is its auto id, or rows where every
191
+ * field is optional and unset). Knex builds a multi-row insert from the columns the rows name, and
192
+ * there are none, so `createMany([{}, {}])` failed with "The query is empty" before 0.1.7. A
193
+ * single `insert({})` compiles to `INSERT ... DEFAULT VALUES` on both databases, so these go one
194
+ * statement per row.
195
+ */
196
+ async function insertDefaultRows(db, table, count) {
197
+ const returned = [];
198
+ for (let i = 0; i < count; i++) returned.push(...(await db(table).insert({}).returning("*")));
199
+ return returned;
200
+ }
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
+
176
209
  export async function insertRecords(
177
210
  db,
178
211
  model,
@@ -190,11 +223,13 @@ export async function insertRecords(
190
223
 
191
224
  for (const chunk of chunkArray(valuesList, size)) {
192
225
  const rows = chunk.map((values) =>
193
- toRow(model, serializeJsonFields(model, values)),
226
+ toRow(model, serializeJsonFields(model, values, fieldTypeRegistry)),
194
227
  );
195
- const returned = await db(model.tableName).insert(rows).returning("*");
228
+ const returned = rows.every(hasNoValues)
229
+ ? await insertDefaultRows(db, model.tableName, rows.length)
230
+ : await insertRows(db, model, rows);
196
231
  const records = returned.map((row) =>
197
- fromRow(model, row, fieldTypeRegistry, { jsonParsed: isPostgres(db) }),
232
+ fromRow(model, row, fieldTypeRegistry, { jsonParsed: isPostgres(db), dialect: dialectOfClient(db.client) }),
198
233
  );
199
234
  results.push(...alignToInput(model, chunk, records));
200
235
  }