@kiri-orm/core 0.1.7 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +27 -15
  2. package/dist/types/client/model-handle.d.ts +4 -1
  3. package/dist/types/connection.d.ts +39 -0
  4. package/dist/types/crud/database-errors.d.ts +61 -0
  5. package/dist/types/crud/errors.d.ts +10 -0
  6. package/dist/types/crud/fast-path.d.ts +73 -0
  7. package/dist/types/crud/index.d.ts +4 -1
  8. package/dist/types/crud/insert-many.d.ts +1 -1
  9. package/dist/types/crud/order.d.ts +28 -0
  10. package/dist/types/crud/repository.d.ts +5 -3
  11. package/dist/types/crud/upsert.d.ts +39 -0
  12. package/dist/types/crud/value.d.ts +39 -0
  13. package/dist/types/dialect/index.d.ts +1 -1
  14. package/dist/types/dialect/transaction-guard.d.ts +19 -18
  15. package/dist/types/domain/compile.d.ts +17 -0
  16. package/dist/types/fields/filter-value.d.ts +21 -0
  17. package/dist/types/fields/registry.d.ts +1 -0
  18. package/dist/types/fields/storage.d.ts +28 -0
  19. package/dist/types/fields/types/date.d.ts +5 -0
  20. package/dist/types/fields/types/decimal.d.ts +40 -0
  21. package/dist/types/global/index.d.ts +1 -0
  22. package/dist/types/global/transaction.d.ts +10 -13
  23. package/dist/types/index.d.ts +2 -0
  24. package/dist/types/meta/snapshot.d.ts +10 -0
  25. package/dist/types/meta/upsert.d.ts +16 -0
  26. package/dist/types/migrations/diff.d.ts +25 -2
  27. package/dist/types/models/constraints.d.ts +27 -0
  28. package/dist/types/schema/alter-column.d.ts +46 -0
  29. package/dist/types/schema/build-column.d.ts +11 -0
  30. package/dist/types/schema/introspect-indexes.d.ts +9 -0
  31. package/dist/types/transaction/after-commit.d.ts +42 -0
  32. package/dist/types/transaction/context.d.ts +39 -0
  33. package/dist/types/uow/entity.d.ts +39 -29
  34. package/dist/types/uow/hooks.d.ts +6 -1
  35. package/dist/types/uow/lifecycle.d.ts +82 -0
  36. package/dist/types/uow/unit-of-work.d.ts +11 -7
  37. package/package.json +5 -4
  38. package/src/client/model-handle.js +14 -4
  39. package/src/client/orm-client.js +10 -5
  40. package/src/connection.js +34 -4
  41. package/src/crud/aggregate-filter.js +8 -2
  42. package/src/crud/aggregate-spec.js +2 -2
  43. package/src/crud/aggregate.js +16 -5
  44. package/src/crud/create-many.js +52 -29
  45. package/src/crud/database-errors.js +107 -0
  46. package/src/crud/errors.js +14 -0
  47. package/src/crud/fast-path.js +449 -0
  48. package/src/crud/index.js +4 -1
  49. package/src/crud/insert-many.js +25 -7
  50. package/src/crud/map-filter.js +2 -1
  51. package/src/crud/order.js +59 -9
  52. package/src/crud/repository.js +106 -38
  53. package/src/crud/row-mapping.js +32 -7
  54. package/src/crud/upsert.js +203 -0
  55. package/src/crud/value.js +71 -0
  56. package/src/dialect/index.js +1 -1
  57. package/src/dialect/transaction-guard.js +216 -45
  58. package/src/domain/compile.js +85 -12
  59. package/src/dto/field-schema.js +5 -0
  60. package/src/fields/default-registry.js +3 -1
  61. package/src/fields/filter-value.js +87 -0
  62. package/src/fields/registry.js +1 -0
  63. package/src/fields/storage.js +50 -0
  64. package/src/fields/types/date.js +16 -3
  65. package/src/fields/types/decimal.js +147 -0
  66. package/src/fields/types/integer.js +7 -0
  67. package/src/global/connect.js +2 -2
  68. package/src/global/create-model.js +59 -57
  69. package/src/global/errors.js +1 -1
  70. package/src/global/index.js +1 -0
  71. package/src/global/transaction.js +12 -14
  72. package/src/index.js +2 -0
  73. package/src/meta/schema.js +10 -0
  74. package/src/meta/snapshot.js +5 -0
  75. package/src/meta/upsert.js +28 -0
  76. package/src/migrations/describe.js +49 -0
  77. package/src/migrations/diff.js +50 -7
  78. package/src/migrations/generate.js +38 -2
  79. package/src/migrations/render.js +30 -12
  80. package/src/migrations/runner.js +2 -1
  81. package/src/models/constraints.js +96 -0
  82. package/src/models/define-model.js +4 -0
  83. package/src/models/inheritance.js +4 -1
  84. package/src/models/registry.js +2 -1
  85. package/src/relations/cascade-delete.js +2 -1
  86. package/src/relations/eager-load.js +45 -40
  87. package/src/reports/report-handle.js +2 -1
  88. package/src/schema/alter-column.js +219 -0
  89. package/src/schema/build-column.js +28 -2
  90. package/src/schema/default-column-builders.js +16 -2
  91. package/src/schema/introspect-indexes.js +22 -0
  92. package/src/schema/sync.js +15 -1
  93. package/src/transaction/after-commit.js +142 -0
  94. package/src/transaction/context.js +84 -0
  95. package/src/uow/entity.js +133 -133
  96. package/src/uow/hooks.js +9 -0
  97. package/src/uow/lifecycle.js +162 -0
  98. package/src/uow/unit-of-work.js +44 -56
  99. package/src/uow/with-unit-of-work.js +2 -1
