@kiri-orm/core 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +27 -15
  2. package/dist/types/client/model-handle.d.ts +4 -1
  3. package/dist/types/connection.d.ts +66 -0
  4. package/dist/types/crud/chunk.d.ts +10 -0
  5. package/dist/types/crud/database-errors.d.ts +61 -0
  6. package/dist/types/crud/errors.d.ts +10 -0
  7. package/dist/types/crud/fast-path.d.ts +73 -0
  8. package/dist/types/crud/index.d.ts +4 -1
  9. package/dist/types/crud/insert-many.d.ts +12 -13
  10. package/dist/types/crud/order.d.ts +28 -0
  11. package/dist/types/crud/repository.d.ts +5 -3
  12. package/dist/types/crud/row-mapping.d.ts +9 -1
  13. package/dist/types/crud/upsert.d.ts +39 -0
  14. package/dist/types/crud/value.d.ts +39 -0
  15. package/dist/types/dialect/date-bucket.d.ts +2 -2
  16. package/dist/types/dialect/index.d.ts +1 -0
  17. package/dist/types/dialect/transaction-guard.d.ts +31 -0
  18. package/dist/types/domain/compile.d.ts +17 -0
  19. package/dist/types/fields/filter-value.d.ts +21 -0
  20. package/dist/types/fields/registry.d.ts +1 -0
  21. package/dist/types/fields/storage.d.ts +28 -0
  22. package/dist/types/fields/types/date.d.ts +6 -6
  23. package/dist/types/fields/types/decimal.d.ts +40 -0
  24. package/dist/types/global/errors.d.ts +3 -0
  25. package/dist/types/global/index.d.ts +2 -0
  26. package/dist/types/global/normalize-dates.d.ts +11 -0
  27. package/dist/types/global/state.d.ts +2 -0
  28. package/dist/types/global/transaction.d.ts +10 -13
  29. package/dist/types/index.d.ts +2 -0
  30. package/dist/types/meta/create-table-once.d.ts +15 -0
  31. package/dist/types/meta/snapshot.d.ts +10 -0
  32. package/dist/types/meta/upsert.d.ts +16 -0
  33. package/dist/types/migrations/diff.d.ts +25 -2
  34. package/dist/types/models/constraints.d.ts +27 -0
  35. package/dist/types/relations/pivot-schema.d.ts +1 -1
  36. package/dist/types/schema/alter-column.d.ts +46 -0
  37. package/dist/types/schema/build-column.d.ts +11 -0
  38. package/dist/types/schema/index.d.ts +1 -0
  39. package/dist/types/schema/introspect-indexes.d.ts +9 -0
  40. package/dist/types/schema/normalize-dates.d.ts +41 -0
  41. package/dist/types/transaction/after-commit.d.ts +42 -0
  42. package/dist/types/transaction/context.d.ts +39 -0
  43. package/dist/types/uow/entity.d.ts +39 -29
  44. package/dist/types/uow/hooks.d.ts +6 -1
  45. package/dist/types/uow/lifecycle.d.ts +82 -0
  46. package/dist/types/uow/unit-of-work.d.ts +11 -7
  47. package/package.json +8 -5
  48. package/src/client/model-handle.js +14 -4
  49. package/src/client/orm-client.js +10 -5
  50. package/src/connection.js +53 -7
  51. package/src/crud/aggregate-filter.js +8 -2
  52. package/src/crud/aggregate-spec.js +2 -2
  53. package/src/crud/aggregate.js +16 -5
  54. package/src/crud/chunk.js +10 -0
  55. package/src/crud/create-many.js +52 -29
  56. package/src/crud/database-errors.js +107 -0
  57. package/src/crud/errors.js +14 -0
  58. package/src/crud/fast-path.js +449 -0
  59. package/src/crud/index.js +4 -1
  60. package/src/crud/insert-many.js +42 -7
  61. package/src/crud/map-filter.js +2 -1
  62. package/src/crud/order.js +59 -9
  63. package/src/crud/repository.js +106 -38
  64. package/src/crud/row-mapping.js +32 -7
  65. package/src/crud/upsert.js +203 -0
  66. package/src/crud/value.js +71 -0
  67. package/src/dialect/index.js +1 -0
  68. package/src/dialect/transaction-guard.js +254 -0
  69. package/src/domain/compile.js +85 -12
  70. package/src/dto/field-schema.js +5 -0
  71. package/src/fields/default-registry.js +3 -1
  72. package/src/fields/filter-value.js +87 -0
  73. package/src/fields/registry.js +1 -0
  74. package/src/fields/storage.js +50 -0
  75. package/src/fields/types/date.js +16 -3
  76. package/src/fields/types/decimal.js +147 -0
  77. package/src/fields/types/integer.js +7 -0
  78. package/src/global/connect.js +25 -1
  79. package/src/global/create-model.js +59 -57
  80. package/src/global/errors.js +1 -1
  81. package/src/global/index.js +2 -0
  82. package/src/global/normalize-dates.js +15 -0
  83. package/src/global/state.js +3 -0
  84. package/src/global/transaction.js +12 -14
  85. package/src/index.js +2 -0
  86. package/src/meta/create-table-once.js +23 -0
  87. package/src/meta/schema.js +15 -6
  88. package/src/meta/snapshot.js +5 -0
  89. package/src/meta/upsert.js +28 -0
  90. package/src/migrations/describe.js +49 -0
  91. package/src/migrations/diff.js +50 -7
  92. package/src/migrations/generate.js +38 -2
  93. package/src/migrations/render.js +30 -12
  94. package/src/migrations/runner.js +40 -6
  95. package/src/models/constraints.js +96 -0
  96. package/src/models/define-model.js +4 -0
  97. package/src/models/inheritance.js +4 -1
  98. package/src/models/registry.js +2 -1
  99. package/src/relations/attach-detach.js +49 -18
  100. package/src/relations/cascade-delete.js +32 -7
  101. package/src/relations/eager-load.js +75 -51
  102. package/src/relations/pivot-schema.js +24 -3
  103. package/src/reports/report-handle.js +2 -1
  104. package/src/schema/alter-column.js +219 -0
  105. package/src/schema/build-column.js +28 -2
  106. package/src/schema/default-column-builders.js +16 -2
  107. package/src/schema/index.js +1 -0
  108. package/src/schema/introspect-indexes.js +22 -0
  109. package/src/schema/normalize-dates.js +58 -0
  110. package/src/schema/sync.js +16 -2
  111. package/src/transaction/after-commit.js +142 -0
  112. package/src/transaction/context.js +84 -0
  113. package/src/uow/entity.js +133 -133
  114. package/src/uow/hooks.js +9 -0
  115. package/src/uow/lifecycle.js +162 -0
  116. package/src/uow/unit-of-work.js +55 -60
  117. package/src/uow/with-unit-of-work.js +2 -1
