@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
@@ -1,6 +1,7 @@
1
1
  import { attachRelation, attachManyRelation, detachRelation } from "../relations/attach-detach.js";
2
2
  import { Repository } from "../crud/repository.js";
3
3
  import { paginateWith } from "../crud/paginate.js";
4
+ import { resolveDb } from "../transaction/context.js";
4
5
 
5
6
  /**
6
7
  * The object behind `client.models.<modelName>`. Wraps a shared
@@ -30,7 +31,7 @@ export class ModelHandle {
30
31
  }
31
32
 
32
33
  get #repo() {
33
- const db = this.unitOfWork.trx ?? this.unitOfWork.db;
34
+ const db = resolveDb(this.unitOfWork.db, this.unitOfWork.trx);
34
35
  return new Repository(db, this.#model, this.unitOfWork.fieldTypeRegistry, this.unitOfWork.modelRegistry);
35
36
  }
36
37
 
@@ -71,6 +72,15 @@ export class ModelHandle {
71
72
  return this.unitOfWork.createMany(this.modelName, dataList, options);
72
73
  }
73
74
 
75
+ /** Insert, or update the row with the same `conflict` key (since 0.2.0); see the global Model.upsert(). */
76
+ upsert(data, options) {
77
+ return this.unitOfWork.upsert(this.modelName, data, options);
78
+ }
79
+
80
+ upsertMany(dataList, options) {
81
+ return this.unitOfWork.upsertMany(this.modelName, dataList, options);
82
+ }
83
+
74
84
  /**
75
85
  * Bulk update, bypassing the identity map and per-row hooks - for
76
86
  * "update every row matching this filter" operations where there's
@@ -176,7 +186,7 @@ export class ModelHandle {
176
186
  * @returns {Promise<number>} count of new associations actually inserted
177
187
  */