@@ -1,5 +1,7 @@
1
1
  import { listModelsMeta, getFieldsMeta } from "../meta/query.js";
2
2
  import { RELATION_TYPES } from "../relations/define-relation.js";
3
+ import { changedColumnOptions } from "../schema/alter-column.js";
4
+ import { constraintList, parseStoredConstraints } from "../meta/upsert.js";
3
5
 
4
6
  // Since Phase 7, relations are stored as rows in `_meta_fields` alongside
5
7
  // scalar fields (see meta/upsert.js). They aren't columns, so they must
@@ -47,7 +49,14 @@ async function getColumnFieldsMeta(db, modelName) {
47
49
  * (e.g. an explicit `column` option was added/changed). Not a
48
50
  * heuristic guess, same reasoning as renameModels above.
49
51
  * @property {Object[]} typeChanges - { fieldName, from, to } - flagged
50
- * but never auto-migrated (see generateMigration).
52
+ * but never auto-migrated (see generateMigration). A decimal's precision or scale counts as
53
+ * its type ("decimal(12,2)" -> "decimal(12,4)"): on SQLite the stored integers would need rescaling.
54
+ * @property {Object[]} optionChanges - { fieldName, column, changes, from, to } (since 0.2.0): the
55
+ * column options that changed (required, unique, index, default, maxLength, enum values), with
56
+ * the recorded and current descriptors; applied with alterColumn() (schema/alter-column.js).
57
+ * @property {Object[]} addConstraints - model constraints (constraints: { unique, index }) not
58
+ * recorded yet: { kind, name, fields, columns } (since 0.2.0)
59
+ * @property {Object[]} dropConstraints - recorded ones the model no longer declares, same shape
51
60
  * @property {{removed: string[], added: string[]}|null} possibleFieldRenames -
52
61
  * advisory only, same rationale as possibleModelRenames but at the
53
62
  * field level (e.g. `customerId` renamed to `clientId` in code).
@@ -157,7 +166,8 @@ export async function diffSchema(db, modelRegistry, options = {}) {
157
166
  }
158
167
  // the models this one holds foreign keys to, so it can be dropped before them
159
168
  const references = allRows.filter((row) => row.type === "belongsTo").map((row) => parseFieldOptions(row.options).model);
160
- dropModels.push({ modelName, tableName: previousRow.table_name, fields, columns, references });
169
+ const constraints = parseStoredConstraints(previousRow.constraints);
170
+ dropModels.push({ modelName, tableName: previousRow.table_name, fields, columns, references, constraints });
161
171
  }
162
172
  // With real foreign keys a table can't be dropped while another still points at it:
163
173
  // drop the referencing (child) tables first.
