@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
@@ -3,6 +3,7 @@ import { prepareWrite, assertPrimaryKeyUntouched } from "./prepare-write.js";
3
3
  import { resolveWhere, isEmptyFilter } from "./resolve-where.js";
4
4
  import { fromRow, toRow } from "./row-mapping.js";
5
5
  import { applyOrderAndPaging } from "./order.js";
6
+ import { compileFastFind, compileFastUpdate, compileFastDelete, runFast } from "./fast-path.js";
6
7
  import { ValidationError } from "./errors.js";
7
8
  import { eagerLoad } from "../relations/eager-load.js";
8
9
  import { normalizeWith, parentKeysNeeded } from "../relations/with-spec.js";
@@ -18,6 +19,12 @@ import { createRecords } from "./create-many.js";
18
19
  import { RelationError } from "../relations/errors.js";
19
20
  import { serializeJsonFields } from "./insert-many.js";
20
21
  import { isPostgres } from "./sequence.js";
22
+ import { dialectOfClient } from "../fields/storage.js";
23
+ import { resolveDb } from "../transaction/context.js";
24
+ import { upsertRecords } from "./upsert.js";
25
+ import { splitValueExpressions } from "./value.js";
26
+ import { translatingErrors } from "./database-errors.js";
27
+ import { instrumentConnection } from "../dialect/transaction-guard.js";
21
28
 
22
29
  /**
23
30
  * The CRUD surface for a single model. Every method speaks in field
@@ -53,14 +60,19 @@ export class Repository {
53
60
  fieldTypeRegistry = defaultFieldTypeRegistry,
54
61
  modelRegistry = undefined,
55
62
  ) {
56
- this.db = db;
63
+ this.db = instrumentConnection(db);
57
64
  this.model = model;
58
65
  this.fieldTypeRegistry = fieldTypeRegistry;
59
66
  this.modelRegistry = modelRegistry;
60
67
  }
61
68
 
69
+ /** The connection to run on: `trx`, else the transaction open in this async flow, else this.db. */
70
+ #conn(trx) {
71
+ return resolveDb(this.db, trx);
72
+ }
73
+
62
74
  #queryBuilder(trx) {
63
- return (trx ?? this.db)(this.model.tableName);
75
+ return this.#conn(trx)(this.model.tableName);
64
76
  }
65
77
 
66
78
  #createRuntime() {
