@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,147 @@
1
+ import { CastError } from "../errors.js";
2
+ import { DialectValue } from "../storage.js";
3
+
4
+ /**
5
+ * `decimal` - an exact base-10 number, for money, prices, rates and quantities (since 0.2.0).
6
+ *
7
+ * price: { type: "decimal", precision: 12, scale: 2 } // up to 9,999,999,999.99
8
+ *
9
+ * Its value is always a string in canonical form - "1234.50", "-0.05", "0.00" - exactly `scale`
10
+ * decimal places, never a JavaScript number, so nothing is ever rounded behind your back. Do
11
+ * arithmetic with a decimal library (decimal.js, big.js) or in SQL (atomic updates, sums).
12
+ *
13
+ * Input:
14
+ * - a string is exact: "12.5" becomes "12.50"; more decimal places than `scale` is an error;
15
+ * - a JavaScript number is approximate already (0.1 + 0.2 is 0.30000000000000004), so it is
16
+ * rounded to `scale` places, half away from zero;
17
+ * - a bigint is a whole number.
18
+ *
19
+ * Storage:
20
+ * - Postgres: `numeric(precision, scale)` - exact, and the driver returns it as text.
21
+ * - SQLite has no exact decimal type (a DECIMAL column silently stores floating point), so the
22
+ * value is stored as an integer scaled by 10^scale: "1234.50" with scale 2 is stored as 123450.
23
+ * Exact, sorts and compares correctly, and SUM() stays exact. The ORM converts on the way in
24
+ * (every write and every filter value, through DialectValue) and on the way out.
25
+ *
26
+ * Limits: `precision` (total significant digits) 1-15 and `scale` 0-precision. Fifteen digits is
27
+ * what a SQLite integer read back by the driver keeps exactly (JavaScript numbers are exact up to
28
+ * 2^53); with scale 2 that is 9,999,999,999,999.99. Defaults: precision 15, scale 2.
29
+ */
30
+ export const MAX_DECIMAL_PRECISION = 15;
31
+
32
+ const shape = (field) => ({ precision: field.precision ?? MAX_DECIMAL_PRECISION, scale: field.scale ?? 2 });
33
+
34
+ const DECIMAL_TEXT = /^\s*([+-]?)(\d*)(?:\.(\d*))?\s*$/;
35
+
36
+ /** Canonical text with exactly `scale` places from sign, integer digits and fraction digits. */
37
+ function canonical(sign, int, frac, scale) {
38
+ const intDigits = int.replace(/^0+(?=\d)/, "") || "0";
39
+ const fracDigits = scale > 0 ? frac.padEnd(scale, "0").slice(0, scale) : "";
40
+ const isZero = /^0+$/.test(intDigits + fracDigits);
41
+ return `${sign === "-" && !isZero ? "-" : ""}${intDigits}${scale > 0 ? `.${fracDigits}` : ""}`;
42
+ }
43
+
44
+ function fromString(field, text) {
45
+ const { scale } = shape(field);
46
+ const match = DECIMAL_TEXT.exec(text);
47
+ if (!match || (match[2] === "" && (match[3] ?? "") === "")) return null;
48
+ const [, sign, int, frac = ""] = match;
49
+ if (frac.replace(/0+$/, "").length > scale) {
50
+ throw new CastError(`${JSON.stringify(text)} has more than ${scale} decimal place${scale === 1 ? "" : "s"}`, { fieldType: "decimal", value: text });
51
+ }
52
+ return canonical(sign, int, frac, scale);
53
+ }
54
+
55
+ function fromNumber(field, value) {
56
+ if (!Number.isFinite(value)) return null;
57
+ const { scale } = shape(field);
58
+ // Half away from zero, on the decimal text JavaScript would print, not on the binary value:
59
+ // 1.005 prints as "1.005" and rounds to "1.01" (toFixed(2) would give "1.00").
60
+ const text = Math.abs(value).toLocaleString("en-US", { useGrouping: false, maximumFractionDigits: 20 });
61
+ const [int, frac = ""] = text.split(".");
62
+ let digits = BigInt(int + frac.padEnd(scale, "0").slice(0, scale));
63
+ if (frac.length > scale && Number(frac[scale]) >= 5) digits += 1n;
64
+ return fromScaledInteger(value < 0 ? -digits : digits, scale);
65
+ }
66
+
67
+ /** The integer `digits` divided by 10^scale, as canonical text. */
68
+ function fromScaledInteger(digits, scale) {
69
+ const negative = digits < 0n;
70
+ const text = (negative ? -digits : digits).toString().padStart(scale + 1, "0");
71
+ const int = scale > 0 ? text.slice(0, -scale) : text;
72
+ const frac = scale > 0 ? text.slice(-scale) : "";
73
+ return canonical(negative ? "-" : "", int, frac, scale);
74
+ }
75
+
76
+ /** Canonical text -> the integer SQLite stores (exact: at most 15 digits, under 2^53). */
77
+ export function toScaledInteger(text, scale) {
78
+ const [int, frac = ""] = text.replace("-", "").split(".");
79
+ const n = Number(int + frac.padEnd(scale, "0"));
80
+ return text.startsWith("-") ? -n : n;
81
+ }
82
+
83
+ export const decimalType = {
84
+ name: "decimal",
85
+
86
+ validateOptions(field) {
87
+ const errors = [];
88
+ const { precision, scale } = shape(field);
89
+ if (!Number.isInteger(precision) || precision < 1 || precision > MAX_DECIMAL_PRECISION) {
90
+ errors.push(`decimal field \`precision\` must be an integer from 1 to ${MAX_DECIMAL_PRECISION} (the digits SQLite keeps exactly)`);
91
+ }
92
+ if (!Number.isInteger(scale) || scale < 0 || scale > precision) {
93
+ errors.push("decimal field `scale` must be an integer from 0 to `precision`");
94
+ }
95
+ for (const bound of ["min", "max"]) {
96
+ if (field[bound] !== undefined) {
97
+ try {
98
+ if (decimalType.cast(field, field[bound]) === undefined) throw new Error();
99
+ } catch {
100
+ errors.push(`decimal field \`${bound}\` must be a decimal value (a string like "0.00", or a number)`);
101
+ }
102
+ }
103
+ }
104
+ return errors;
105
+ },
106
+
107
+ validate(field, value) {
108
+ const { precision, scale } = shape(field);
109
+ if (typeof value !== "string" || !DECIMAL_TEXT.test(value)) {
110
+ return [`expected a decimal value like "12.50", got ${JSON.stringify(value)}`];
111
+ }
112
+ const errors = [];
113
+ const intDigits = value.replace("-", "").split(".")[0].replace(/^0+/, "");
114
+ if (intDigits.length > precision - scale) {
115
+ errors.push(`must have at most ${precision - scale} digit${precision - scale === 1 ? "" : "s"} before the decimal point (precision ${precision}, scale ${scale})`);
116
+ }
117
+ const asNumber = (text) => toScaledInteger(decimalType.cast(field, text), scale);
118
+ if (field.min !== undefined && asNumber(value) < asNumber(field.min)) errors.push(`must be >= ${decimalType.cast(field, field.min)} (got ${value})`);
119
+ if (field.max !== undefined && asNumber(value) > asNumber(field.max)) errors.push(`must be <= ${decimalType.cast(field, field.max)} (got ${value})`);
120
+ return errors;
121
+ },
122
+
123
+ cast(field, value) {
124
+ let result = null;
125
+ if (typeof value === "string") result = fromString(field, value);
126
+ else if (typeof value === "number") result = fromNumber(field, value);
127
+ else if (typeof value === "bigint") result = fromScaledInteger(value * 10n ** BigInt(shape(field).scale), shape(field).scale);
128
+ if (result === null) {
129
+ throw new CastError(`cannot cast ${typeof value === "bigint" ? `${value}n` : JSON.stringify(value)} to decimal`, { fieldType: "decimal", value });
130
+ }
131
+ return result;
132
+ },
133
+
134
+ /** The value as the database stores it - resolved per dialect when the query is bound. */
135
+ toStorage(field, value) {
136
+ const { scale } = shape(field);
137
+ return new DialectValue((dialect) => (dialect === "sqlite" ? toScaledInteger(value, scale) : value));
138
+ },
139
+
140
+ /** The stored value back to canonical text: SQLite gives the scaled integer, Postgres text. */
141
+ fromStorage(field, value, dialect) {
142
+ const { scale } = shape(field);
143
+ if (dialect === "sqlite" && typeof value === "number") return fromScaledInteger(BigInt(Math.round(value)), scale);
144
+ if (dialect === "sqlite" && typeof value === "bigint") return fromScaledInteger(value, scale);
145
+ return value;
146
+ },
147
+ };
@@ -32,6 +32,13 @@ export const integerType = {
32
32
  errors.push(`expected an integer, got ${JSON.stringify(value)}`);
33
33
  return errors;
34
34
  }
