@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,4 +1,5 @@
1
1
  import { META_MODELS_TABLE, META_FIELDS_TABLE } from "./reserved-tables.js";
2
+ import { parseStoredConstraints } from "./upsert.js";
2
3
 
3
4
  /**
4
5
  * A portable, id-free picture of one model's rows in `_meta_models` /
@@ -15,6 +16,8 @@ import { META_MODELS_TABLE, META_FIELDS_TABLE } from "./reserved-tables.js";
15
16
  * @typedef {Object} ModelMetaSnapshot
16
17
  * @property {string} table_name
17
18
  * @property {boolean} removed
19
+ * @property {Array<{ kind: string, name: string, fields: string[], columns: string[] }>} [constraints] - since 0.2.0;
20
+ * absent in migrations generated before, which then leave the stored value alone
18
21
  * @property {Array<{
19
22
  * name: string, column: string, type: string, required: boolean,
20
23
  * is_unique: boolean, is_indexed: boolean, options: unknown, removed: boolean
@@ -43,6 +46,7 @@ export async function snapshotModelMeta(db, modelName) {
43
46
  return {
44
47
  table_name: model.table_name,
45
48
  removed: model.removed_at !== null && model.removed_at !== undefined,
49
+ constraints: parseStoredConstraints(model.constraints),
46
50
  fields: rows.map((row) => ({
47
51
  name: row.name,
48
52
  column: row.column,
@@ -84,6 +88,7 @@ export async function restoreModelMeta(db, modelName, snapshot) {
84
88
  updated_at: now,
85
89
  removed_at: snapshot.removed ? now : null,
86
90
  };
91
+ if (snapshot.constraints !== undefined) modelValues.constraints = JSON.stringify(snapshot.constraints);
87
92
  let modelId;
88
93
  if (existing) {
89
94
  modelId = existing.id;
@@ -17,12 +17,14 @@ import { META_MODELS_TABLE, META_FIELDS_TABLE } from "./reserved-tables.js";
17
17
  */
18
18
  export async function ensureMetaModel(trx, model, now) {
19
19
  const existing = await trx(META_MODELS_TABLE).where({ name: model.name }).first();
20
+ const constraints = serializeConstraints(model.constraints);
20
21
 
21
22
  if (existing) {
22
23
  await trx(META_MODELS_TABLE).where({ id: existing.id }).update({
23
24
  table_name: model.tableName,
24
25
  updated_at: now,
25
26
  removed_at: null,
27
+ constraints,
26
28
  });
27
29
  return existing.id;
28
30
  }
@@ -33,6 +35,7 @@ export async function ensureMetaModel(trx, model, now) {
33
35
  created_at: now,
34
36
  updated_at: now,
35
37
  removed_at: null,
38
+ constraints,
36
39
  });
37
40
  const created = await trx(META_MODELS_TABLE).where({ name: model.name }).first();
38
41
  return created.id;
@@ -181,3 +184,28 @@ export async function flagRemovedFields(trx, modelId, currentFieldNames, now) {
181
184
  }
182
185
  return removed;
183
186
  }
187
+
188
+ /**
189
+ * A model's multi-field constraints as stored in `_meta_models.constraints` (since 0.2.0):
190
+ * `[{ kind: "unique"|"index", name, fields, columns }]`, as JSON text.
191
+ *
192
+ * @param {import('../models/constraints.js').ModelConstraints|undefined} constraints
193
+ */
194
+ export function serializeConstraints(constraints) {
195
+ return JSON.stringify(constraintList(constraints));
196
+ }
197
+
198
+ /** @returns {Array<{ kind: string, name: string, fields: string[], columns: string[] }>} */
199
+ export function constraintList(constraints) {
200
+ const list = [];
201
+ for (const kind of ["unique", "index"]) {
202
+ for (const c of constraints?.[kind] ?? []) list.push({ kind, name: c.name, fields: [...c.fields], columns: [...c.columns] });
203
+ }
204
+ return list;
205
+ }
206
+
207
+ /** The stored constraints of a `_meta_models` row; a row from before 0.2.0 has none. */
208
+ export function parseStoredConstraints(value) {
209
+ if (value === null || value === undefined) return [];
210
+ return typeof value === "string" ? JSON.parse(value) : value;
211
+ }
@@ -54,6 +54,18 @@ export function describePlan(plan) {
54
54
  `[DESTRUCTIVE] ${modelName}: drop field "${drop.fieldName}" (column "${drop.columnName}") - data will be lost`
55
55
  );
56
56
  }