@@ -1,6 +1,7 @@
1
1
  import { castValue } from "../fields/cast-value.js";
2
2
  import { defaultFieldTypeRegistry } from "../fields/default-registry.js";
3
3
  import { ValidationError } from "./errors.js";
4
+ import { filterValue } from "../fields/filter-value.js";
4
5
 
5
6
  /**
6
7
  * Converts a `{ fieldName: value }` equality filter into a
@@ -31,7 +32,7 @@ export function mapFilterToColumns(model, filter, fieldTypeRegistry = defaultFie
31
32
  }
32
33
  const columnName = model.columns[fieldName];
33
34
  columnFilter[columnName] =
34
- value === null || value === undefined ? value : castValue(field, value, fieldTypeRegistry);
35
+ value === null || value === undefined ? value : filterValue(field, "=", value, fieldTypeRegistry);
35
36
  }
36
37
 
37
38
  return columnFilter;
package/src/crud/order.js CHANGED
@@ -54,6 +54,7 @@ export function parseOrderBy(orderBy, fail) {
54
54
  for (const item of items) {
55
55
  let field;
56
56
  let direction = "asc";
57
+ let nulls;
57
58
 
58
59
  if (typeof item === "string") {
59
60
  field = item;
@@ -62,10 +63,11 @@ export function parseOrderBy(orderBy, fail) {
62
63
  direction = "desc";
63
64
  }
64
65
  } else if (Array.isArray(item)) {
65
- [field, direction = "asc"] = item;
66
+ [field, direction = "asc", nulls] = item;
66
67
  } else if (item && typeof item === "object") {
67
68
  field = item.field;
68
69
  direction = item.direction ?? "asc";
70
+ nulls = item.nulls;
69
71
  } else {
70
72
  fail(`orderBy entries must be a field name, [field, direction] or { field, direction } (got ${JSON.stringify(item)})`);
71
73
  }
@@ -80,7 +82,15 @@ export function parseOrderBy(orderBy, fail) {
80
82
  if (result.some((entry) => entry.field === field)) {
81
83
  fail(`orderBy lists "${field}" more than once`);
82
84
  }
83
- result.push({ field, direction });
85
+ if (nulls !== undefined && nulls !== "first" && nulls !== "last") {
86
+ fail(`orderBy nulls must be "first" or "last" (got ${JSON.stringify(nulls)})`);
87
+ }
88
+ // NULLs sort where the database puts them unless `nulls` says otherwise: Postgres last
89
+ // ascending / first descending, SQLite the reverse. A fixed rule would be the non-native one
90
+ // on one of the two, and that order can't be read from an index: on SQLite a sorted, LIMITed
91
+ // read of a nullable indexed column became a full sort (63x slower in a load test). So
92
+ // consistency is opt-in (since 0.2.0): ["dueAt", "asc", "last"].
93
+ result.push(nulls === undefined ? { field, direction } : { field, direction, nulls });
84
94
  }
85
95
  return result;
86
96
  }
@@ -106,6 +116,22 @@ export function validatePaging(model, { limit, offset }) {
106
116
  }
107
117
  }
108
118
 
119
+ /**
120
+ * The validated sort keys of a find(), with the primary key appended as the final tie-breaker
121
+ * whenever the caller orders or skips rows (see applyOrderAndPaging()). Validates limit/offset too.
122
+ *
123
+ * @returns {Array<{ field: string, direction: "asc"|"desc", nulls?: "first"|"last" }>}
124
+ */
125
+ export function resolveOrder(model, { orderBy, limit, offset }) {
126
+ validatePaging(model, { limit, offset });
127
+ const order = normalizeOrderBy(model, orderBy);
128
+ const key = primaryKeyOf(model);
129
+ if ((order.length > 0 || offset !== undefined) && key !== null && !order.some((entry) => entry.field === key)) {
130
+ order.push({ field: key, direction: "asc" });
131
+ }
132
+ return order;
133
+ }
134
+
109
135
  /**
110
136
  * Applies ordering and paging to a Knex query builder.
111
137
  *
@@ -117,16 +143,40 @@ export function validatePaging(model, { limit, offset }) {
117
143
  * @returns {import('knex').Knex.QueryBuilder}
118
144
  */