35
+ // Past 2^53 a JavaScript number can't hold every whole number, so the value written may not be
36
+ // the one given (since 0.2.0). Note: a Postgres `integer` column holds 32 bits; a larger value
37
+ // fails there with OutOfRangeError.
38
+ if (!Number.isSafeInteger(value)) {
39
+ errors.push(`must be between ${Number.MIN_SAFE_INTEGER} and ${Number.MAX_SAFE_INTEGER} (got ${value})`);
40
+ return errors;
41
+ }
35
42
  if (field.min !== undefined && value < field.min) {
36
43
  errors.push(`must be >= ${field.min} (got ${value})`);
37
44
  }
@@ -1,5 +1,5 @@
1
1
  import { createConnection, closeConnection } from "../connection.js";
2
- import { guardTransactions } from "../dialect/transaction-guard.js";
2
+ import { instrumentConnection } from "../dialect/transaction-guard.js";
3
3
  import { state } from "./state.js";
4
4
 
5
5
  /**
@@ -24,7 +24,7 @@ export function connect(configOrConnection) {
24
24
  // alive). A Knex instance the app passed in is the app's to close, so it is left alone.
25
25
  const previous = state.ownsConnection ? state.connection : null;
26
26
  const ownsNew = typeof configOrConnection !== "function";
27
- const next = ownsNew ? createConnection(configOrConnection) : guardTransactions(configOrConnection);
27
+ const next = ownsNew ? createConnection(configOrConnection) : instrumentConnection(configOrConnection);
28
28
  state.connection = next;
29
29
  state.ownsConnection = ownsNew;
30
30
  if (previous && previous !== next) closeWhenIdle(previous);
@@ -4,6 +4,7 @@ import {
4
4
  diffEntity,
5
5
  mergeRecordIntoEntity,
6
6
  ENTITY_META,
7
+ originalValue,
7
8
  } from "../uow/entity.js";
8
9
  import { withPrimaryKey } from "../crud/select.js";
9
10
  import { paginateWith } from "../crud/paginate.js";
@@ -14,6 +15,7 @@ import {
14
15
  detachRelation,
15
16
  } from "../relations/attach-detach.js";
16
17
  import { createRecords } from "../crud/create-many.js";
18
+ import { upsertRecords } from "../crud/upsert.js";
17
19
  import { assertPrimaryKeyUntouched } from "../crud/prepare-write.js";
18
20
  import { defaultFieldTypeRegistry } from "../fields/default-registry.js";
19
21
  import { getConnection } from "./connect.js";
@@ -21,6 +23,8 @@ import { state } from "./state.js";
21
23
  import { currentIdentityMap } from "./identity-scope.js";
22
24
  import { primaryKeyOf } from "../models/primary-key.js";
23
25
  import { SaveDeletedError } from "./errors.js";
26
+ import { resolveDb } from "../transaction/context.js";
27
+ import { saveEntityLifecycle, deleteEntityLifecycle } from "../uow/lifecycle.js";
24
28
 
25
29
  const assertKnownHooks = (name, hooks) => {
26
30
  for (const hookName of Object.keys(hooks)) {
@@ -104,11 +108,11 @@ function addMixinHooks(mixinName, hooks) {
104
108
  * @returns {Model}
105
109
  */