@@ -88,6 +100,17 @@ export class Repository {
88
100
  * @returns {Promise<Record<string, unknown>>}
89
101
  * @throws {ValidationError}
90
102
  */
103
+ /** Insert, or update the row with the same `conflict` key - see upsertRecords(). Since 0.2.0. */
104
+ async upsert(data, options = {}) {
105
+ const [record] = await upsertRecords(this.#createRuntime(), this.model, [data], { ...options, labels: [""] });
106
+ return record;
107
+ }
108
+
109
+ /** Many upserts, one statement per chunk - see upsertRecords(). Since 0.2.0. */
110
+ async upsertMany(dataList, options = {}) {
111
+ return upsertRecords(this.#createRuntime(), this.model, dataList, options);
112
+ }
113
+
91
114
  async create(data, options = {}) {
92
115
  const [record] = await createRecords(
93
116
  this.#createRuntime(),
@@ -173,27 +196,32 @@ export class Repository {
173
196
  : [],
174
197
  );
175
198
 
176
- const where = resolveWhere(
177
- this.model,
178
- filter,
179
- this.fieldTypeRegistry,
180
- this.modelRegistry,
181
- );
182
- let query = this.#queryBuilder(options.trx).where(where);
183
- if (plan.columns) query = query.select(plan.columns);
184
- query = applyOrderAndPaging(query, this.model, options);
185
-
186
- const rows = await query;
199
+ const conn = this.#conn(options.trx);
200
+ // Most finds are written as SQL directly and reuse a prepared statement (crud/fast-path.js);
201
+ // the rest - and anything that path declines - are built with Knex.
202
+ const fast = compileFastFind(this.db, this.model, filter, plan.columns, options, this.fieldTypeRegistry);
203
+ let rows = fast ? await runFast(conn, fast) : undefined;
204
+ if (rows === undefined) {
205
+ const where = resolveWhere(
206
+ this.model,
207
+ filter,
208
+ this.fieldTypeRegistry,
209
+ this.modelRegistry,
210
+ );
211
+ let query = conn(this.model.tableName).where(where);
212
+ if (plan.columns) query = query.select(plan.columns);
213
+ query = applyOrderAndPaging(query, this.model, options);
214
+ if (options.lock !== undefined) query = applyLock(query, conn, this.model.name, options);
215
+ rows = await query;
216
+ }
217
+ const readOptions = { computed: plan.computed, jsonParsed: isPostgres(this.db), dialect: dialectOfClient(this.db.client) };
187
218
  const records = rows.map((row) =>
188
- fromRow(this.model, row, this.fieldTypeRegistry, {
189
- computed: plan.computed,
190
- jsonParsed: isPostgres(this.db),
191
- }),
219
+ fromRow(this.model, row, this.fieldTypeRegistry, readOptions),
192
220
  );
193
221
 
194
222
  if (tree.size > 0) {
195
223
  await eagerLoad(
196
- options.trx ?? this.db,
224
+ conn,
197
225
  this.modelRegistry,
198
226
  this.model,
199
227
  records,
@@ -247,7 +275,7 @@ export class Repository {
247
275
  */
248
276
  async aggregate(filter = {}, options = {}) {
249
277
  return runAggregate({
250
- db: options.trx ?? this.db,
278
+ db: this.#conn(options.trx),
251
279
  model: this.model,
252
280
  filter,
253
281
  options,
@@ -357,7 +385,7 @@ export class Repository {
357
385
  const { trx, ...constraints } = options;
358
386
  const withSpec = typeof spec === "string" ? { [spec]: constraints } : spec;
359
387
  await eagerLoad(
360
- trx ?? this.db,
388
+ this.#conn(trx),
361
389
  modelRegistry,
362
390
  this.model,
363
391
  records,
@@ -410,29 +438,37 @@ export class Repository {
410
438
  });
411
439
  }
412
440
  assertPrimaryKeyUntouched(this.model, data);
441
+ // Value.increment()/decrement() become `col = col + ?` (since 0.2.0); the rest is validated as usual.
442
+ const { plain, hasExpressions, toSet, expressions } = splitValueExpressions(this.model, data, this.fieldTypeRegistry);
413
443
  const { errors, values } = prepareWrite(
414
444
  this.model,
415
- data,
445
+ plain,
416
446
  { partial: true },
417
447
  this.fieldTypeRegistry,
418
448
  );
419
449
  if (Object.keys(errors).length > 0) {
420
450
  throw new ValidationError(this.model.name, errors);
421
451
  }
422
- if (Object.keys(values).length === 0) {
452
+ if (Object.keys(values).length === 0 && !hasExpressions) {
423
453
  throw new ValidationError(this.model.name, {
424
454
  _: ["update() requires at least one field to update"],
425
455
  });
426
456
  }
427
457
 
428
- const where = resolveWhere(
429
- this.model,
430
- filter,
431
- this.fieldTypeRegistry,
432
- this.modelRegistry,
433
- );
434
- const row = toRow(this.model, serializeJsonFields(this.model, values));
435
- return this.#queryBuilder(options.trx).where(where).update(row);
458
+ const row = toRow(this.model, serializeJsonFields(this.model, values, this.fieldTypeRegistry));
459
+ const conn = this.#conn(options.trx);
460
+ const fast = compileFastUpdate(this.db, this.model, filter, row, expressions, this.fieldTypeRegistry);
461
+ return translatingErrors(this.model, async () => {
462
+ const changed = fast ? await runFast(conn, fast) : undefined;
463
+ if (changed !== undefined) return changed;
464
+ const where = resolveWhere(
465
+ this.model,
466
+ filter,
467
+ this.fieldTypeRegistry,
468
+ this.modelRegistry,
469
+ );
470
+ return conn(this.model.tableName).where(where).update({ ...row, ...toSet(conn) });
471
+ });
436
472
  }
437
473
 
438
474
  /**
@@ -455,22 +491,29 @@ export class Repository {
455
491
  });
456
492
  }
457
493
 
458
- const where = resolveWhere(
459
- this.model,
460
- filter,
461
- this.fieldTypeRegistry,
462
- this.modelRegistry,
463
- );
494
+ const fast = hasIncomingRelations(this.modelRegistry, this.model.name) ? null : compileFastDelete(this.db, this.model, filter, this.fieldTypeRegistry);
495
+ const where = fast
496
+ ? null
497
+ : resolveWhere(
498
+ this.model,
499
+ filter,
500
+ this.fieldTypeRegistry,
501
+ this.modelRegistry,
502
+ );
464
503
 
465
504
  // Referential integrity (restrict / set null / cascade) is enforced by the database's own
466
505
  // foreign keys, so this is one statement. Only a model that a `constraint: false` relation
467
506
  // points at takes the slower path, where the ORM applies onDelete itself.
468
507
  try {
508
+ if (fast) {
509
+ const deleted = await runFast(this.#conn(options.trx), fast);
510
+ if (deleted !== undefined) return deleted;
511
+ }
469
512
  if (!hasIncomingRelations(this.modelRegistry, this.model.name)) {
470
- return await this.#queryBuilder(options.trx).where(where).delete();
513
+ return await this.#queryBuilder(options.trx).where(where ?? resolveWhere(this.model, filter, this.fieldTypeRegistry, this.modelRegistry)).delete();
471
514
  }
472
515
  return await deleteRowsWithCascade(
473
- this.db,
516
+ this.#conn(options.trx),
474
517
  this.modelRegistry,
475
518
  this.model,
476
519
  where,
@@ -505,3 +548,28 @@ export function createRepository(
505
548
  ) {
506
549
  return new Repository(db, model, fieldTypeRegistry, modelRegistry);
507
550
  }
551
+
552
+ /**
553
+ * Row locking for find() (since 0.2.0): `{ lock: "update" }` reads the rows with SELECT ... FOR
554
+ * UPDATE, so no other transaction can change (or lock) them until this one ends - the safe way to
555
+ * check-then-write (a balance, stock, a job queue). `"share"` lets others read-lock too but not
556
+ * write. `skipLocked: true` skips rows another transaction holds (a job queue's "take the next free
557
+ * one"). Only meaningful inside a transaction, so it is refused outside one.
558
+ *
559
+ * SQLite has no row locks and needs none: a write transaction locks the whole database, and
560
+ * transactions run one at a time. There the option is accepted and does nothing.
561
+ */
562
+ function applyLock(query, conn, modelName, options) {
563
+ const mode = options.lock;
564
+ if (mode !== "update" && mode !== "share") {
565
+ throw new ValidationError(modelName, { lock: ['`lock` must be "update" or "share"'] });
566
+ }
567
+ if (!conn.isTransaction) {
568
+ throw new ValidationError(modelName, {
569
+ lock: ["`lock` only works inside a transaction: wrap the read and the write in transaction(async () => { ... })"],
570
+ });
571
+ }
572
+ if (!isPostgres(conn)) return query;
573
+ query = mode === "update" ? query.forUpdate() : query.forShare();
574
+ return options.skipLocked ? query.skipLocked() : query;
575
+ }
@@ -1,4 +1,3 @@
1
- import { castValue } from "../fields/cast-value.js";
2
1
  import { defaultFieldTypeRegistry } from "../fields/default-registry.js";
3
2
  import { defineComputedGetters } from "../fields/computed-access.js";
4
3
 
@@ -42,17 +41,19 @@ export const PARTIAL = Symbol("partialRecord");
42
41
  */
43
42
  export function fromRow(model, row, fieldTypeRegistry = defaultFieldTypeRegistry, options = {}) {
44
43
  const record = {};
44
+ const plan = readPlan(model, fieldTypeRegistry);
45
+ const parseJsonText = !options.jsonParsed;
46
+ const dialect = options.dialect;
45
47
 
46
- for (const [fieldName, field] of Object.entries(model.fields)) {
47
- const columnName = model.columns[fieldName];
48
+ for (let i = 0; i < plan.length; i++) {
49
+ const { fieldName, columnName, field, typeDef, isJson } = plan[i];
48
50
  if (!(columnName in row)) continue;
49
51
 
50
52
  let value = row[columnName];
51
53
  if (value !== null && value !== undefined) {
52
- if (field.type === "json" && typeof value === "string" && !options.jsonParsed) {
53
- value = JSON.parse(value);
54
- }
55
- value = castValue(field, value, fieldTypeRegistry);
54
+ if (isJson && parseJsonText && typeof value === "string") value = JSON.parse(value);
55
+ if (dialect && typeDef.fromStorage) value = typeDef.fromStorage(field, value, dialect);
56
+ if (value !== null && value !== undefined) value = typeDef.cast(field, value);
56
57
  }
57
58
  record[fieldName] = value;
58
59
  }
@@ -82,3 +83,27 @@ export function toRow(model, fieldValues) {
82
83
  }
83
84
  return row;
84
85
  }
86
+
87
+ /**
88
+ * Per model and field-type registry, what fromRow() needs for each field - resolved once instead
89
+ * of on every value of every row (since 0.2.0). Models and registries are immutable once in use;
90
+ * a model redefined (extendModel) is a new descriptor object and gets its own plan.
91
+ */
92
+ const readPlans = new WeakMap();
93
+ function readPlan(model, fieldTypeRegistry) {
94
+ let byRegistry = readPlans.get(model);
95
+ if (!byRegistry) readPlans.set(model, (byRegistry = new WeakMap()));
96
+ let plan = byRegistry.get(fieldTypeRegistry);
97
+ if (!plan || plan.version !== fieldTypeRegistry.version) {
98
+ plan = Object.entries(model.fields).map(([fieldName, field]) => ({
99
+ fieldName,
100
+ columnName: model.columns[fieldName],
101
+ field,
102
+ typeDef: fieldTypeRegistry.get(field.type),
103
+ isJson: field.type === "json",
104
+ }));
105
+ plan.version = fieldTypeRegistry.version;
106
+ byRegistry.set(fieldTypeRegistry, plan);
107
+ }
108
+ return plan;
109
+ }
@@ -0,0 +1,203 @@
1
+ import { prepareWrite } from "./prepare-write.js";
2
+ import { ValidationError } from "./errors.js";
3
+ import { toRow, fromRow } from "./row-mapping.js";
4
+ import { serializeJsonFields, rowsPerStatement, chunkArray } from "./insert-many.js";
5
+ import { advanceSequence, isPostgres } from "./sequence.js";
6
+ import { primaryKeyOf } from "../models/primary-key.js";
7
+ import { resolveDb, inTransactionIf } from "../transaction/context.js";
8
+ import { hookContext, runAfterHooks } from "../uow/lifecycle.js";
9
+ import { ENTITY_META, originalValues } from "../uow/entity.js";
10
+ import { dialectOfClient } from "../fields/storage.js";
11
+ import { translatingErrors } from "./database-errors.js";
12
+ import { RelationError } from "../relations/errors.js";
13
+
14
+ const INSERTED = "__kiri_inserted";
15
+
16
+ /**
17
+ * Inserts each record, or - when a row with the same `conflict` key exists - updates that row
18
+ * instead, in one `INSERT ... ON CONFLICT` statement per chunk (since 0.2.0). Atomic per row:
19
+ * two requests upserting the same key at once can't both insert, unlike find-then-create.
20
+ *
21
+ * await User.upsert({ email, name }, { conflict: ["email"] });
22
+ * await User.upsertMany(rows, { conflict: ["orgId", "email"], update: ["name"] });
23
+ * await Tag.upsertMany(names.map((name) => ({ name })), { conflict: ["name"], update: false }); // insert if missing
24
+ *
25
+ * Options:
26
+ * - `conflict` (required): the fields that decide whether a row "already exists". They must form a
27
+ * unique key - the primary key, a `unique: true` field, or a `constraints.unique` entry - because
28
+ * that's what the database checks.
29
+ * - `update`: the fields to overwrite when the row exists. Default: the fields you passed (never
30
+ * the conflict fields or the primary key; defaults for fields you left out aren't written over
31
+ * existing values). An array picks them; `false` means insert-if-missing and leave existing rows alone.
32
+ *
33
+ * Hooks: `beforeSave(record, ctx)` runs first with ctx.event "upsert" and ctx.isNew undefined -
34
+ * whether it will insert isn't known yet. After the write, each row gets `afterCreate` or
35
+ * `afterUpdate` (ctx.event / ctx.isNew say which), then `afterSave` and `afterCommit`, as for
36
+ * create and save. With `update: false`, a row that already existed runs no after-hooks: nothing
37
+ * was written. Postgres reports which rows were inserted; SQLite (one writer at a time) is checked
38
+ * for existing keys inside the same transaction.
39
+ *
40
+ * Returns the stored records (documents, through runtime.wrap) in input order. Relation values
41
+ * aren't accepted here - upsert the related rows separately.
42
+ *
43
+ * @param {import('./create-many.js').CreateRuntime} runtime
44
+ * @param {import('../models/define-model.js').ModelDescriptor} model
45
+ * @param {Record<string, unknown>[]} dataList
46
+ * @param {{ conflict: string[]|string, update?: string[]|false, trx?: import('knex').Knex.Transaction, chunkSize?: number, labels?: string[] }} options
47
+ */
48
+ export async function upsertRecords(runtime, model, dataList, options = {}) {
49
+ if (!Array.isArray(dataList)) throw new TypeError(`upsertMany() for model "${model.name}" expects an array of records`);
50
+ if (dataList.length === 0) return [];
51
+ const conflict = resolveConflict(model, options.conflict);
52
+ const pk = primaryKeyOf(model);
53
+ const labels = options.labels ?? dataList.map((_, i) => `[${i}]`);
54
+ const { fieldTypeRegistry, hooks } = runtime;
55
+ const baseDb = resolveDb(runtime.db, options.trx);
56
+ const statements = Math.ceil(dataList.length / rowsPerStatement(baseDb, Object.keys(model.fields).length, options.chunkSize));
57
+ const needsTransaction = (hooks?.has(model.name) ?? false) || statements > 1;
58
+
59
+ return translatingErrors(model, () => inTransactionIf(needsTransaction, baseDb, async (db) => {
60
+ const postgres = isPostgres(db);
61
+ const readOptions = { jsonParsed: postgres, dialect: dialectOfClient(db.client) };
62
+
63
+ // Phase 1 - beforeSave hooks and validation; nothing is written.
64
+ const rows = [];
65
+ const errors = {};
66
+ for (let i = 0; i < dataList.length; i++) {
67
+ const data = dataList[i];
68
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
69
+ throw new TypeError(`Cannot upsert model "${model.name}": entry ${labels[i] || "[0]"} must be an object of field values`);
70
+ }
71
+ const relationKey = Object.keys(data).find((key) => key in (model.relations ?? {}));
72
+ if (relationKey) {
73
+ throw new RelationError(`upsert() on "${model.name}" doesn't write relations ("${relationKey}"): upsert or attach the related records separately`);
74
+ }
75
+ if (hooks?.has(model.name, ["beforeSave"])) await hooks.run(model.name, "beforeSave", data, hookContext(db, "upsert", { isNew: undefined, changes: data, model: model.name }));
76
+ const { errors: fieldErrors, values } = prepareWrite(model, data, { partial: false }, fieldTypeRegistry);
77
+ for (const [field, messages] of Object.entries(fieldErrors)) errors[`${labels[i]}${labels[i] ? "." : ""}${field}`] = messages;
78
+ const provided = Object.keys(data).filter((key) => key in model.fields);
79
+ rows.push({ data, values, provided, key: keyOf(conflict, values) });
80
+ }
81
+ if (Object.keys(errors).length > 0) throw new ValidationError(model.name, errors);
82
+
83
+ const seen = new Map();
84
+ for (let i = 0; i < rows.length; i++) {
85
+ if (seen.has(rows[i].key)) {
86
+ throw new ValidationError(model.name, {
87
+ [labels[i] || "conflict"]: [`has the same ${conflict.join(" + ")} as ${labels[seen.get(rows[i].key)] || "another row"}: one statement can't insert or update a row twice`],
88
+ });
89
+ }
90
+ seen.set(rows[i].key, i);
91
+ }
92
+
93
+ const updateFields = resolveUpdate(model, options.update, rows, conflict, pk);
94
+ const conflictColumns = conflict.map((f) => model.columns[f]);
95
+
96
+ // SQLite can't say which rows a statement inserted; look the keys up first (same transaction).
97
+ const existedBefore = !postgres && hooks?.has(model.name) ? await existingKeys(db, model, conflict, rows, readOptions, fieldTypeRegistry) : null;
98
+
99
+ // Phase 2 - the statements.
100
+ await advanceSequence(db, model, rows.map((r) => r.values));
101
+ const stored = new Map(); // key -> { record, inserted }
102
+ for (const chunk of chunkArray(rows, rowsPerStatement(db, Object.keys(model.fields).length, options.chunkSize))) {
103
+ let query = db(model.tableName)
104
+ .insert(chunk.map((r) => toRow(model, serializeJsonFields(model, r.values, fieldTypeRegistry))))
105
+ .onConflict(conflictColumns);
106
+ query = updateFields === null ? query.ignore() : query.merge(updateFields.map((f) => model.columns[f]));
107
+ const returned = await (postgres ? query.returning(["*", db.raw("(xmax = 0) as ??", [INSERTED])]) : query.returning("*"));
108
+ for (const row of returned) {
109
+ const inserted = postgres ? Boolean(row[INSERTED]) : null;
110
+ const record = fromRow(model, row, fieldTypeRegistry, readOptions);
111
+ const key = keyOf(conflict, record);
112
+ stored.set(key, { record, inserted: inserted ?? (existedBefore ? !existedBefore.has(key) : true) });
113
+ }
114
+ }
115
+ // `update: false` returns nothing for a row that already existed: read those back.
116
+ const missing = rows.filter((r) => !stored.has(r.key));
117
+ if (missing.length > 0) {
118
+ for (const record of await readByKeys(db, model, conflict, missing, readOptions, fieldTypeRegistry)) {
119
+ stored.set(keyOf(conflict, record), { record, inserted: false, untouched: true });
120
+ }
121
+ }
122
+
123
+ // Phase 3 - documents and after-hooks (inside the unit; afterCommit after it).
124
+ const results = [];
125
+ for (const row of rows) {
126
+ const entry = stored.get(row.key);
127
+ const result = runtime.wrap ? runtime.wrap(model.name, entry.record) : entry.record;
128
+ if (hooks && !entry.untouched) {
129
+ const event = entry.inserted ? "create" : "update";
130
+ const written = result?.[ENTITY_META] ? originalValues(result) : { ...entry.record };
131
+ const changes = entry.inserted ? written : Object.fromEntries(updateFields.map((f) => [f, row.values[f]]));
132
+ await runAfterHooks(hooks, model.name, db, event, result, hookContext(db, event, { isNew: entry.inserted, changes, model: model.name }));
133
+ }
134
+ results.push(result);
135
+ }
136
+ return results;
137
+ }));
138
+ }
139
+
140
+ function resolveConflict(model, conflictOption) {
141
+ const conflict = typeof conflictOption === "string" ? [conflictOption] : conflictOption;
142
+ const fail = (message) => {
143
+ throw new ValidationError(model.name, { conflict: [message] });
144
+ };
145
+ if (!Array.isArray(conflict) || conflict.length === 0) {
146
+ fail(`upsert needs \`conflict\`: the fields that identify an existing row, e.g. { conflict: ["email"] }`);
147
+ }
148
+ for (const f of conflict) if (!(f in model.fields)) fail(`"${f}" is not a field of "${model.name}"`);
149
+ const same = (fields) => fields.length === conflict.length && fields.every((f) => conflict.includes(f));
150
+ const pk = primaryKeyOf(model);
151
+ const isUniqueKey =
152
+ (pk !== null && same([pk])) ||
153
+ (conflict.length === 1 && model.fields[conflict[0]].unique) ||
154
+ (model.constraints?.unique ?? []).some((c) => same(c.fields));
155
+ if (!isUniqueKey) {
156
+ fail(
157
+ `${JSON.stringify(conflict)} isn't a unique key of "${model.name}". Use the primary key, a field with \`unique: true\`, ` +
158
+ `or add it to the model's constraints: { unique: [${JSON.stringify(conflict)}] }`
159
+ );
160
+ }
161
+ return conflict;
162
+ }
163
+
164
+ function resolveUpdate(model, updateOption, rows, conflict, pk) {
165
+ if (updateOption === false) return null;
166
+ const excluded = new Set([...conflict, ...(pk ? [pk] : [])]);
167
+ if (Array.isArray(updateOption)) {
168
+ for (const f of updateOption) {
169
+ if (!(f in model.fields)) throw new ValidationError(model.name, { update: [`"${f}" is not a field of "${model.name}"`] });
170
+ if (excluded.has(f)) throw new ValidationError(model.name, { update: [`"${f}" identifies the row (conflict key or primary key) and can't be updated by an upsert`] });
171
+ }
172
+ return updateOption.length > 0 ? [...updateOption] : null;
173
+ }
174
+ if (updateOption !== undefined) throw new ValidationError(model.name, { update: ["`update` must be an array of field names, or false"] });
175
+ // The id of an existing row is never rewritten: the primary key is left out even if passed.
176
+ const provided = new Set();
177
+ for (const row of rows) for (const f of row.provided) if (!excluded.has(f)) provided.add(f);
178
+ return provided.size > 0 ? [...provided] : null; // nothing to change -> behaves like `update: false`
179
+ }
180
+
181
+ const keyOf = (conflict, values) => JSON.stringify(conflict.map((f) => values[f] ?? null));
182
+
183
+ async function readByKeys(db, model, conflict, rows, readOptions, fieldTypeRegistry) {
184
+ const columns = conflict.map((f) => model.columns[f]);
185
+ const found = [];
186
+ for (const chunk of chunkArray(rows, 1000)) {
187
+ const query =
188
+ columns.length === 1
189
+ ? db(model.tableName).whereIn(columns[0], chunk.map((r) => storageValue(r.values, conflict[0])))
190
+ : db(model.tableName).whereIn(columns, chunk.map((r) => conflict.map((f) => storageValue(r.values, f))));
191
+ for (const row of await query) found.push(fromRow(model, row, fieldTypeRegistry, readOptions));
192
+ }
193
+ return found;
194
+
195
+ function storageValue(values, field) {
196
+ return serializeJsonFields(model, { [field]: values[field] }, fieldTypeRegistry)[field];
197
+ }
198
+ }
199
+
200
+ async function existingKeys(db, model, conflict, rows, readOptions, fieldTypeRegistry) {
201
+ const records = await readByKeys(db, model, conflict, rows, readOptions, fieldTypeRegistry);
202
+ return new Set(records.map((record) => keyOf(conflict, record)));
203
+ }
@@ -0,0 +1,71 @@
1
+ import { castValue } from "../fields/cast-value.js";
2
+ import { toStorage } from "../fields/storage.js";
3
+ import { ValidationError } from "./errors.js";
4
+
5
+ /**
6
+ * Values computed by the database at write time (since 0.2.0), for updates that must not lose
7
+ * concurrent changes:
8
+ *
9
+ * await Post.updateMany({ id }, { views: Value.increment(1) }); // views = views + 1
10
+ * await Account.updateMany({ id }, { balance: Value.decrement("12.50") }); // a decimal field
11
+ *
12
+ * Reading a value, changing it in JavaScript and saving it back loses an update when two requests
13
+ * do it at once: both read 10, both write 11. `Value.increment` sends `SET views = views + 1`, so
14
+ * the database applies each change to whatever the row holds at that moment.
15
+ *
16
+ * Works on integer, float and decimal fields, in updateMany() (and inside transactions); the
17
+ * amount is validated as a value of the field (a decimal amount keeps its exactness).
18
+ */
19
+ export class ValueExpression {
20
+ constructor(kind, amount) {
21
+ this.kind = kind;
22
+ this.amount = amount;
23
+ }
24
+ }
25
+
26
+ export const Value = Object.freeze({
27
+ /** `field = field + amount` (amount defaults to 1). */
28
+ increment: (amount = 1) => new ValueExpression("increment", amount),
29
+ /** `field = field - amount` (amount defaults to 1). */
30
+ decrement: (amount = 1) => new ValueExpression("decrement", amount),
31
+ });
32
+
33
+ const NUMERIC = new Set(["integer", "float", "decimal"]);
34
+
35
+ /**
36
+ * Splits update data into plain values and database expressions. Returns the plain part, plus a
37
+ * function that turns the expressions into Knex raw SET values for a given connection.
38
+ */
39
+ export function splitValueExpressions(model, data, fieldTypeRegistry) {
40
+ const plain = {};
41
+ const expressions = [];
42
+ const errors = {};
43
+ for (const [fieldName, value] of Object.entries(data)) {
44
+ if (!(value instanceof ValueExpression)) {
45
+ plain[fieldName] = value;
46
+ continue;
47
+ }
48
+ const field = model.fields[fieldName];
49
+ if (!field) {
50
+ errors[fieldName] = [`unknown field "${fieldName}" on model "${model.name}"`];
51
+ continue;
52
+ }
53
+ if (!NUMERIC.has(field.type)) {
54
+ errors[fieldName] = [`Value.${value.kind}() needs an integer, float or decimal field; "${fieldName}" is ${field.type}`];
55
+ continue;
56
+ }
57
+ let amount;
58
+ try {
59
+ amount = castValue(field, value.amount, fieldTypeRegistry);
60
+ const typeErrors = field.type === "decimal" ? [] : fieldTypeRegistry.get(field.type).validate({ type: field.type }, amount);
61
+ if (typeErrors.length) throw new Error(typeErrors.join("; "));
62
+ } catch (error) {
63
+ errors[fieldName] = [`Value.${value.kind}(): ${error.message}`];
64
+ continue;
65
+ }
66
+ expressions.push({ column: model.columns[fieldName], operator: value.kind === "increment" ? "+" : "-", amount: toStorage(field, amount, fieldTypeRegistry) });
67
+ }
68
+ if (Object.keys(errors).length > 0) throw new ValidationError(model.name, errors);
69
+ const toSet = (db) => Object.fromEntries(expressions.map((e) => [e.column, db.raw(`?? ${e.operator} ?`, [e.column, e.amount])]));
70
+ return { plain, hasExpressions: expressions.length > 0, toSet, expressions };
71
+ }
@@ -1,2 +1,2 @@
1
1
  export { DATE_BUCKETS, dateBucketSql, parseBucket } from "./date-bucket.js";
2
- export { guardTransactions, TransactionDeadlockError } from "./transaction-guard.js";
2
+ export { instrumentConnection, guardTransactions, TransactionDeadlockError } from "./transaction-guard.js";