119
145
  export function applyOrderAndPaging(query, model, { orderBy, limit, offset }) {
120
- validatePaging(model, { limit, offset });
121
- const order = normalizeOrderBy(model, orderBy);
122
-
146
+ const order = resolveOrder(model, { orderBy, limit, offset });
123
147
  const key = primaryKeyOf(model);
124
- if ((order.length > 0 || offset !== undefined) && key !== null && !order.some((entry) => entry.field === key)) {
125
- order.push({ field: key, direction: "asc" });
126
- }
127
148
 
128
- for (const { field, direction } of order) query = query.orderBy(model.columns[field], direction);
149
+ // The primary key never holds NULL: no clause for it.
150
+ for (const { field, direction, nulls } of order) {
151
+ query = orderWithNulls(query, model.columns[field], direction, nullsClause(query, field === key ? null : model.fields[field], direction, nulls));
152
+ }
129
153
  if (limit !== undefined) query = query.limit(limit);
130
154
  if (offset !== undefined && offset > 0) query = query.offset(offset); // OFFSET 0 is a no-op; leave it out
131
155
  return query;
132
156
  }
157
+
158
+ /**
159
+ * The `nulls` argument for Knex's orderBy(), or undefined when the database already sorts NULLs that
160
+ * way, or the column can't hold any (required fields, primary keys). On SQLite Knex emulates it with
161
+ * an `(col is null)` sort key, which keeps SQLite from using an index for the ORDER BY - so it is
162
+ * only added where NULLs can actually appear.
163
+ */
164
+ export function nullsClause(query, field, direction, nulls) {
165
+ if (!nulls || !field || field.required || field.primaryKey) return undefined;
166
+ const client = String(query.client?.config?.client ?? "");
167
+ const databaseDefault = client.includes("sqlite") ? (direction === "asc" ? "first" : "last") : direction === "asc" ? "last" : "first";
168
+ return nulls === databaseDefault ? undefined : nulls;
169
+ }
170
+
171
+ /**
172
+ * query.orderBy(column, direction) with a NULLS FIRST/LAST rule. Not Knex's own `nulls` argument on
173
+ * SQLite: there Knex replaces the column's ordering with the `(col is null)` key alone, so rows come
174
+ * back sorted by nullness only. SQLite gets both keys explicitly; Postgres its native clause.
175
+ */
176
+ export function orderWithNulls(query, column, direction, nulls) {
177
+ if (!nulls) return query.orderBy(column, direction);
178
+ if (String(query.client?.config?.client ?? "").includes("sqlite")) {
179
+ return query.orderByRaw(`(?? IS NULL) ${nulls === "last" ? "ASC" : "DESC"}`, [column]).orderBy(column, direction);
180
+ }
181
+ return query.orderBy(column, direction, nulls);
182
+ }
@@ -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
+ }