106
110
  export function extendModel(name, extension = {}) {
107
- const { fields, relations, mixins, hooks, origin } = extension;
111
+ const { fields, relations, mixins, hooks, origin, constraints } = extension;
108
112
  const targetIsMixin = state.registry.isAbstract(name);
109
113
  if (hooks && !targetIsMixin) assertKnownHooks(name, hooks); // before anything is registered
110
114
  state.registry.define(
111
- { extend: name, fields, relations, mixins },
115
+ { extend: name, fields, relations, mixins, constraints },
112
116
  { origin },
113
117
  );
114
118
  if (targetIsMixin) addMixinHooks(name, hooks);
@@ -147,9 +151,9 @@ export function extendModel(name, extension = {}) {
147
151
  * @param {string} [definition.origin]
148
152
  */
149
153
  export function defineMixin(name, definition) {
150
- const { fields, relations, mixins, hooks, origin } = definition;
154
+ const { fields, relations, mixins, hooks, origin, constraints, primaryKey } = definition;
151
155
  state.registry.define(
152
- { name, abstract: true, fields, relations, mixins },
156
+ { name, abstract: true, fields, relations, mixins, constraints, primaryKey },
153
157
  { origin },
154
158
  );
155
159
  addMixinHooks(name, hooks);
@@ -215,11 +219,11 @@ export function defineMixin(name, definition) {
215
219
  * @returns {Model}
216
220
  */
217
221
  export function createModel(name, schema) {
218
- const { fields, relations, hooks, table, mixins, origin } = schema;
222
+ const { fields, relations, hooks, table, mixins, origin, constraints, primaryKey } = schema;
219
223
  // Returns null (rather than throwing) if `mixins` names a model that doesn't exist yet: the
220
224
  // model then simply waits for it. Either way the Model below works once everything is defined.
221
225
  const descriptorNow = state.registry.define(
222
- { name, table, fields, relations, mixins },
226
+ { name, table, fields, relations, mixins, constraints, primaryKey },
223
227
  { origin },
224
228
  );
225
229
 
@@ -302,7 +306,7 @@ function getOrCreateModelHandle(name) {
302
306
  // models; each one is wrapped by its own model's wrapper.
303
307
  function createRuntime(options) {
304
308
  return {
305
- db: options.trx ?? getConnection(),
309
+ db: resolveDb(getConnection(), options.trx),
306
310
  modelRegistry: state.registry,
307
311
  fieldTypeRegistry: defaultFieldTypeRegistry,
308
312
  hooks: state.hooks,
@@ -311,58 +315,31 @@ function getOrCreateModelHandle(name) {
311
315
  };
312
316
  }
313
317
 
318
+ // Both shared with UnitOfWork (uow/lifecycle.js): hooks + the write as one atomic unit.
314
319
  async function saveDocument(entity, options = {}) {
315
- const dirty = diffEntity(entity, descriptor());
316
- if (Object.keys(dirty).length === 0) return entity;
317
-
318
- const original = entity[ENTITY_META].original;
319
- const originalSnapshot = { ...original };
320
-
321
- try {
322
- assertPrimaryKeyUntouched(descriptor(), dirty); // before any hook sees an id change
323
- await state.hooks.run(
324
- name,
325
- "beforeUpdate",
326
- entity,
327
- dirty,
328
- originalSnapshot,
329
- );
330
- await state.hooks.run(
331
- name,
332
- "beforeSave",
333
- entity,
334
- dirty,
335
- originalSnapshot,
336
- );
337
- const result = await repo().update(
338
- { [primaryKeyOf(descriptor())]: original[primaryKeyOf(descriptor())] },
339
- dirty,
340
- options,
341
- );
342
- if (!result)
343
- throw new SaveDeletedError("save() did not affect any rows.");
344
- } catch (err) {
345
- for (const key of Object.keys(dirty)) entity[key] = original[key];
346
- throw err;
347
- }
348
-
349
- for (const [key, value] of Object.entries(dirty)) {
350
- entity[key] = value;
351
- original[key] = value;
352
- }
353
-
354
- await state.hooks.run(name, "afterUpdate", entity, dirty, originalSnapshot);
355
- await state.hooks.run(name, "afterSave", entity, dirty, originalSnapshot);
356
- return entity;
320
+ const key = primaryKeyOf(descriptor());
321
+ const id = originalValue(entity, key);
322
+ return saveEntityLifecycle({
323
+ entity,
324
+ model: descriptor(),
325
+ modelName: name,
326
+ hooks: state.hooks,
327
+ db: resolveDb(getConnection(), options.trx),
328
+ write: (conn, changes) => repo().update({ [key]: id }, changes, { ...options, trx: conn.isTransaction ? conn : options.trx }),
329
+ });
357
330
  }
358
331
 
359
332
  async function deleteDocument(entity, options = {}) {
360
- const original = entity[ENTITY_META].original;
361
- await state.hooks.run(name, "beforeDelete", entity);
362
333
  const key = primaryKeyOf(descriptor());
363
- await repo().delete({ [key]: original[key] }, options);
364
- currentIdentityMap()?.delete(identityKey(original[key]));
365
- await state.hooks.run(name, "afterDelete", entity);
334
+ const id = originalValue(entity, key);
335
+ await deleteEntityLifecycle({
336
+ entity,
337
+ modelName: name,
338
+ hooks: state.hooks,
339
+ db: resolveDb(getConnection(), options.trx),
340
+ write: (conn) => repo().delete({ [key]: id }, { ...options, trx: conn.isTransaction ? conn : options.trx }),
341
+ });
342
+ currentIdentityMap()?.delete(identityKey(id));
366
343
  return true;
367
344
  }
368
345
 
@@ -410,6 +387,31 @@ function getOrCreateModelHandle(name) {
410
387
  );
411
388
  },
412
389
 
390
+ /**
391
+ * Inserts the document, or updates the row with the same `conflict` key - one atomic
392
+ * statement (since 0.2.0). `conflict` must be a unique key; `update` picks the fields
393
+ * overwritten on an existing row (default: those passed; `false` = insert if missing).
394
+ *
395
+ * await User.upsert({ email, name }, { conflict: ["email"] });
396
+ *
397
+ * @param {Record<string, unknown>} data
398
+ * @param {{ conflict: string[]|string, update?: string[]|false, trx?: import('knex').Knex.Transaction }} options
399
+ */
400
+ async upsert(data, options = {}) {
401
+ const [document] = await upsertRecords(createRuntime(options), descriptor(), [data], { ...options, labels: [""] });
402
+ return document;
403
+ },
404
+
405
+ /**
406
+ * upsert() for many rows: one INSERT ... ON CONFLICT per chunk, all-or-nothing.
407
+ *
408
+ * @param {Record<string, unknown>[]} dataList
409
+ * @param {{ conflict: string[]|string, update?: string[]|false, trx?: import('knex').Knex.Transaction, chunkSize?: number }} options
410
+ */
411
+ async upsertMany(dataList, options = {}) {
412
+ return upsertRecords(createRuntime(options), descriptor(), dataList, options);
413
+ },
414
+
413
415
  /**
414
416
  * `select` limits the fields read; the primary key is always included so the document can
415
417
  * save itself and take part in the identity map. `with` takes names, paths or
@@ -511,7 +513,7 @@ function getOrCreateModelHandle(name) {
511
513
 
512
514
  /** @param {{ trx?: import('knex').Knex.Transaction }} [options] */
513
515
  async attach(source, relationName, targetIds, options = {}) {
514
- const db = options.trx ?? getConnection();
516
+ const db = resolveDb(getConnection(), options.trx);
515
517
  return attachRelation(
516
518
  db,
517
519
  descriptor(),
@@ -530,13 +532,13 @@ function getOrCreateModelHandle(name) {
530
532
  * @param {{ trx?: import('knex').Knex.Transaction }} [options]
531
533
  */
532
534
  async attachMany(relationName, links, options = {}) {
533
- const db = options.trx ?? getConnection();
535
+ const db = resolveDb(getConnection(), options.trx);
534
536
  return attachManyRelation(db, descriptor(), name, relationName, links);
535
537
  },
536
538
 
537
539
  /** @param {{ trx?: import('knex').Knex.Transaction }} [options] */
538
540
  async detach(source, relationName, targetIds, options = {}) {
539
- const db = options.trx ?? getConnection();
541
+ const db = resolveDb(getConnection(), options.trx);
540
542
  return detachRelation(
541
543
  db,
542
544
  descriptor(),
@@ -1,6 +1,6 @@
1
1
  export class SaveDeletedError extends Error {
2
2
  constructor(message) {
3
3
  super(message);
4
- this.name = "SavedDeletedError";
4
+ this.name = "SaveDeletedError";
5
5
  }
6
6
  }
@@ -11,3 +11,4 @@ export { withIdentityMap } from "./identity-scope.js";
11
11
  export { diffModels, migrateModels, getDefaultModelRegistry } from "./migrate.js";
12
12
  export { generateModelDTOs, generateAllModelDTOs, generateModelJSDoc } from "./dto.js";
13
13
  export { __resetGlobalStateForTests } from "./state.js";
14
+ export { SaveDeletedError } from "./errors.js";
@@ -1,26 +1,24 @@
1
1
  import { getConnection } from "./connect.js";
2
+ import { resolveDb } from "../transaction/context.js";
2
3
 
3
4
  /**
4
- * Runs `fn` inside a transaction on the default connection, passing
5
- * the transaction object through so it can be handed to any Model
6
- * method's `{ trx }` option (`Order.create(data, { trx })`) to
7
- * include it in the same atomic unit. Every `Model` method - `create`,
8
- * `find`, `findOne`, `updateMany`, `deleteMany`, `attach`, `detach`,
9
- * and a document's own `save()`/`delete()` - accepts `{ trx }` for
10
- * exactly this reason.
5
+ * Runs `fn` inside a transaction on the default connection.
11
6
  *
12
- * Without this, a multi-step write across Models (e.g. creating an
13
- * order plus each of its line items) has no way to be atomic: each
14
- * `Model.create()` call would hit the default connection directly,
15
- * with no way to roll every step back together if a later one fails.
7
+ * Since 0.2.0 every model call made while `fn` runs joins the transaction on its own - in `fn`,
8
+ * in a helper it calls, in a hook - so `{ trx }` no longer has to be passed along (it still works,
9
+ * and `fn` still receives the transaction for raw Knex queries: `trx("table")...`).
16
10
  *
17
- * If `fn` throws (or returns a rejected promise), Knex rolls the
18
- * transaction back automatically and the rejection propagates here.
11
+ * Called while a transaction is already open in this async flow, it opens a savepoint inside it:
12
+ * if `fn` throws, only the savepoint's work is undone and the error propagates to the outer code.
13
+ *
14
+ * Writes and their before/after hooks commit or roll back together. `afterCommit` hooks run once
15
+ * the outermost transaction has committed, before this promise resolves (an error there rejects it,
16
+ * though the data stays committed).
19
17
  *
20
18
  * @template T
21
19
  * @param {(trx: import('knex').Knex.Transaction) => Promise<T>} fn
22
20
  * @returns {Promise<T>}
23
21
  */
24
22
  export async function transaction(fn) {
25
- return getConnection().transaction(fn);
23
+ return resolveDb(getConnection()).transaction(fn);
26
24
  }
package/src/index.js CHANGED
@@ -14,3 +14,5 @@ export * from "./uow/index.js";
14
14
  export * from "./client/index.js";
15
15
  export * from "./global/index.js";
16
16
  export * from "./dto/index.js";
17
+ export { afterCommit } from "./transaction/after-commit.js";
18
+ export { resolveDb, ambientTransaction } from "./transaction/context.js";
@@ -27,7 +27,17 @@ export async function ensureMetaTables(db) {
27
27
  table.timestamp("created_at").notNullable();
28
28
  table.timestamp("updated_at").notNullable();
29
29
  table.timestamp("removed_at").nullable();
30
+ table.text("constraints").nullable();
30
31
  });
32
+ // Since 0.2.0: the model's multi-field constraints (models/constraints.js), so migrations can
33
+ // tell which were added or removed. Tables made by 0.1.x get the column here; NULL = none recorded.
34
+ if (!(await db.schema.hasColumn(META_MODELS_TABLE, "constraints"))) {
35
+ try {
36
+ await db.schema.alterTable(META_MODELS_TABLE, (table) => table.text("constraints").nullable());
37
+ } catch (error) {
38
+ if (!(await db.schema.hasColumn(META_MODELS_TABLE, "constraints"))) throw error; // another process added it
39
+ }
40
+ }
31
41
  }
32
42
 
33
43
  {
@@ -1,4 +1,5 @@
1
1
  import { META_MODELS_TABLE, META_FIELDS_TABLE } from "./reserved-tables.js";
2
+ import { parseStoredConstraints } from "./upsert.js";
2
3
 
3
4
  /**
4
5
  * A portable, id-free picture of one model's rows in `_meta_models` /
@@ -15,6 +16,8 @@ import { META_MODELS_TABLE, META_FIELDS_TABLE } from "./reserved-tables.js";
15
16
  * @typedef {Object} ModelMetaSnapshot
16
17
  * @property {string} table_name
17
18
  * @property {boolean} removed
19
+ * @property {Array<{ kind: string, name: string, fields: string[], columns: string[] }>} [constraints] - since 0.2.0;
20
+ * absent in migrations generated before, which then leave the stored value alone
18
21
  * @property {Array<{
19
22
  * name: string, column: string, type: string, required: boolean,
20
23
  * is_unique: boolean, is_indexed: boolean, options: unknown, removed: boolean
@@ -43,6 +46,7 @@ export async function snapshotModelMeta(db, modelName) {
43
46
  return {
44
47
  table_name: model.table_name,
45
48
  removed: model.removed_at !== null && model.removed_at !== undefined,
49
+ constraints: parseStoredConstraints(model.constraints),
46
50
  fields: rows.map((row) => ({
47
51
  name: row.name,
48
52
  column: row.column,
@@ -84,6 +88,7 @@ export async function restoreModelMeta(db, modelName, snapshot) {
84
88
  updated_at: now,
85
89
  removed_at: snapshot.removed ? now : null,
86
90
  };
91
+ if (snapshot.constraints !== undefined) modelValues.constraints = JSON.stringify(snapshot.constraints);
87
92
  let modelId;
88
93
  if (existing) {
89
94
  modelId = existing.id;
@@ -17,12 +17,14 @@ import { META_MODELS_TABLE, META_FIELDS_TABLE } from "./reserved-tables.js";
17
17
  */
18
18
  export async function ensureMetaModel(trx, model, now) {
19
19
  const existing = await trx(META_MODELS_TABLE).where({ name: model.name }).first();
20
+ const constraints = serializeConstraints(model.constraints);
20
21
 
21
22
  if (existing) {
22
23
  await trx(META_MODELS_TABLE).where({ id: existing.id }).update({
23
24
  table_name: model.tableName,
24
25
  updated_at: now,
25
26
  removed_at: null,
27
+ constraints,
26
28
  });
27
29
  return existing.id;
28
30
  }
@@ -33,6 +35,7 @@ export async function ensureMetaModel(trx, model, now) {
33
35
  created_at: now,
34
36
  updated_at: now,
35
37
  removed_at: null,
38
+ constraints,
36
39
  });
37
40
  const created = await trx(META_MODELS_TABLE).where({ name: model.name }).first();
38
41
  return created.id;
@@ -181,3 +184,28 @@ export async function flagRemovedFields(trx, modelId, currentFieldNames, now) {
181
184
  }
182
185
  return removed;
183
186
  }
187
+
188
+ /**
189
+ * A model's multi-field constraints as stored in `_meta_models.constraints` (since 0.2.0):
190
+ * `[{ kind: "unique"|"index", name, fields, columns }]`, as JSON text.
191
+ *
192
+ * @param {import('../models/constraints.js').ModelConstraints|undefined} constraints
193
+ */
194
+ export function serializeConstraints(constraints) {
195
+ return JSON.stringify(constraintList(constraints));
196
+ }
197
+
198
+ /** @returns {Array<{ kind: string, name: string, fields: string[], columns: string[] }>} */
199
+ export function constraintList(constraints) {
200
+ const list = [];
201
+ for (const kind of ["unique", "index"]) {
202
+ for (const c of constraints?.[kind] ?? []) list.push({ kind, name: c.name, fields: [...c.fields], columns: [...c.columns] });
203
+ }
204
+ return list;
205
+ }
206
+
207
+ /** The stored constraints of a `_meta_models` row; a row from before 0.2.0 has none. */
208
+ export function parseStoredConstraints(value) {
209
+ if (value === null || value === undefined) return [];
210
+ return typeof value === "string" ? JSON.parse(value) : value;
211
+ }
@@ -54,6 +54,18 @@ export function describePlan(plan) {
54
54
  `[DESTRUCTIVE] ${modelName}: drop field "${drop.fieldName}" (column "${drop.columnName}") - data will be lost`
55
55
  );
56
56
  }
57
+ for (const change of changes.optionChanges ?? []) {
58
+ const { label, detail } = describeOptionChange(change);
59
+ lines.push(`${label}${modelName}: field "${change.fieldName}" ${detail}`);
60
+ }
61
+ for (const c of changes.addConstraints ?? []) {
62
+ const label = c.kind === "unique" ? "[check] " : "[safe] ";
63
+ const note = c.kind === "unique" ? " - fails (and rolls back) if existing rows have duplicates" : "";
64
+ lines.push(`${label}${modelName}: add ${c.kind} (${c.fields.join(", ")}) "${c.name}"${note}`);
65
+ }
66
+ for (const c of changes.dropConstraints ?? []) {
67
+ lines.push(`[safe] ${modelName}: drop ${c.kind} (${c.fields.join(", ")}) "${c.name}"`);
68
+ }
57
69
  for (const change of changes.typeChanges) {
58
70
  lines.push(
59
71
  `[MANUAL] ${modelName}: field "${change.fieldName}" type changed ${change.from} -> ${change.to} - ` +
@@ -75,3 +87,40 @@ export function describePlan(plan) {
75
87
 
76
88
  return lines;
77
89
  }
90
+
91
+ /**
92
+ * One line per changed field (since 0.2.0). "[check]" means the database checks existing rows
93
+ * against the new rule: the migration fails and rolls back, changing nothing, if some don't fit.
94
+ */
95
+ function describeOptionChange({ changes, from, to }) {
96
+ const parts = [];
97
+ let check = false;
98
+ for (const key of changes) {
99
+ if (key === "required") {
100
+ if (to.required) {
101
+ const fill = to.default !== undefined && typeof to.default !== "function";
102
+ parts.push(fill ? `now required (existing NULLs set to ${JSON.stringify(to.default)})` : "now required");
103
+ check ||= !fill;
104
+ } else parts.push("now optional");
105
+ } else if (key === "unique") {
106
+ parts.push(to.unique ? "now unique" : "no longer unique");
107
+ check ||= Boolean(to.unique);
108
+ } else if (key === "index") {
109
+ parts.push(to.index ? "indexed" : "index dropped");
110
+ } else if (key === "default") {
111
+ parts.push(to.default === undefined || typeof to.default === "function" ? "default removed" : `default ${JSON.stringify(to.default)}`);
112
+ } else if (key === "maxLength") {
113
+ const [a, b] = [from.maxLength ?? 255, to.maxLength ?? 255];
114
+ parts.push(`maxLength ${a} -> ${b}`);
115
+ check ||= b < a;
116
+ } else if (key === "values") {
117
+ const removed = (from.values ?? []).filter((v) => !(to.values ?? []).includes(v));
118
+ const added = (to.values ?? []).filter((v) => !(from.values ?? []).includes(v));
119
+ if (added.length) parts.push(`allows ${added.map((v) => JSON.stringify(v)).join(", ")}`);
120
+ if (removed.length) parts.push(`no longer allows ${removed.map((v) => JSON.stringify(v)).join(", ")}`);
121
+ check ||= removed.length > 0;
122
+ }
123
+ }
124
+ const note = check ? " - checked against existing rows; fails (and rolls back) if some don't fit" : "";
125
+ return { label: check ? "[check] " : "[safe] ", detail: parts.join(", ") + note };
126
+ }