57
+ for (const change of changes.optionChanges ?? []) {
58
+ const { label, detail } = describeOptionChange(change);
59
+ lines.push(`${label}${modelName}: field "${change.fieldName}" ${detail}`);
60
+ }
61
+ for (const c of changes.addConstraints ?? []) {
62
+ const label = c.kind === "unique" ? "[check] " : "[safe] ";
63
+ const note = c.kind === "unique" ? " - fails (and rolls back) if existing rows have duplicates" : "";
64
+ lines.push(`${label}${modelName}: add ${c.kind} (${c.fields.join(", ")}) "${c.name}"${note}`);
65
+ }
66
+ for (const c of changes.dropConstraints ?? []) {
67
+ lines.push(`[safe] ${modelName}: drop ${c.kind} (${c.fields.join(", ")}) "${c.name}"`);
68
+ }
57
69
  for (const change of changes.typeChanges) {
58
70
  lines.push(
59
71
  `[MANUAL] ${modelName}: field "${change.fieldName}" type changed ${change.from} -> ${change.to} - ` +
@@ -75,3 +87,40 @@ export function describePlan(plan) {
75
87
 
76
88
  return lines;
77
89
  }
90
+
91
+ /**
92
+ * One line per changed field (since 0.2.0). "[check]" means the database checks existing rows
93
+ * against the new rule: the migration fails and rolls back, changing nothing, if some don't fit.
94
+ */
95
+ function describeOptionChange({ changes, from, to }) {
96
+ const parts = [];
97
+ let check = false;
98
+ for (const key of changes) {
99
+ if (key === "required") {
100
+ if (to.required) {
101
+ const fill = to.default !== undefined && typeof to.default !== "function";
102
+ parts.push(fill ? `now required (existing NULLs set to ${JSON.stringify(to.default)})` : "now required");
103
+ check ||= !fill;
104
+ } else parts.push("now optional");
105
+ } else if (key === "unique") {
106
+ parts.push(to.unique ? "now unique" : "no longer unique");
107
+ check ||= Boolean(to.unique);
108
+ } else if (key === "index") {
109
+ parts.push(to.index ? "indexed" : "index dropped");
110
+ } else if (key === "default") {
111
+ parts.push(to.default === undefined || typeof to.default === "function" ? "default removed" : `default ${JSON.stringify(to.default)}`);
112
+ } else if (key === "maxLength") {
113
+ const [a, b] = [from.maxLength ?? 255, to.maxLength ?? 255];
114
+ parts.push(`maxLength ${a} -> ${b}`);
115
+ check ||= b < a;
116
+ } else if (key === "values") {
117
+ const removed = (from.values ?? []).filter((v) => !(to.values ?? []).includes(v));
118
+ const added = (to.values ?? []).filter((v) => !(from.values ?? []).includes(v));
119
+ if (added.length) parts.push(`allows ${added.map((v) => JSON.stringify(v)).join(", ")}`);
120
+ if (removed.length) parts.push(`no longer allows ${removed.map((v) => JSON.stringify(v)).join(", ")}`);
121
+ check ||= removed.length > 0;
122
+ }
123
+ }
124
+ const note = check ? " - checked against existing rows; fails (and rolls back) if some don't fit" : "";
125
+ return { label: check ? "[check] " : "[safe] ", detail: parts.join(", ") + note };
126
+ }
@@ -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";
@@ -14,6 +15,7 @@ import { describePlan } from "./describe.js";
14
15
  import { renderMigrationSource } from "./render.js";
15
16
  import { MigrationSafetyError, MigrationStateError } from "./errors.js";
16
17
  import { dialectOf } from "../schema/introspect-foreign-keys.js";
18
+ import { createTableOnce } from "../meta/create-table-once.js";
17
19
 
18
20
  /** Applied-migration history. `_meta_` is a reserved prefix, so no model's table can collide with it. */
19
21
  export const MIGRATIONS_TABLE = "_meta_migrations";
@@ -22,8 +24,7 @@ const FILE_PATTERN = /^(\d{14})_([a-z0-9_]+)\.(?:js|mjs)$/;
22
24
 
23
25
  /** @param {import('knex').Knex} db */
24
26
  export async function ensureMigrationsTable(db) {
25
- if (await db.schema.hasTable(MIGRATIONS_TABLE)) return;
26
- await db.schema.createTable(MIGRATIONS_TABLE, (table) => {
27
+ await createTableOnce(db, MIGRATIONS_TABLE, (table) => {
27
28
  table.increments("id");
28
29
  table.string("name", 255).notNullable().unique();
29
30
  table.timestamp("applied_at").notNullable();
@@ -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
  /**
@@ -113,6 +114,29 @@ function helpers(options) {
113
114
  *
114
115
  * Postgres alters tables in place and needs none of this.
115
116
  */
117
+ /**
118
+ * Serializes migrations across processes - two app instances deploying at once both see the same
119
+ * pending migrations. Taken at the start of each migration's transaction and held until it commits
120
+ * or rolls back; the caller then re-checks the history, so a migration the other process just
121
+ * applied is skipped instead of run twice (before 0.1.7 the second run failed half-way, or on
122
+ * SQLite applied DDL twice).
123
+ *
124
+ * Postgres: a transaction-scoped advisory lock - no extra connection, released with the
125
+ * transaction. SQLite: a write that changes nothing still takes the database's write lock, which
126
+ * SQLite holds until the transaction ends. A process waiting longer than the connection's busy
127
+ * timeout (5 s by default with better-sqlite3) fails with SQLITE_BUSY rather than waiting forever.
128
+ */
129
+ async function lockMigrations(trx) {
130
+ if (dialectOf(trx) === "postgres") {
131
+ await trx.raw("select pg_advisory_xact_lock(?)", [MIGRATION_LOCK_KEY]);
132
+ } else {
133
+ await trx(MIGRATIONS_TABLE).where(trx.raw("0 = 1")).update({ name: trx.ref("name") });
134
+ }
135
+ }
136
+
137
+ /** Any fixed 64-bit number works; this one is "kiri" in ASCII, so it's recognizable in pg_locks. */
138
+ const MIGRATION_LOCK_KEY = "1802072681";
139
+
116
140
  async function inMigrationTransaction(db, work) {
117
141
  if (dialectOf(db) !== "sqlite") return db.transaction(work);
118
142
  return db.transaction(
@@ -156,13 +180,18 @@ export async function migrateUp(db, options) {
156
180
  const applied = [];
157
181
  for (const entry of toApply) {
158
182
  const migration = await loadMigration(entry);
159
- await inMigrationTransaction(db, async (trx) => {
183
+ const ran = await inMigrationTransaction(db, async (trx) => {
184
+ await lockMigrations(trx);
185
+ // Another process may have applied it while this one waited for the lock.
186
+ if (await trx(MIGRATIONS_TABLE).where({ name: entry.name }).first()) return false;
160
187
  await migration.up(trx, helpers(options));
161
188
  for (const [modelName, snapshots] of Object.entries(migration.meta ?? {})) {
162
189
  await restoreModelMeta(trx, modelName, snapshots.after);
163
190
  }
164
191
  await trx(MIGRATIONS_TABLE).insert({ name: entry.name, applied_at: new Date() });
192
+ return true;
165
193
  });
194
+ if (!ran) continue;
166
195
  applied.push(entry.name);
167
196
  options.onApply?.(entry.name, migration.summary ?? []);
168
197
  }
@@ -178,7 +207,7 @@ export async function migrateUp(db, options) {
178
207
  }
179
208
  }
180
209
  for (const table of wanted) if (!(await db.schema.hasTable(table))) pivotTablesCreated.push(table);
181
- await ensurePivotTables(db, options.modelRegistry);
210
+ await ensurePivotTables(db, options.modelRegistry, options.columnBuilderRegistry ?? defaultColumnBuilderRegistry);
182
211
  }
183
212
  return { applied, pivotTablesCreated };
184
213
  }
@@ -207,13 +236,18 @@ export async function migrateDown(db, options) {
207
236
  const rolledBack = [];
208
237
  for (const row of toRollBack) {
209
238
  const migration = await loadMigration(files.get(row.name));
210
- await inMigrationTransaction(db, async (trx) => {
239
+ const ran = await inMigrationTransaction(db, async (trx) => {
240
+ await lockMigrations(trx);
241
+ // Another process may have rolled it back while this one waited for the lock.
242
+ if (!(await trx(MIGRATIONS_TABLE).where({ name: row.name }).first())) return false;
211
243
  await migration.down(trx, helpers(options));
212
244
  for (const [modelName, snapshots] of Object.entries(migration.meta ?? {})) {
213
245
  await restoreModelMeta(trx, modelName, snapshots.before);
214
246
  }
215
247
  await trx(MIGRATIONS_TABLE).where({ name: row.name }).delete();
248
+ return true;
216
249
  });
250
+ if (!ran) continue;
217
251
  rolledBack.push(row.name);
218
252
  options.onRollback?.(row.name, migration.summary ?? []);
219
253
  }
@@ -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
+ }