@@ -220,24 +230,50 @@ export async function diffSchema(db, modelRegistry, options = {}) {
220
230
 
221
231
  const columnRenames = [];
222
232
  const typeChanges = [];
233
+ const optionChanges = [];
234
+ const compareField = (previousRow, fieldName) => {
235
+ const field = model.fields[fieldName];
236
+ const previous = parseFieldOptions(previousRow.options) ?? {};
237
+ const typeName = (f, type) => (type === "decimal" ? `decimal(${f.precision ?? 15},${f.scale ?? 2})` : type);
238
+ const from = typeName(previous, previousRow.type);
239
+ const to = typeName(field, field.type);
240
+ if (from !== to) {
241
+ typeChanges.push({ fieldName, from, to });
242
+ return;
243
+ }
244
+ if (isPrimary(field, model.columns[fieldName]) || isPrimary(previous, previousRow.column)) return;
245
+ const changes = changedColumnOptions(previous, field);
246
+ if (changes.length > 0) optionChanges.push({ fieldName, column: model.columns[fieldName], changes, from: previous, to: field });
247
+ };
223
248
  for (const row of previousFieldRows) {
224
249
  if (!currentFieldNames.has(row.name)) continue;
225
- const field = model.fields[row.name];
226
250
  const currentColumn = model.columns[row.name];
227
251
  if (currentColumn !== row.column) {
228
252
  columnRenames.push({ fieldName: row.name, fromColumn: row.column, toColumn: currentColumn });
229
253
  }
230
- if (field.type !== row.type) {
231
- typeChanges.push({ fieldName: row.name, from: row.type, to: field.type });
232
- }
254
+ compareField(row, row.name);
255
+ }
256
+ for (const rename of renameFields) {
257
+ compareField(previousFieldRows.find((r) => r.name === rename.from), rename.to);
233
258
  }
234
259
 
260
+ // Multi-field constraints, by name: a renamed table or column gives a new name, so the old
261
+ // index is dropped and the new one added.
262
+ const previousModelRow = previousModelRows.find((r) => r.name === sourceMetaName);
263
+ const recorded = parseStoredConstraints(previousModelRow?.constraints);
264
+ const current = constraintList(model.constraints);
265
+ const addConstraints = current.filter((c) => !recorded.some((r) => r.name === c.name));
266
+ const dropConstraints = recorded.filter((r) => !current.some((c) => c.name === r.name));
267
+
235
268
  const hasChanges =
236
269
  addFields.length ||
237
270
  dropFields.length ||
238
271
  renameFields.length ||
239
272
  columnRenames.length ||
240
- typeChanges.length;
273
+ typeChanges.length ||
274
+ optionChanges.length ||
275
+ addConstraints.length ||
276
+ dropConstraints.length;
241
277
 
242
278
  if (hasChanges) {
243
279
  fieldChanges[modelName] = {
@@ -246,6 +282,9 @@ export async function diffSchema(db, modelRegistry, options = {}) {
246
282
  renameFields,
247
283
  columnRenames,
248
284
  typeChanges,
285
+ optionChanges,
286
+ addConstraints,
287
+ dropConstraints,
249
288
  possibleFieldRenames,
250
289
  };
251
290
  }
@@ -260,6 +299,10 @@ export async function diffSchema(db, modelRegistry, options = {}) {
260
299
  };
261
300
  }
262
301
 
302
+ function isPrimary(field, columnName) {
303
+ return field.primary === undefined ? columnName === "id" : field.primary === true;
304
+ }
305
+
263
306
  function parseFieldOptions(options) {
264
307
  return typeof options === "string" ? JSON.parse(options) : options;
265
308
  }
@@ -1,6 +1,9 @@
1
1
  import { defaultColumnBuilderRegistry } from "../schema/default-column-builders.js";
2
2
  import { buildColumn } from "../schema/build-column.js";
3
3
  import { addForeignKey } from "../schema/foreign-keys.js";
4
+ import { alterColumn } from "../schema/alter-column.js";
5
+ import { addConstraint, dropConstraint } from "../models/constraints.js";
6
+ import { constraintList } from "../meta/upsert.js";
4
7
  import { planMigrationForeignKeys } from "./foreign-keys-plan.js";
5
8
  import { MigrationSafetyError } from "./errors.js";
6
9
  import { describePlan } from "./describe.js";
@@ -82,6 +85,7 @@ export function generateMigration(plan, modelRegistry, options = {}) {
82
85
  buildColumn(table, model.columns[fieldName], field, columnBuilderRegistry);
83
86
  }
84
87
  for (const fk of keys.creation.inline.get(model.name)) addForeignKey(table, fk);
88
+ for (const c of constraintList(model.constraints)) addConstraint(table, c);
85
89
  });
86
90
  }