178
188
  async attach(source, relationName, targetIds) {
179
- const db = this.unitOfWork.trx ?? this.unitOfWork.db;
189
+ const db = resolveDb(this.unitOfWork.db, this.unitOfWork.trx);
180
190
  return attachRelation(db, this.#model, this.modelName, source, relationName, targetIds);
181
191
  }
182
192
 
@@ -192,7 +202,7 @@ export class ModelHandle {
192
202
  * @returns {Promise<number>} count of new associations actually inserted
193
203
  */
194
204
  async attachMany(relationName, links) {
195
- const db = this.unitOfWork.trx ?? this.unitOfWork.db;
205
+ const db = resolveDb(this.unitOfWork.db, this.unitOfWork.trx);
196
206
  return attachManyRelation(db, this.#model, this.modelName, relationName, links);
197
207
  }
198
208
 
@@ -206,7 +216,7 @@ export class ModelHandle {
206
216
  * @returns {Promise<number>} count of associations removed
207
217
  */
208
218
  async detach(source, relationName, targetIds) {
209
- const db = this.unitOfWork.trx ?? this.unitOfWork.db;
219
+ const db = resolveDb(this.unitOfWork.db, this.unitOfWork.trx);
210
220
  return detachRelation(db, this.#model, this.modelName, source, relationName, targetIds);
211
221
  }
212
222
  }
@@ -5,6 +5,7 @@ import { UnitOfWork } from "../uow/unit-of-work.js";
5
5
  import { ModelHandle } from "./model-handle.js";
6
6
  import { ReportHandle } from "../reports/report-handle.js";
7
7
  import { NPlusOneError, scanForNPlusOne, watchForNPlusOne } from "../diagnostics/n-plus-one.js";
8
+ import { resolveDb } from "../transaction/context.js";
8
9
 
9
10
  const RESERVED_CLIENT_PROPERTIES = new Set([
10
11
  "db",
@@ -72,7 +73,10 @@ export class OrmClient {
72
73
  this.db = db;
73
74
  this.modelRegistry = modelRegistry;
74
75
  this.hooks = hooks;
75
- this.unitOfWork = new UnitOfWork(db, modelRegistry, { hooks, trx });
76
+ // One object per row only inside client.transaction(), like the global API's withIdentityMap().
77
+ // Before 0.2.0 a client kept every object it ever read: a long-lived client returned stale
78
+ // values after other writes, and its memory only grew.
79
+ this.unitOfWork = new UnitOfWork(db, modelRegistry, { hooks, trx, identityMap: trx !== undefined });
76
80
  this.models = this.#buildModelsProxy();
77
81
  this.reportDescriptors = reports;
78
82
  this.reports = this.#buildReportsProxy(reports);
@@ -157,7 +161,7 @@ export class OrmClient {
157
161
  * @param {object} [options] - `threshold`, `windowMs`, `statements`
158
162
  */
159
163
  async detectNPlusOne(fn, options = {}) {
160
- return scanForNPlusOne(this.unitOfWork.trx ?? this.db, fn, options);
164
+ return scanForNPlusOne(resolveDb(this.db, this.unitOfWork.trx), fn, options);
161
165
  }
162
166
 
163
167
  /** Like detectNPlusOne(), but throws an NPlusOneError (with `.findings`) if anything repeated. */
@@ -169,7 +173,7 @@ export class OrmClient {
169
173
 
170
174
  /** A live console watcher for development; returns the monitor (`.detach()` to stop). */
171
175
  watchNPlusOne(options = {}) {
172
- return watchForNPlusOne(this.unitOfWork.trx ?? this.db, options);
176
+ return watchForNPlusOne(resolveDb(this.db, this.unitOfWork.trx), options);
173
177
  }
174
178
 
175
179
  async sync() {
@@ -184,7 +188,7 @@ export class OrmClient {
184
188
  * @returns {Promise<Array<{ model: string, table: string, synced: boolean }>>}
185
189
  */
186
190
  async syncSequences() {
187
- return syncRegistrySequences(this.unitOfWork.trx ?? this.db, this.modelRegistry);
191
+ return syncRegistrySequences(resolveDb(this.db, this.unitOfWork.trx), this.modelRegistry);
188
192
  }
189
193
 
190
194
  /**
@@ -202,7 +206,8 @@ export class OrmClient {
202
206
  * @returns {Promise<T>}
203
207
  */
204
208
  async transaction(fn) {
205
- return this.db.transaction(async (trx) => {
209
+ // Inside another transaction (this client's or the global API's), a savepoint in it.
210
+ return resolveDb(this.db).transaction(async (trx) => {
206
211
  const txClient = new OrmClient(this.db, this.modelRegistry, this.hooks, trx, this.moduleServices, this.reportDescriptors);
207
212
  return fn(txClient);
208
213
  });
package/src/connection.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import knexFactory from "knex";
2
- import { guardTransactions } from "./dialect/transaction-guard.js";
2
+ import { instrumentConnection } from "./dialect/transaction-guard.js";
3
3
 
4
4
  /**
5
5
  * Supported dialects for Phase 0. More can be added later without
@@ -19,6 +19,21 @@ const DIALECTS = /** @type {const} */ (["sqlite", "postgres"]);
19
19
  * of your own runs after the ORM's (SQLite turns foreign keys on there). Since 0.1.7.
20
20
  * @property {number} [acquireConnectionTimeout] - ms to wait for a free pooled connection before
21
21
  * failing (Knex default 60000). Since 0.1.7.
22
+ * @property {boolean} [wal] - sqlite only, since 0.2.0: a database file is opened in WAL mode with
23
+ * `synchronous = NORMAL` (default `true`) - each write commits without waiting for the disk
24
+ * twice, ~10-20x faster for single writes, and readers in other processes don't block the
25
+ * writer. A committed write can be lost on a power cut or OS crash (never on an app crash), and
26
+ * the database is never corrupted. The `-wal` / `-shm` files next to the database are part of
27
+ * it while it's open. `false` uses SQLite's classic rollback journal (journal_mode = DELETE,
28
+ * synchronous = FULL), switching back a file that was in WAL mode. Ignored for ":memory:".
29
+ * @property {boolean} [preparedStatements] - postgres only, since 0.2.0: find() and findOne() reuse
30
+ * named prepared statements, parsed and planned once per pooled connection (default `true`). Set
31
+ * `false` behind a pooler that doesn't keep one server session per client connection
32
+ * (pgbouncer in transaction mode before 1.21), where a named statement may not exist on the next
33
+ * query's session.
34
+ * @property {boolean} [fastPath] - since 0.2.0: `false` builds every find() with Knex, as before
35
+ * 0.2.0, instead of writing plain finds as SQL directly. Results are the same either way; this is
36
+ * an escape hatch, not a tuning knob.
22
37
  */
23
38
 
24
39
  /**
@@ -40,18 +55,31 @@ export function createConnection(config) {
40
55
 
41
56
  if (config.dialect === "sqlite") {
42
57
  const { afterCreate: userAfterCreate, ...pool } = config.pool ?? {};
43
- return guardTransactions(knexFactory({
58
+ return instrumentConnection(knexFactory({
44
59
  client: "better-sqlite3",
45
60
  connection: {
46
61
  filename: config.filename ?? ":memory:",
47
62
  },
48
63
  useNullAsDefault: true,
64
+ kiriLower: true, // read by the domain compiler's ilike: kiri_lower() exists on these connections
65
+ ...(config.fastPath === false ? { kiriFastPath: false } : {}),
49
66
  ...shared,
50
67
  pool: {
51
68
  ...pool,
52
69
  // SQLite only enforces foreign keys on connections that ask for it (off by default).
53
70
  afterCreate(connection, done) {
54
71
  connection.pragma("foreign_keys = ON");
72
+ if (!connection.memory) {
73
+ if (config.wal === false) {
74
+ connection.pragma("journal_mode = DELETE");
75
+ connection.pragma("synchronous = FULL");
76
+ } else {
77
+ connection.pragma("journal_mode = WAL");
78
+ connection.pragma("synchronous = NORMAL");
79
+ }
80
+ }
81
+ // Unicode-aware lower-case for case-insensitive matching (SQLite's lower() only folds A-Z).
82
+ connection.function("kiri_lower", { deterministic: true }, (value) => (typeof value === "string" ? value.toLowerCase() : value));
55
83
  if (userAfterCreate) userAfterCreate(connection, done);
56
84
  else done(null, connection);
57
85
  },
@@ -63,12 +91,14 @@ export function createConnection(config) {
63
91
  if (!config.connectionString) {
64
92
  throw new Error("postgres dialect requires a connectionString");
65
93
  }
66
- return knexFactory({
94
+ return instrumentConnection(knexFactory({
67
95
  client: "pg",
68
96
  connection: config.ssl === undefined ? config.connectionString : { connectionString: config.connectionString, ssl: config.ssl },
97
+ ...(config.fastPath === false ? { kiriFastPath: false } : {}),
98
+ ...(config.preparedStatements === false ? { kiriPreparedStatements: false } : {}),
69
99
  ...shared,
70
100
  ...(config.pool ? { pool: config.pool } : {}),
71
- });
101
+ }));
72
102
  }
73
103
 
74
104
  // Unreachable given the guard above, but keeps the function honest.
@@ -1,6 +1,7 @@
1
1
  import { parseDomain } from "../domain/parse.js";
2
2
  import { castValue } from "../fields/cast-value.js";
3
3
  import { ValidationError } from "./errors.js";
4
+ import { toStorage } from "../fields/storage.js";
4
5
 
5
6
  /**
6
7
  * WHERE vs HAVING.
@@ -129,10 +130,15 @@ export function compileHaving(model, plan, ast, expressionFor, fieldTypeRegistry
129
130
 
130
131
  // count/sum/avg come out as numbers whatever the column was; min/max keep the column's own type.
131
132
  const castFor = (aggregate) => {
132
- const field = aggregate.fn === "min" || aggregate.fn === "max" ? aggregate.def : { type: "float" };
133
+ // A decimal aggregate (min/max/sum, and avg on SQLite where it's over scaled integers) compares
134
+ // in the column's stored form, so the value goes through the decimal type too.
135
+ const decimal = aggregate.def?.type === "decimal" && aggregate.fn !== "count" && aggregate.fn !== "countDistinct";
136
+ const field = aggregate.fn === "min" || aggregate.fn === "max" || decimal ? aggregate.def : { type: "float" };
133
137
  return (value, op) => {
134
138
  try {
135
- return castValue(field, value, fieldTypeRegistry);
139
+ const cast = castValue(field, value, fieldTypeRegistry);
140
+ if (decimal && aggregate.fn === "avg") return toStorage({ ...field, scale: field.scale ?? 2 }, cast, fieldTypeRegistry);
141
+ return decimal || field === aggregate.def ? toStorage(field, cast, fieldTypeRegistry) : cast;
136
142
  } catch (error) {
137
143
  return fail(`filter on aggregate "${aggregate.alias}" (${op}): ${error.message}`);
138
144
  }
@@ -35,8 +35,8 @@ import { resolvePath } from "./aggregate-paths.js";
35
35
 
36
36
  const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
37
37
  const FUNCTIONS = ["count", "countDistinct", "sum", "avg", "min", "max"];
38
- const NUMERIC_TYPES = new Set(["integer", "float"]);
39
- const COMPARABLE_TYPES = new Set(["integer", "float", "date", "datetime", "char", "text", "enum"]); // min / max
38
+ const NUMERIC_TYPES = new Set(["integer", "float", "decimal"]);
39
+ const COMPARABLE_TYPES = new Set(["integer", "float", "decimal", "date", "datetime", "char", "text", "enum"]); // min / max
40
40
  const DATE_TYPES = new Set(["date", "datetime"]);
41
41
  const GROUP_OPTION_KEYS = new Set(["field", "bucket", "as"]);
42
42
 
@@ -4,6 +4,7 @@ import { dateBucketSql, parseBucket } from "../dialect/date-bucket.js";
4
4
  import { planAggregate } from "./aggregate-spec.js";
5
5
  import { compileHaving, filterToAst, mentionsResultColumn, splitFilter } from "./aggregate-filter.js";
6
6
  import { resolveWhere } from "./resolve-where.js";
7
+ import { fromStorage, dialectOfClient } from "../fields/storage.js";
7
8
 
8
9
  /**
9
10
  * Builds and runs one aggregate query: groups rows, computes count/sum/avg/min/max, filters
@@ -224,7 +225,7 @@ function buildSubtotalQuery(db, { many, components }) {
224
225
  export async function runAggregate(ctx) {
225
226
  const { query, plan } = buildAggregateQuery(ctx);
226
227
  const rows = await query;
227
- return rows.map((row) => mapRow(plan, row, ctx.fieldTypeRegistry));
228
+ return rows.map((row) => mapRow(plan, row, ctx.fieldTypeRegistry, dialectOfClient(ctx.db.client)));
228
229
  }
229
230
 
230
231
  /**
@@ -247,12 +248,15 @@ const toNumber = (value) => (value === null || value === undefined ? null : Numb
247
248
  * as the column's own type (a Date for a date field). Group keys are cast like any stored value.
248
249
  * Numbers are JS doubles: a count or integer sum beyond 2^53 would lose precision.
249
250
  */
250
- function mapRow(plan, row, fieldTypeRegistry) {
251
+ function mapRow(plan, row, fieldTypeRegistry, dialect) {
251
252
  const result = {};
253
+ // A stored value back to the field's own type (decimal: SQLite's scaled integer to "12.50").
254
+ const asField = (def, value) =>
255
+ value === null || value === undefined ? null : castValue(def, fromStorage(def, value, dialect, fieldTypeRegistry), fieldTypeRegistry);
252
256
  for (const key of plan.keys) {
253
257
  const value = row[key.alias];
254
258
  if (key.kind === "bucket") result[key.alias] = parseBucket(value);
255
- else result[key.alias] = value === null || value === undefined ? null : castValue(key.def, value, fieldTypeRegistry);
259
+ else result[key.alias] = asField(key.def, value);
256
260
  }
257
261
  for (const aggregate of plan.aggregates) {
258
262
  const value = row[aggregate.alias];
@@ -262,11 +266,18 @@ function mapRow(plan, row, fieldTypeRegistry) {
262
266
  result[aggregate.alias] = toNumber(value) ?? 0;
263
267
  break;
264
268
  case "sum":
269
+ // A sum of decimals stays an exact decimal string (SQLite sums the scaled integers exactly).
270
+ result[aggregate.alias] = aggregate.def?.type === "decimal" ? asField(aggregate.def, value) : toNumber(value);
271
+ break;
265
272
  case "avg":
266
- result[aggregate.alias] = toNumber(value);
273
+ // An average is rarely a whole number of cents: always a number (on SQLite, unscaled).
274
+ result[aggregate.alias] =
275
+ aggregate.def?.type === "decimal" && dialect === "sqlite" && value !== null && value !== undefined
276
+ ? Number(value) / 10 ** (aggregate.def.scale ?? 2)
277
+ : toNumber(value);
267
278
  break;
268
279
  default: // min, max
269
- result[aggregate.alias] = value === null || value === undefined ? null : castValue(aggregate.def, value, fieldTypeRegistry);
280
+ result[aggregate.alias] = asField(aggregate.def, value);
270
281
  }
271
282
  }
272
283
  return result;
@@ -7,6 +7,11 @@ import { attachPairs } from "../relations/attach-detach.js";
7
7
  import { RelationError } from "../relations/errors.js";
8
8
  import { resolveLocalKey } from "../relations/keys.js";
9
9
  import { primaryKeyOf } from "../models/primary-key.js";
10
+ import { resolveDb, inTransactionIf } from "../transaction/context.js";
11
+ import { hookContext, runAfterHooks } from "../uow/lifecycle.js";
12
+ import { ENTITY_META, originalValues, markCreateRolledBack } from "../uow/entity.js";
13
+ import { onRollback } from "../transaction/after-commit.js";
14
+ import { translatingErrors } from "./database-errors.js";
10
15
 
11
16
  /**
12
17
  * Batched record creation - the engine behind `createMany()` (and,
@@ -150,9 +155,10 @@ async function prepareLevel(ctx, model, dataList, labels) {
150
155
  );
151
156
  }
152
157
 
153
- if (runtime.hooks) {
154
- await runtime.hooks.run(model.name, "beforeCreate", data);
155
- await runtime.hooks.run(model.name, "beforeSave", data, undefined);
158
+ if (runtime.hooks?.has(model.name, ["beforeCreate", "beforeSave"])) {
159
+ const hookCtx = hookContext(ctx.db, "create", { isNew: true, changes: data, model: model.name });
160
+ await runtime.hooks.run(model.name, "beforeCreate", data, hookCtx);
161
+ await runtime.hooks.run(model.name, "beforeSave", data, hookCtx);
156
162
  }
157
163
 
158
164
  const { fieldData, relationKeys } = splitRelationKeys(model, data);
@@ -366,35 +372,52 @@ export async function createRecords(runtime, model, dataList, options = {}) {
366
372
  if (dataList.length === 0) return [];
367
373
 
368
374
  const labels = options.labels ?? dataList.map((_, i) => `[${i}]`);
369
- const baseDb = options.trx ?? runtime.db;
370
- const ctx = { runtime, db: baseDb, chunkSize: options.chunkSize, created: [], targets: new Map() };
375
+ const baseDb = resolveDb(runtime.db, options.trx);
376
+
377
+ // One atomic unit whenever more than a lone INSERT is involved: hooks (since 0.2.0 they run
378
+ // inside it, so a hook's own writes and a hook that throws commit or roll back with the rows),
379
+ // nested relation writes, or more rows than one INSERT holds. Inside an open transaction
380
+ // (explicit or ambient) all of it simply joins that one.
381
+ const relationNames = Object.keys(model.relations ?? {});
382
+ const isPayload = (value) => value !== undefined && !(Array.isArray(value) && value.length === 0);
383
+ const hasRelationPayload =
384
+ relationNames.length > 0 && dataList.some((data) => data && typeof data === "object" && relationNames.some((r) => isPayload(data[r])));
385
+ if (hasRelationPayload && !runtime.modelRegistry) {
386
+ // Say so before touching the database (resolveTarget() would, but only inside the transaction).
387
+ throw new RelationError(
388
+ `Writing relations of model "${model.name}" requires a modelRegistry (construct the Repository with one, or use RepositoryFactory / createClient).`
389
+ );
390
+ }
391
+ const statements = Math.ceil(dataList.length / rowsPerStatement(baseDb, Object.keys(model.fields).length, options.chunkSize));
392
+ const needsTransaction = (runtime.hooks?.has(model.name) ?? false) || hasRelationPayload || statements > 1;
371
393
 
372
- // Phase 1 - nothing is written.
373
- const rows = await prepareLevel(ctx, model, dataList, labels);
394
+ return translatingErrors(model, () => inTransactionIf(needsTransaction, baseDb, async (db) => {
395
+ const ctx = { runtime, db, chunkSize: options.chunkSize, created: [], targets: new Map() };
374
396
 
375
- // Phase 2 - a lone INSERT is atomic by itself; anything more needs a transaction.
376
- const hasRelationWork = rows.some((row) => row.commands && Object.values(row.commands).some((ops) => ops.length > 0));
377
- const insertStatements = Math.ceil(rows.length / rowsPerStatement(baseDb, Object.keys(model.fields).length, options.chunkSize));
378
-
379
- let rootEntries;
380
- if (!baseDb.isTransaction && (hasRelationWork || insertStatements > 1)) {
381
- await baseDb.transaction(async (trx) => {
382
- rootEntries = await executeLevel({ ...ctx, db: trx }, model, rows);
383
- });
384
- } else {
385
- rootEntries = await executeLevel(ctx, model, rows);
386
- }
397
+ // Phase 1 - before-hooks, validation, relation payloads; nothing is written.
398
+ const rows = await prepareLevel(ctx, model, dataList, labels);
399
+ // Phase 2 - the INSERTs (and nested relation writes).
400
+ const rootEntries = await executeLevel(ctx, model, rows);
387
401
 
388
- // Phase 3 - committed; now build entities and fire after-hooks.
389
- for (const entry of ctx.created) {
390
- entry.result = runtime.wrap ? runtime.wrap(entry.model.name, entry.record) : entry.record;
391
- }
392
- if (runtime.hooks) {
402
+ // Phase 3 - documents, then after-hooks, still inside the unit; afterCommit waits for the commit.
393
403
  for (const entry of ctx.created) {
394
- await runtime.hooks.run(entry.model.name, "afterCreate", entry.result);
395
- await runtime.hooks.run(entry.model.name, "afterSave", entry.result, undefined);
404
+ entry.result = runtime.wrap ? runtime.wrap(entry.model.name, entry.record) : entry.record;
396
405
  }
397
- }
398
-
399
- return rootEntries.map((entry) => entry.result);
406
+ // If the transaction these INSERTs ran in rolls back, the documents have no rows (since 0.2.0).
407
+ if (db.isTransaction) {
408
+ const documents = ctx.created.map((entry) => entry.result);
409
+ onRollback(db, () => documents.forEach(markCreateRolledBack));
410
+ }
411
+ if (runtime.hooks) {
412
+ for (const entry of ctx.created) {
413
+ if (!runtime.hooks.has(entry.model.name)) continue; // no hooks: nothing to run, no context to build
414
+ // What was written, as its own object: the document (the same object as entry.record once
415
+ // wrapped) may change before afterCommit runs.
416
+ const changes = entry.result[ENTITY_META] ? originalValues(entry.result) : entry.record;
417
+ const hookCtx = hookContext(db, "create", { isNew: true, changes, model: entry.model.name });
418
+ await runAfterHooks(runtime.hooks, entry.model.name, db, "create", entry.result, hookCtx);
419
+ }
420
+ }
421
+ return rootEntries.map((entry) => entry.result);
422
+ }));
400
423
  }
@@ -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
+ }