87
91
  for (const { model, fk } of keys.creation.deferred) {
@@ -90,7 +94,7 @@ export function generateMigration(plan, modelRegistry, options = {}) {
90
94
 
91
95
  for (const [modelName, changes] of Object.entries(plan.fieldChanges)) {
92
96
  const model = modelRegistry.getModel(modelName);
93
- await db.schema.alterTable(model.tableName, (table) => {
97
+ if (hasColumnChanges(changes, keys.added[modelName])) await db.schema.alterTable(model.tableName, (table) => {
94
98
  for (const rename of changes.renameFields) {
95
99
  table.renameColumn(rename.fromColumn, rename.toColumn);
96
100
  }
@@ -105,6 +109,7 @@ export function generateMigration(plan, modelRegistry, options = {}) {
105
109
  table.dropColumn(drop.columnName);
106
110
  }
107
111
  });
112
+ await applyOptionChanges(db, model.tableName, changes, "up", columnBuilderRegistry);
108
113
  }
109
114
 
110
115
  for (const drop of plan.dropModels) {
@@ -118,12 +123,14 @@ export function generateMigration(plan, modelRegistry, options = {}) {
118
123
  for (const [fieldName, field] of Object.entries(drop.fields)) {
119
124
  buildColumn(table, drop.columns[fieldName], field, columnBuilderRegistry);
120
125
  }
126
+ for (const c of drop.constraints ?? []) addConstraint(table, c);
121
127
  });
122
128
  }
123
129
 
124
130
  for (const [modelName, changes] of Object.entries(plan.fieldChanges).reverse()) {
125
131
  const model = modelRegistry.getModel(modelName);
126
- await db.schema.alterTable(model.tableName, (table) => {
132
+ await applyOptionChanges(db, model.tableName, changes, "down", columnBuilderRegistry);
133
+ if (hasColumnChanges(changes, keys.added[modelName])) await db.schema.alterTable(model.tableName, (table) => {
127
134
  for (const drop of changes.dropFields) {
128
135
  buildColumn(table, drop.columnName, drop.field, columnBuilderRegistry);
129
136
  }
@@ -155,6 +162,35 @@ export function generateMigration(plan, modelRegistry, options = {}) {
155
162
  return { up, down, summary: describePlan(plan) };
156
163
  }
157
164
 
165
+ function hasColumnChanges(changes, addedKeys) {
166
+ return (
167
+ changes.renameFields.length > 0 ||
168
+ changes.columnRenames.length > 0 ||
169
+ changes.addFields.length > 0 ||
170
+ changes.dropFields.length > 0 ||
171
+ (addedKeys ?? []).length > 0
172
+ );
173
+ }
174
+
175
+ /**
176
+ * Since 0.2.0: column option changes and model constraints, after the columns themselves exist
177
+ * (up) / before they're renamed back (down). Constraints that went away are dropped first, so a
178
+ * column they cover can be rebuilt; new ones are added last, once the columns have their final form.
179
+ */
180
+ async function applyOptionChanges(db, tableName, changes, direction, columnBuilderRegistry) {
181
+ const options = changes.optionChanges ?? [];
182
+ const added = changes.addConstraints ?? [];
183
+ const dropped = changes.dropConstraints ?? [];
184
+ const [first, last] = direction === "up" ? [dropped, added] : [added, dropped];
185
+ if (first.length > 0) await db.schema.alterTable(tableName, (table) => first.forEach((c) => dropConstraint(table, c)));
186
+ const ordered = direction === "up" ? options : [...options].reverse();
187
+ for (const change of ordered) {
188
+ const [from, to] = direction === "up" ? [change.from, change.to] : [change.to, change.from];
189
+ await alterColumn(db, tableName, change.column, from, to, columnBuilderRegistry);
190
+ }
191
+ if (last.length > 0) await db.schema.alterTable(tableName, (table) => last.forEach((c) => addConstraint(table, c)));
192
+ }
193
+
158
194
  function describeDestructive(plan) {
159
195
  const lines = [];
160
196
  for (const drop of plan.dropModels) {
@@ -1,10 +1,15 @@
1
1
  import { generateMigration } from "./generate.js";
2
+ import { constraintList } from "../meta/upsert.js";
2
3
  import {
3
4
  planMigrationForeignKeys,
4
5
  renderForeignKey,
5
6
  } from "./foreign-keys-plan.js";
6
7
 
7
8
  const json = (value) => JSON.stringify(value);
9
+ const addConstraintLine = (c) =>
10
+ c.kind === "unique" ? `table.unique(${json(c.columns)}, { indexName: ${json(c.name)} });` : `table.index(${json(c.columns)}, ${json(c.name)});`;
11
+ const dropConstraintLine = (c) =>
12
+ c.kind === "unique" ? `table.dropUnique(${json(c.columns)}, ${json(c.name)});` : `table.dropIndex(${json(c.columns)}, ${json(c.name)});`;
8
13
  const indent = (text, spaces) =>
9
14
  text
10
15
  .split("\n")
@@ -54,7 +59,7 @@ export function renderMigrationSource(plan, modelRegistry, options = {}) {
54
59
  });
55
60
 
56
61
  const keys = planMigrationForeignKeys(plan, modelRegistry);
57
- const createTable = (tableName, entries, foreignKeys = []) => {
62
+ const createTable = (tableName, entries, foreignKeys = [], constraints = []) => {
58
63
  const columns = entries.map(
59
64
  ([column, field]) =>
60
65
  ` buildColumn(table, ${json(column)}, ${json(field)}, columnBuilderRegistry);`,
@@ -63,9 +68,25 @@ export function renderMigrationSource(plan, modelRegistry, options = {}) {
63
68
  `await db.schema.createTable(${json(tableName)}, (table) => {`,
64
69
  ...columns,
65
70
  ...foreignKeys.map((fk) => ` ${renderForeignKey(fk)}`),
71
+ ...constraints.map((c) => ` ${addConstraintLine(c)}`),
66
72
  `});`,
67
73
  ];
68
74
  };
75
+ // Since 0.2.0: option changes go through the alterColumn helper; constraints that went away are
76
+ // dropped before it, new ones added after (see generate.js applyOptionChanges).
77
+ const optionLines = (tableName, changes, direction) => {
78
+ const lines = [];
79
+ const options = changes.optionChanges ?? [];
80
+ const [first, last] = direction === "up" ? [changes.dropConstraints ?? [], changes.addConstraints ?? []] : [changes.addConstraints ?? [], changes.dropConstraints ?? []];
81
+ if (first.length > 0) lines.push(...alterWith(tableName, first.map(dropConstraintLine)));
82
+ for (const change of direction === "up" ? options : [...options].reverse()) {
83
+ const [from, to] = direction === "up" ? [change.from, change.to] : [change.to, change.from];
84
+ lines.push(`// ${change.fieldName}: ${change.changes.join(", ")}`);
85
+ lines.push(`await alterColumn(db, ${json(tableName)}, ${json(change.column)}, ${json(from)}, ${json(to)}, columnBuilderRegistry);`);
86
+ }
87
+ if (last.length > 0) lines.push(...alterWith(tableName, last.map(addConstraintLine)));
88
+ return lines;
89
+ };
69
90
  const alterWith = (tableName, lines) => [
70
91
  `await db.schema.alterTable(${json(tableName)}, (table) => {`,
71
92
  ...lines.map((l) => ` ${l}`),
@@ -90,6 +111,7 @@ export function renderMigrationSource(plan, modelRegistry, options = {}) {
90
111
  model.tableName,
91
112
  modelEntries(model),
92
113
  keys.creation.inline.get(model.name),
114
+ constraintList(model.constraints),
93
115
  ),
94
116
  );
95
117
  }
@@ -112,11 +134,8 @@ export function renderMigrationSource(plan, modelRegistry, options = {}) {
112
134
  body.push(renderForeignKey(fk));
113
135
  for (const drop of changes.dropFields)
114
136
  body.push(`table.dropColumn(${json(drop.columnName)});`);
115
- up.push(
116
- `await db.schema.alterTable(${json(model.tableName)}, (table) => {`,
117
- ...body.map((l) => ` ${l}`),
118
- `});`,
119
- );
137
+ if (body.length > 0) up.push(...alterWith(model.tableName, body));
138
+ up.push(...optionLines(model.tableName, changes, "up"));
120
139
  }
121
140
  for (const drop of plan.dropModels)
122
141
  up.push(`await db.schema.dropTable(${json(drop.tableName)});`);
@@ -130,6 +149,8 @@ export function renderMigrationSource(plan, modelRegistry, options = {}) {
130
149
  drop.columns[f],
131
150
  field,
132
151
  ]),
152
+ [],
153
+ drop.constraints ?? [],
133
154
  ),
134
155
  );
135
156
  }
@@ -137,6 +158,7 @@ export function renderMigrationSource(plan, modelRegistry, options = {}) {
137
158
  plan.fieldChanges,
138
159
  ).reverse()) {
139
160
  const model = modelRegistry.getModel(modelName);
161
+ down.push(...optionLines(model.tableName, changes, "down"));
140
162
  const body = [];
141
163
  for (const drop of changes.dropFields) {
142
164
  body.push(
@@ -152,11 +174,7 @@ export function renderMigrationSource(plan, modelRegistry, options = {}) {
152
174
  `table.renameColumn(${json(rename.toColumn)}, ${json(rename.fromColumn)});`,
153
175
  );
154
176
  }
155
- down.push(
156
- `await db.schema.alterTable(${json(model.tableName)}, (table) => {`,
157
- ...body.map((l) => ` ${l}`),
158
- `});`,
159
- );
177
+ if (body.length > 0) down.push(...alterWith(model.tableName, body));
160
178
  }
161
179
  for (const { model, fk } of [...keys.creation.deferred].reverse())
162
180
  down.push(
@@ -173,7 +191,7 @@ export function renderMigrationSource(plan, modelRegistry, options = {}) {
173
191
 
174
192
  const fn = (name, lines) =>
175
193
  [
176
- `export async function ${name}(db, { buildColumn, columnBuilderRegistry }) {`,
194
+ `export async function ${name}(db, { buildColumn, alterColumn, columnBuilderRegistry }) {`,
177
195
  indent(lines.join("\n"), 2),
178
196
  `}`,
179
197
  ].join("\n");
@@ -6,6 +6,7 @@ import { ensureMetaTables } from "../meta/schema.js";
6
6
  import { listModelsMeta } from "../meta/query.js";
7
7
  import { syncMeta } from "../meta/sync-meta.js";
8
8
  import { snapshotModelMeta, restoreModelMeta } from "../meta/snapshot.js";
9
+ import { alterColumn } from "../schema/alter-column.js";
9
10
  import { buildColumn } from "../schema/build-column.js";
10
11
  import { defaultColumnBuilderRegistry } from "../schema/default-column-builders.js";
11
12
  import { ensurePivotTables } from "../relations/pivot-schema.js";
@@ -91,7 +92,7 @@ export async function getMigrationStatus(db, dir) {
91
92
  }
92
93
 
93
94
  function helpers(options) {
94
- return { buildColumn, columnBuilderRegistry: options.columnBuilderRegistry ?? defaultColumnBuilderRegistry };
95
+ return { buildColumn, alterColumn, columnBuilderRegistry: options.columnBuilderRegistry ?? defaultColumnBuilderRegistry };
95
96
  }
96
97
 
97
98
  /**
@@ -0,0 +1,96 @@
1
+ import { InvalidModelDefinitionError } from "./errors.js";
2
+
3
+ /**
4
+ * Constraints across several fields (since 0.2.0), declared on the model:
5
+ *
6
+ * constraints: {
7
+ * unique: [["orgId", "email"]], // email unique per organisation
8
+ * index: [["status", "createdAt"]], // a composite index for a common filter + sort
9
+ * }
10
+ *
11
+ * A single-field unique/index stays a field option (`unique: true`, `index: true`).
12
+ * Each entry gets a stable, readable name - `<table>_<columns>_unique` / `_index` - which sync()
13
+ * and migrations use to tell whether it already exists. Postgres limits names to 63 bytes, so a
14
+ * longer one is cut and given a short hash of the full name.
15
+ *
16
+ * @typedef {{ fields: string[], columns: string[], name: string }} ModelConstraint
17
+ * @typedef {{ unique: ModelConstraint[], index: ModelConstraint[] }} ModelConstraints
18
+ */
19
+
20
+ const KINDS = ["unique", "index"];
21
+
22
+ /** @returns {ModelConstraints} */
23
+ export function defineConstraints(modelName, tableName, input, fields, columns) {
24
+ const result = { unique: [], index: [] };
25
+ if (input === undefined) return result;
26
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
27
+ throw new InvalidModelDefinitionError(`Model "${modelName}" \`constraints\` must be an object like { unique: [["a", "b"]] }`);
28
+ }
29
+ for (const key of Object.keys(input)) {
30
+ if (!KINDS.includes(key)) {
31
+ throw new InvalidModelDefinitionError(`Model "${modelName}" \`constraints.${key}\` is not supported (use: ${KINDS.join(", ")})`);
32
+ }
33
+ }
34
+ for (const kind of KINDS) {
35
+ const entries = input[kind] ?? [];
36
+ if (!Array.isArray(entries)) {
37
+ throw new InvalidModelDefinitionError(`Model "${modelName}" \`constraints.${kind}\` must be an array of field lists, e.g. [["orgId", "email"]]`);
38
+ }
39
+ const seen = new Set();
40
+ for (const entry of entries) {
41
+ if (!Array.isArray(entry) || entry.length === 0 || entry.some((f) => typeof f !== "string")) {
42
+ throw new InvalidModelDefinitionError(`Model "${modelName}" \`constraints.${kind}\`: each entry must be a non-empty array of field names, got ${JSON.stringify(entry)}`);
43
+ }
44
+ for (const fieldName of entry) {
45
+ if (!(fieldName in fields)) {
46
+ throw new InvalidModelDefinitionError(
47
+ `Model "${modelName}" \`constraints.${kind}\` names "${fieldName}", which is not a stored field. Known fields: ${Object.keys(fields).join(", ")}`
48
+ );
49
+ }
50
+ }
51
+ if (new Set(entry).size !== entry.length) {
52
+ throw new InvalidModelDefinitionError(`Model "${modelName}" \`constraints.${kind}\` lists a field twice: ${JSON.stringify(entry)}`);
53
+ }
54
+ const key = entry.join(",");
55
+ if (seen.has(key)) continue; // the same constraint from a mixin and the model: one is enough
56
+ seen.add(key);
57
+ const cols = entry.map((f) => columns[f]);
58
+ result[kind].push(Object.freeze({ fields: Object.freeze([...entry]), columns: Object.freeze(cols), name: constraintName(tableName, cols, kind) }));
59
+ }
60
+ }
61
+ return Object.freeze({ unique: Object.freeze(result.unique), index: Object.freeze(result.index) });
62
+ }
63
+
64
+ /** Folds constraint declarations from mixins and extension layers into one. */
65
+ export function mergeConstraintInputs(target, input) {
66
+ if (!input) return target;
67
+ for (const kind of KINDS) {
68
+ if (Array.isArray(input[kind])) target[kind] = [...(target[kind] ?? []), ...input[kind]];
69
+ }
70
+ return target;
71
+ }
72
+
73
+ export function constraintName(tableName, columns, kind) {
74
+ const name = `${tableName}_${columns.join("_")}_${kind}`;
75
+ if (name.length <= 63) return name;
76
+ let hash = 0;
77
+ for (const char of name) hash = (Math.imul(hash, 31) + char.charCodeAt(0)) >>> 0;
78
+ const suffix = `_${hash.toString(36)}_${kind}`;
79
+ return name.slice(0, 63 - suffix.length) + suffix;
80
+ }
81
+
82
+ /** Adds a model's constraints to a Knex table builder (create or alter). */
83
+ export function addConstraints(table, constraints, only = null) {
84
+ for (const c of constraints.unique) if (!only || only.has(c.name)) table.unique([...c.columns], { indexName: c.name });
85
+ for (const c of constraints.index) if (!only || only.has(c.name)) table.index([...c.columns], c.name);
86
+ }
87
+
88
+ /** Adds or drops one stored constraint ({ kind, name, columns }) on a Knex table builder. */
89
+ export function addConstraint(table, { kind, name, columns }) {
90
+ if (kind === "unique") table.unique([...columns], { indexName: name });
91
+ else table.index([...columns], name);
92
+ }
93
+ export function dropConstraint(table, { kind, name, columns }) {
94
+ if (kind === "unique") table.dropUnique([...columns], name);
95
+ else table.dropIndex([...columns], name);
96
+ }
@@ -6,6 +6,7 @@ import { defaultNamingStrategy } from "./naming.js";
6
6
  import { InvalidModelDefinitionError } from "./errors.js";
7
7
  import { defineRelation } from "../relations/define-relation.js";
8
8
  import { resolvePrimaryKey } from "./primary-key.js";
9
+ import { defineConstraints } from "./constraints.js";
9
10
 
10
11
  /**
11
12
  * @typedef {Object} ModelDescriptor
@@ -206,6 +207,8 @@ export function defineModel(
206
207
 
207
208
  const tableName = options.table ?? namingStrategy.modelToTable(options.name);
208
209
 
210
+ const constraints = defineConstraints(options.name, tableName, options.constraints, fields, columns);
211
+
209
212
  return Object.freeze({
210
213
  name: options.name,
211
214
  tableName,
@@ -214,5 +217,6 @@ export function defineModel(
214
217
  columns: Object.freeze(columns),
215
218
  relations: Object.freeze(relations),
216
219
  computed: Object.freeze(computed),
220
+ constraints,
217
221
  });
218
222
  }
@@ -1,4 +1,5 @@
1
1
  import { InvalidModelDefinitionError } from "./errors.js";
2
+ import { mergeConstraintInputs } from "./constraints.js";
2
3
 
3
4
  /**
4
5
  * Model inheritance, in the shape of Odoo's `_inherit` - which Odoo
@@ -155,13 +156,14 @@ export function foldModel(name, specs, stack = []) {
155
156
  if (stack.includes(name)) {
156
157
  throw new InvalidModelDefinitionError(`Circular mixins: ${[...stack, name].join(" -> ")}`);
157
158
  }
158
- const state = { table: undefined, primaryKey: undefined, fields: {}, relations: {}, origins: {} };
159
+ const state = { table: undefined, primaryKey: undefined, fields: {}, relations: {}, origins: {}, constraints: {} };
159
160
 
160
161
  for (const layer of specs.get(name).layers) {
161
162
  for (const mixinName of layer.def.mixins ?? []) {
162
163
  // A mixin contributes its fields and relations - never its name or table.
163
164
  const mixin = foldModel(mixinName, specs, [...stack, name]);
164
165
  applyPart(state, name, mixin.fields, mixin.relations, `mixin "${mixinName}"`);
166
+ mergeConstraintInputs(state.constraints, mixin.constraints);
165
167
  // A mixin may declare the primary key its models get; one set on the model itself wins.
166
168
  if (mixin.primaryKey !== undefined) state.primaryKey = mixin.primaryKey;
167
169
  }
@@ -175,6 +177,7 @@ export function foldModel(name, specs, stack = []) {
175
177
  state.table = layer.def.table;
176
178
  }
177
179
  applyPart(state, name, layer.def.fields ?? {}, layer.def.relations ?? {}, layerLabel(layer));
180
+ mergeConstraintInputs(state.constraints, layer.def.constraints);
178
181
  }
179
182
  return state;
180
183
  }
@@ -101,6 +101,7 @@ export class ModelRegistry {
101
101
  primaryKey: model.primaryKey ?? undefined,
102
102
  fields: { ...model.fields, ...(model.computed ?? {}) },
103
103
  relations: { ...model.relations },
104
+ constraints: { unique: (model.constraints?.unique ?? []).map((c) => [...c.fields]), index: (model.constraints?.index ?? []).map((c) => [...c.fields]) },
104
105
  };
105
106
  this.#specs.set(model.name, { abstract: false, layers: [{ kind: "primary", def, origin: null }] });
106
107
  this.#models.set(model.name, model);
@@ -249,7 +250,7 @@ export class ModelRegistry {
249
250
  try {
250
251
  folded = foldModel(name, candidate);
251
252
  const descriptor = defineModel(
252
- { name, table: spec.abstract ? undefined : folded.table, primaryKey: folded.primaryKey, fields: folded.fields, relations: folded.relations },
253
+ { name, table: spec.abstract ? undefined : folded.table, primaryKey: folded.primaryKey, fields: folded.fields, relations: folded.relations, constraints: folded.constraints },
253
254
  this.#namingStrategy,
254
255
  this.#fieldTypeRegistry
255
256
  );
@@ -4,6 +4,7 @@ import { resolveOnDelete } from "./foreign-keys.js";
4
4
  import { primaryKeyOf } from "../models/primary-key.js";
5
5
  import { IN_LIST_CHUNK } from "../crud/chunk.js";
6
6
  import { chunkArray } from "../crud/insert-many.js";
7
+ import { resolveDb } from "../transaction/context.js";
7
8
 
8
9
  // Since foreign keys became real database constraints (see foreign-keys.js), the database applies
9
10
  // onDelete itself and a delete is a single statement. Everything in this file is therefore only
@@ -151,7 +152,7 @@ export async function deleteRowsWithCascade(db, modelRegistry, model, where, opt
151
152
  `Remove the relations that point at it, or declare a primary key.`
152
153
  );
153
154
  }
154
- const baseDb = options.trx ?? db;
155
+ const baseDb = resolveDb(db, options.trx);
155
156
  const idColumn = model.columns[key];
156
157
  const ids = (await baseDb(model.tableName).where(where).select(idColumn)).map((row) => row[idColumn]);
157
158
  if (ids.length === 0) return 0;