@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
@@ -0,0 +1,219 @@
1
+ import { buildColumn, storedDefault as storedColumnDefault } from "./build-column.js";
2
+ import { defaultColumnBuilderRegistry } from "./default-column-builders.js";
3
+
4
+ /**
5
+ * The column options a migration can change in place (since 0.2.0), compared between a field's
6
+ * recorded descriptor and its current one. Everything else about a column is either its type
7
+ * (never auto-migrated) or JS-side only (validation, casting).
8
+ *
9
+ * @param {import('../fields/define-field.js').FieldDescriptor} field
10
+ */
11
+ export function columnOptions(field) {
12
+ return {
13
+ required: Boolean(field.required),
14
+ unique: Boolean(field.unique),
15
+ index: Boolean(field.index),
16
+ default: field.default === undefined || typeof field.default === "function" ? null : field.default,
17
+ maxLength: field.type === "char" ? field.maxLength ?? 255 : null,
18
+ values: field.type === "enum" ? [...(field.values ?? [])] : null,
19
+ };
20
+ }
21
+
22
+ /** The names of the options that differ between two descriptors of the same field. */
23
+ export function changedColumnOptions(from, to) {
24
+ const a = columnOptions(from);
25
+ const b = columnOptions(to);
26
+ const same = (key) =>
27
+ key === "values" ? JSON.stringify([...(a.values ?? [])].sort()) === JSON.stringify([...(b.values ?? [])].sort()) : JSON.stringify(a[key]) === JSON.stringify(b[key]);
28
+ return Object.keys(a).filter((key) => !same(key));
29
+ }
30
+
31
+ const isSqlite = (db) => String(db.client.config?.client ?? "").includes("sqlite");
32
+
33
+ /**
34
+ * Changes one column from field descriptor `from` to `to`: NOT NULL, DEFAULT, varchar length,
35
+ * an enum's allowed values (its CHECK), and the column's single-field unique / index. Used by
36
+ * generated migrations (the `alterColumn` helper), because Knex's own `.alter()` can't do this on
37
+ * either database: on Postgres it emits invalid SQL for an enum, and on SQLite it keeps the old
38
+ * CHECK next to the new one.
39
+ *
40
+ * - Postgres: plain ALTER COLUMN / constraint statements, in place.
41
+ * - SQLite: the table is rebuilt with only this column's definition replaced (create a copy, copy
42
+ * the rows, drop, rename, recreate the indexes). Foreign key enforcement must be off for that
43
+ * (SQLite would otherwise run ON DELETE actions for the dropped table) - it is inside the
44
+ * migration runner's transaction. Called outside a transaction, this turns it off around its
45
+ * own transaction and checks the foreign keys before committing.
46
+ *
47
+ * Making a column required with a static default first fills existing NULLs with the default;
48
+ * otherwise a constraint the existing rows break (NULLs, duplicates, an enum value no longer
49
+ * allowed, text longer than the new length on Postgres) fails the statement, and the migration
50
+ * rolls back.
51
+ *
52
+ * @param {import('knex').Knex} db
53
+ * @param {string} tableName
54
+ * @param {string} columnName
55
+ * @param {import('../fields/define-field.js').FieldDescriptor} from
56
+ * @param {import('../fields/define-field.js').FieldDescriptor} to
57
+ * @param {import('./column-builder-registry.js').ColumnBuilderRegistry} [registry]
58
+ */
59
+ export async function alterColumn(db, tableName, columnName, from, to, registry = defaultColumnBuilderRegistry) {
60
+ const changed = new Set(changedColumnOptions(from, to));
61
+ if (changed.size === 0) return;
62
+ const next = columnOptions(to);
63
+
64
+ if (changed.has("required") && next.required && next.default !== null) {
65
+ await db(tableName).whereNull(columnName).update({ [columnName]: storedDefault(db, to) });
66
+ }
67
+
68
+ const definitionChanges = ["required", "default", "maxLength", "values"].filter((key) => changed.has(key));
69
+ if (definitionChanges.length > 0) {
70
+ if (isSqlite(db)) {
71
+ // varchar(n) isn't enforced by SQLite: a length change alone needs no rebuild.
72
+ if (!(definitionChanges.length === 1 && definitionChanges[0] === "maxLength")) {
73
+ await rebuildSqliteColumn(db, tableName, columnName, to, registry);
74
+ }
75
+ } else {
76
+ await alterPostgresColumn(db, tableName, columnName, definitionChanges, to);
77
+ }
78
+ }
79
+
80
+ if (changed.has("unique")) {
81
+ await db.schema.alterTable(tableName, (table) => (next.unique ? table.unique([columnName]) : table.dropUnique([columnName])));
82
+ }
83
+ if (changed.has("index")) {
84
+ await db.schema.alterTable(tableName, (table) => (next.index ? table.index([columnName]) : table.dropIndex([columnName])));
85
+ }
86
+ }
87
+
88
+ const storedDefault = (db, field) => storedColumnDefault(isSqlite(db), field);
89
+
90
+ /** A value as an SQL literal (DDL can't take bound parameters). */
91
+ const literal = (db, value) => db.raw("?", [value]).toQuery();
92
+
93
+ async function alterPostgresColumn(db, tableName, columnName, changes, to) {
94
+ const target = `${quote(tableName)}`;
95
+ const column = quote(columnName);
96
+ const next = columnOptions(to);
97
+ for (const change of changes) {
98
+ if (change === "required") {
99
+ await db.raw(`alter table ${target} alter column ${column} ${next.required ? "set" : "drop"} not null`);
100
+ } else if (change === "default") {
101
+ await db.raw(
102
+ next.default === null
103
+ ? `alter table ${target} alter column ${column} drop default`
104
+ : `alter table ${target} alter column ${column} set default ${literal(db, storedDefault(db, to))}`
105
+ );
106
+ } else if (change === "maxLength") {
107
+ await db.raw(`alter table ${target} alter column ${column} type varchar(${Number(next.maxLength)})`);
108
+ } else if (change === "values") {
109
+ // Knex creates an enum's CHECK unnamed (Postgres calls it <table>_<column>_check, but a table
110
+ // renamed since keeps the old name): find it by the one column it covers.
111
+ const { rows } = await db.raw(
112
+ `select con.conname from pg_constraint con
113
+ join pg_attribute att on att.attrelid = con.conrelid and att.attnum = any(con.conkey)
114
+ where con.conrelid = ?::regclass and con.contype = 'c' and att.attname = ? and array_length(con.conkey, 1) = 1`,
115
+ [quote(tableName), columnName]
116
+ );
117
+ for (const { conname } of rows) await db.raw(`alter table ${target} drop constraint ${quote(conname)}`);
118
+ const list = next.values.map((v) => literal(db, v)).join(", ");
119
+ await db.raw(`alter table ${target} add constraint ${quote(`${tableName}_${columnName}_check`)} check (${column} in (${list}))`);
120
+ }
121
+ }
122
+ }
123
+
124
+ const quote = (identifier) => `"${String(identifier).replace(/"/g, '""')}"`;
125
+
126
+ async function rebuildSqliteColumn(db, tableName, columnName, to, registry) {
127
+ const inTransaction = db.isTransaction === true;
128
+ const foreignKeysOn = Number((await db.raw("PRAGMA foreign_keys"))[0]?.foreign_keys) === 1;
129
+ if (foreignKeysOn && inTransaction) {
130
+ throw new Error(
131
+ `alterColumn("${tableName}", "${columnName}") on SQLite rebuilds the table, which with foreign keys enforced would run ` +
132
+ `ON DELETE actions on every table referencing it. Inside a transaction that can't be turned off: run it through the ` +
133
+ `migration runner (migrate:up), or on the connection itself.`
134
+ );
135
+ }
136
+ if (!inTransaction) {
137
+ if (foreignKeysOn) await db.raw("PRAGMA foreign_keys = OFF");
138
+ try {
139
+ await db.transaction(async (trx) => {
140
+ await rebuild(trx);
141
+ const violations = await trx.raw("PRAGMA foreign_key_check");
142
+ if (violations.length > 0) throw new Error(`alterColumn("${tableName}", "${columnName}"): the rebuilt table breaks ${violations.length} foreign key reference(s)`);
143
+ });
144
+ } finally {
145
+ if (foreignKeysOn) await db.raw("PRAGMA foreign_keys = ON");
146
+ }
147
+ return;
148
+ }
149
+ await rebuild(db);
150
+
151
+ async function rebuild(conn) {
152
+ const master = await conn.raw(`select type, name, sql from sqlite_master where tbl_name = ? and sql is not null`, [tableName]);
153
+ const tableRow = master.find((row) => row.type === "table");
154
+ if (!tableRow) throw new Error(`alterColumn: table "${tableName}" doesn't exist`);
155
+ const indexes = master.filter((row) => row.type === "index").map((row) => row.sql);
156
+ const triggers = master.filter((row) => row.type === "trigger").map((row) => row.sql);
157
+
158
+ const open = tableRow.sql.indexOf("(");
159
+ const close = tableRow.sql.lastIndexOf(")");
160
+ const parts = splitTopLevel(tableRow.sql.slice(open + 1, close));
161
+ const at = parts.findIndex((part) => leadingIdentifier(part)?.toLowerCase() === columnName.toLowerCase());
162
+ if (at === -1) throw new Error(`alterColumn: column "${columnName}" not found in table "${tableName}"`);
163
+ parts[at] = columnDefinition(conn, columnName, to, registry);
164
+
165
+ const temp = `_kiri_alter_${tableName}`;
166
+ await conn.raw(`create table ${quote(temp)} (${parts.join(", ")})${tableRow.sql.slice(close + 1)}`);
167
+ await conn.raw(`insert into ${quote(temp)} select * from ${quote(tableName)}`);
168
+ await conn.raw(`drop table ${quote(tableName)}`);
169
+ await conn.raw(`alter table ${quote(temp)} rename to ${quote(tableName)}`);
170
+ for (const sql of [...indexes, ...triggers]) await conn.raw(sql);
171
+ }
172
+ }
173
+
174
+ /** One column's definition as Knex would write it in a CREATE TABLE, without unique/index (separate statements). */
175
+ function columnDefinition(db, columnName, field, registry) {
176
+ const { sql } = db.schema
177
+ .createTable("__kiri_column", (table) => {
178
+ buildColumn(table, columnName, { ...field, unique: false, index: false, primary: false }, registry);
179
+ })
180
+ .toSQL()[0];
181
+ return sql.slice(sql.indexOf("(") + 1, sql.lastIndexOf(")")).trim();
182
+ }
183
+
184
+ /** Splits a CREATE TABLE body at its top-level commas, respecting quotes and parentheses. */
185
+ export function splitTopLevel(body) {
186
+ const parts = [];
187
+ let depth = 0;
188
+ let quoteChar = null;
189
+ let start = 0;
190
+ for (let i = 0; i < body.length; i++) {
191
+ const ch = body[i];
192
+ if (quoteChar) {
193
+ if (ch === quoteChar) {
194
+ if (body[i + 1] === quoteChar && quoteChar !== "]") i++;
195
+ else quoteChar = null;
196
+ }
197
+ continue;
198
+ }
199
+ if (ch === "'" || ch === '"' || ch === "`") quoteChar = ch;
200
+ else if (ch === "[") quoteChar = "]";
201
+ else if (ch === "(") depth++;
202
+ else if (ch === ")") depth--;
203
+ else if (ch === "," && depth === 0) {
204
+ parts.push(body.slice(start, i).trim());
205
+ start = i + 1;
206
+ }
207
+ }
208
+ parts.push(body.slice(start).trim());
209
+ return parts.filter(Boolean);
210
+ }
211
+
212
+ /** The column name a definition starts with, or null for a table constraint (PRIMARY KEY, FOREIGN KEY, ...). */
213
+ function leadingIdentifier(part) {
214
+ const quoted = /^(["`])((?:[^"`]|\1\1)*)\1/.exec(part) ?? /^\[([^\]]*)\]/.exec(part);
215
+ if (quoted) return quoted[2] ?? quoted[1];
216
+ const bare = /^([A-Za-z_][\w$]*)/.exec(part);
217
+ if (!bare) return null;
218
+ return /^(constraint|primary|foreign|unique|check)$/i.test(bare[1]) ? null : bare[1];
219
+ }
@@ -1,4 +1,6 @@
1
1
  import { defaultColumnBuilderRegistry } from "./default-column-builders.js";
2
+ import { decimalType, toScaledInteger } from "../fields/types/decimal.js";
3
+ import { dateType } from "../fields/types/date.js";
2
4
 
3
5
  /**
4
6
  * Adds one column to a Knex table builder for the given field, then
@@ -27,7 +29,7 @@ export function buildColumn(table, columnName, field, registry = defaultColumnBu
27
29
  if (isPrimary) {
28
30
  if (field.autoId === "increment") return table.increments(columnName);
29
31
  let idColumn = registry.get(field.type)(table, columnName, field).primary();
30
- if (field.default !== undefined && typeof field.default !== "function") idColumn = idColumn.defaultTo(field.default);
32
+ if (field.default !== undefined && typeof field.default !== "function") idColumn = idColumn.defaultTo(storedDefault(table, field));
31
33
  return idColumn;
32
34
  }
33
35
 
@@ -38,8 +40,32 @@ export function buildColumn(table, columnName, field, registry = defaultColumnBu
38
40
  if (field.unique) column = column.unique();
39
41
  if (field.index) column = column.index();
40
42
  if (field.default !== undefined && typeof field.default !== "function") {
41
- column = column.defaultTo(field.default);
43
+ column = column.defaultTo(storedDefault(table, field));
42
44
  }
43
45
 
44
46
  return column;
45
47
  }
48
+
49
+ /**
50
+ * A static default in the column's stored form, for the SQL DEFAULT clause: a decimal as its
51
+ * scaled integer on SQLite; a `date` as "YYYY-MM-DD" and a `datetime` Date as epoch milliseconds
52
+ * on SQLite / ISO text on Postgres - what the ORM itself writes. Before 0.2.0 a Date default went
53
+ * in as its toString() ("Sat Jun 01 2024 ... GMT+0900"): unreadable rows from raw inserts on
54
+ * SQLite, and syncModels() failing on Postgres.
55
+ *
56
+ * @param {boolean|import('knex').Knex.CreateTableBuilder} sqliteOrTable - a table builder, or whether the database is SQLite
57
+ * @param {import('../fields/define-field.js').FieldDescriptor} field
58
+ */
59
+ export function storedDefault(sqliteOrTable, field) {
60
+ const sqlite =
61
+ typeof sqliteOrTable === "boolean" ? sqliteOrTable : String(sqliteOrTable.client?.config?.client ?? "").includes("sqlite");
62
+ const value = field.default;
63
+ if (value === null || value === undefined) return value;
64
+ if (field.type === "decimal") {
65
+ const exact = decimalType.cast(field, value);
66
+ return sqlite ? toScaledInteger(exact, field.scale ?? 2) : exact;
67
+ }
68
+ if (field.type === "date") return dateType.cast(field, value);
69
+ if (field.type === "datetime" && value instanceof Date) return sqlite ? value.getTime() : value.toISOString();
70
+ return value;
71
+ }
@@ -17,7 +17,9 @@ export function createDefaultColumnBuilderRegistry() {
17
17
 
18
18
  registry.register("integer", (table, columnName) => table.integer(columnName));
19
19
 
20
- registry.register("float", (table, columnName) => table.float(columnName));
20
+ // `double`: an 8-byte float on both databases. Before 0.2.0 this was table.float(), which is a
21
+ // 4-byte `real` on Postgres (about 7 significant digits: 123456.789 read back as 123456.79).
22
+ registry.register("float", (table, columnName) => table.double(columnName));
21
23
 
22
24
  registry.register("boolean", (table, columnName) => table.boolean(columnName));
23
25
 
@@ -25,7 +27,15 @@ export function createDefaultColumnBuilderRegistry() {
25
27
 
26
28
  registry.register("datetime", (table, columnName) => table.datetime(columnName));
27
29
 
28
- registry.register("json", (table, columnName) => table.json(columnName));
30
+ // `jsonb` on Postgres since 0.2.0 (`json` before): it can be compared, indexed and grouped.
31
+ // SQLite stores either as text.
32
+ registry.register("json", (table, columnName) => table.jsonb(columnName));
33
+
34
+ // Exact numbers: numeric(precision, scale) on Postgres; on SQLite, which has no exact decimal
35
+ // type, an integer holding the value scaled by 10^scale (see fields/types/decimal.js).
36
+ registry.register("decimal", (table, columnName, field) =>
37
+ isSqliteTable(table) ? table.bigInteger(columnName) : table.decimal(columnName, field.precision ?? 15, field.scale ?? 2)
38
+ );
29
39
 
30
40
  registry.register("uuid", (table, columnName) => table.uuid(columnName));
31
41
 
@@ -36,4 +46,8 @@ export function createDefaultColumnBuilderRegistry() {
36
46
  return registry;
37
47
  }
38
48
 
49
+ function isSqliteTable(table) {
50
+ return String(table.client?.config?.client ?? table.client?.dialect ?? "").includes("sqlite");
51
+ }
52
+
39
53
  export const defaultColumnBuilderRegistry = createDefaultColumnBuilderRegistry();
@@ -7,3 +7,4 @@ export {
7
7
  } from "./default-column-builders.js";
8
8
  export { SchemaSyncError } from "./errors.js";
9
9
  export { listForeignKeys } from "./introspect-foreign-keys.js";
10
+ export { normalizeDateColumns } from "./normalize-dates.js";
@@ -0,0 +1,22 @@
1
+ import { dialectOf } from "./introspect-foreign-keys.js";
2
+
3
+ /**
4
+ * Names of the indexes on `table` (unique constraints included: both databases back them with an
5
+ * index of the constraint's name). Null for a dialect it can't introspect.
6
+ *
7
+ * @param {import('knex').Knex} db
8
+ * @param {string} table
9
+ * @returns {Promise<Set<string>|null>}
10
+ */
11
+ export async function listIndexNames(db, table) {
12
+ const dialect = dialectOf(db);
13
+ if (dialect === "sqlite") {
14
+ const rows = await db.raw("select name from pragma_index_list(?)", [table]);
15
+ return new Set(rows.map((r) => r.name));
16
+ }
17
+ if (dialect === "postgres") {
18
+ const rows = await db("pg_indexes").where({ tablename: table }).whereRaw("schemaname = current_schema()").select("indexname");
19
+ return new Set(rows.map((r) => r.indexname));
20
+ }
21
+ return null;
22
+ }
@@ -0,0 +1,58 @@
1
+ import { castValue } from "../fields/cast-value.js";
2
+ import { dialectOf } from "./introspect-foreign-keys.js";
3
+
4
+ /**
5
+ * @typedef {Object} NormalizedDateColumn
6
+ * @property {string} model
7
+ * @property {string} field
8
+ * @property {string} table
9
+ * @property {string} column
10
+ * @property {number} rows - values rewritten
11
+ */
12
+
13
+ /**
14
+ * Rewrites `date` values that SQLite still holds as epoch milliseconds into the "YYYY-MM-DD"
15
+ * text the ORM has written since 0.1.3. Since 0.1.7.
16
+ *
17
+ * 0.1.0-0.1.2 stored `date` fields as epoch ms (Knex binds a Date as its valueOf() on SQLite).
18
+ * 0.1.6+ reads those rows fine, but a column holding both forms still compares and sorts wrong
19
+ * in SQL - SQLite orders every number before every text - so a filter like
20
+ * `[["on", ">=", "2024-01-01"]]` or `orderBy: "on"` gives wrong results until it's rewritten.
21
+ *
22
+ * Each old value becomes the calendar day the read path already shows for it (see the `date`
23
+ * field type's cast), so nothing visible changes - only the stored form. Runs in one transaction;
24
+ * safe to run again (it only touches numeric values). Postgres stores a real `date` and has
25
+ * nothing to rewrite, so it returns an empty list there.
26
+ *
27
+ * @param {import('knex').Knex} db
28
+ * @param {import('../models/registry.js').ModelRegistry} modelRegistry
29
+ * @param {{ models?: string[], fieldTypeRegistry?: import('../fields/registry.js').FieldTypeRegistry }} [options]
30
+ * @returns {Promise<NormalizedDateColumn[]>} one entry per date column that had values to rewrite
31
+ */
32
+ export async function normalizeDateColumns(db, modelRegistry, options = {}) {
33
+ if (dialectOf(db) !== "sqlite") return [];
34
+ const modelNames = options.models ?? modelRegistry.listModels();
35
+
36
+ const work = async (trx) => {
37
+ const report = [];
38
+ for (const modelName of modelNames) {
39
+ const model = modelRegistry.getModel(modelName);
40
+ if (!(await trx.schema.hasTable(model.tableName))) continue;
41
+ for (const [fieldName, field] of Object.entries(model.fields)) {
42
+ if (field.type !== "date") continue;
43
+ const column = model.columns[fieldName];
44
+ // rowid, not the primary key: every table Knex creates has one, keyed or not.
45
+ const rows = await trx(model.tableName)
46
+ .select(trx.raw("rowid as ??", ["__kiri_rowid"]), column)
47
+ .whereRaw("typeof(??) in ('integer', 'real')", [column]);
48
+ for (const row of rows) {
49
+ const day = options.fieldTypeRegistry ? castValue(field, row[column], options.fieldTypeRegistry) : castValue(field, row[column]);
50
+ await trx(model.tableName).where(trx.raw("rowid = ?", [row.__kiri_rowid])).update({ [column]: day });
51
+ }
52
+ if (rows.length > 0) report.push({ model: modelName, field: fieldName, table: model.tableName, column, rows: rows.length });
53
+ }
54
+ }
55
+ return report;
56
+ };
57
+ return db.isTransaction ? work(db) : db.transaction(work);
58
+ }
@@ -6,6 +6,8 @@ import { ensurePivotTables } from "../relations/pivot-schema.js";
6
6
  import { foreignKeysOf } from "../relations/foreign-keys.js";
7
7
  import { addForeignKey, planCreation } from "./foreign-keys.js";
8
8
  import { ensureSqliteForeignKeys, listForeignKeys } from "./introspect-foreign-keys.js";
9
+ import { addConstraints } from "../models/constraints.js";
10
+ import { listIndexNames } from "./introspect-indexes.js";
9
11
 
10
12
  /**
11
13
  * @typedef {Object} SyncResult
@@ -56,7 +58,7 @@ export async function sync(db, modelRegistry, options = {}) {
56
58
  const columnBuilderRegistry = options.columnBuilderRegistry ?? defaultColumnBuilderRegistry;
57
59
 
58
60
  /** @type {SyncResult} */
59
- const result = { tablesCreated: [], columnsAdded: {}, foreignKeysAdded: [], warnings: [] };
61
+ const result = { tablesCreated: [], columnsAdded: {}, foreignKeysAdded: [], constraintsAdded: [], warnings: [] };
60
62
  const describeKey = (table, fk) => `${table}.${fk.column} -> ${fk.refTable}.${fk.refColumn}`;
61
63
 
62
64
  if ((await ensureSqliteForeignKeys(db)) === false) {
@@ -82,8 +84,10 @@ export async function sync(db, modelRegistry, options = {}) {
82
84
  buildColumn(table, model.columns[fieldName], field, columnBuilderRegistry);
83
85
  }
84
86
  for (const fk of inline) addForeignKey(table, fk);
87
+ addConstraints(table, model.constraints);
85
88
  });
86
89
  for (const fk of inline) result.foreignKeysAdded.push(describeKey(model.tableName, fk));
90
+ for (const c of [...model.constraints.unique, ...model.constraints.index]) result.constraintsAdded.push(c.name);
87
91
  }
88
92
  // A cycle (a -> b -> a) can't be satisfied inside the CREATE TABLEs: add those keys now.
89
93
  for (const { model, fk } of plan.deferred) {
@@ -114,6 +118,16 @@ export async function sync(db, modelRegistry, options = {}) {
114
118
  for (const fk of withNewColumn) result.foreignKeysAdded.push(describeKey(model.tableName, fk));
115
119
  }
116
120
 
121
+ // Multi-field constraints (model `constraints`) that the table doesn't have yet, by name.
122
+ // A unique one fails here if existing rows already break it - fix the data, then sync again.
123
+ const indexNames = await listIndexNames(db, model.tableName);
124
+ const missingConstraints = indexNames && [...model.constraints.unique, ...model.constraints.index].filter((c) => !indexNames.has(c.name));
125
+ if (missingConstraints?.length) {
126
+ const names = new Set(missingConstraints.map((c) => c.name));
127
+ await db.schema.alterTable(model.tableName, (table) => addConstraints(table, model.constraints, names));
128
+ result.constraintsAdded.push(...names);
129
+ }
130
+
117
131
  const present = await listForeignKeys(db, model.tableName);
118
132
  if (present === null) continue; // a dialect we can't introspect
119
133
  const missing = wanted.filter((fk) => !addedColumns.has(fk.column) && !present.some((p) => p.column === fk.column && p.refTable === fk.refTable));
@@ -140,7 +154,7 @@ export async function sync(db, modelRegistry, options = {}) {
140
154
  }
141
155
  }
142
156
 
143
- await ensurePivotTables(db, modelRegistry);
157
+ await ensurePivotTables(db, modelRegistry, columnBuilderRegistry);
144
158
  await ensureMetaTables(db);
145
159
  result.meta = await syncMeta(db, modelRegistry);
146
160
 
@@ -0,0 +1,142 @@
1
+ import { currentTransaction } from "./context.js";
2
+
3
+ /**
4
+ * Work deferred until a transaction commits (since 0.2.0): the `afterCommit` hook, and anything
5
+ * else registered with afterCommit(fn). And, since 0.2.0, work that undoes in-memory state when a
6
+ * transaction rolls back (onRollback()).
7
+ *
8
+ * Callbacks are queued on the OUTERMOST transaction - a savepoint's release isn't a commit - and run
9
+ * in order once it commits. A rollback drops them: the outermost transaction's rollback drops all of
10
+ * them; a savepoint's rollback (inside a transaction that still commits) drops only those queued
11
+ * inside that savepoint. Outside any transaction there is nothing to wait for and the callback runs
12
+ * at once.
13
+ *
14
+ * instrumentConnection() calls flushAfterCommit() when a transaction it started commits, before the
15
+ * caller's `await db.transaction(...)` resumes; so an error thrown there reaches that caller (the
16
+ * data is already committed - it is the side effect that failed).
17
+ */
18
+ const queues = new WeakMap(); // outermost transactor -> [{ owner, fn }]
19
+ const rollbackQueues = new WeakMap(); // outermost transactor -> [{ owner, fn }]
20
+
21
+ export function outermostTransaction(trx) {
22
+ let current = trx;
23
+ while (current.parentTransaction) current = current.parentTransaction;
24
+ return current;
25
+ }
26
+
27
+ /**
28
+ * Runs `fn` after `db` commits, or now when `db` isn't a transaction. The ORM's own entry point
29
+ * (the `afterCommit` hook), with the connection it resolved.
30
+ *
31
+ * @param {import('knex').Knex} db
32
+ * @param {() => unknown} fn
33
+ */
34
+ export async function queueAfterCommit(db, fn) {
35
+ if (!db?.isTransaction) {
36
+ await fn();
37
+ return;
38
+ }
39
+ const root = outermostTransaction(db);
40
+ if (!queues.has(root)) queues.set(root, []);
41
+ queues.get(root).push({ owner: db, fn });
42
+ }
43
+
44
+ /**
45
+ * Runs `fn` once the transaction open in this async flow commits - the outermost one, so a
46
+ * savepoint's release doesn't count - or right away outside a transaction:
47
+ *
48
+ * await transaction(async () => {
49
+ * const order = await Order.create(data);
50
+ * afterCommit(() => queue.publish("order.created", { id: order.id }));
51
+ * });
52
+ *
53
+ * A rollback (of the transaction, or of the savepoint the call was made in) drops `fn`. An error it
54
+ * throws reaches whoever awaited the outermost `transaction()`. Outside a transaction it returns a
55
+ * promise of `fn`'s result. `afterCommit(trx, fn)` (0.2.0's form) queues on `trx`.
56
+ *
57
+ * @param {(() => unknown) | import('knex').Knex} fnOrTrx
58
+ * @param {() => unknown} [fn]
59
+ * @returns {Promise<unknown>}
60
+ */
61
+ export function afterCommit(fnOrTrx, fn) {
62
+ if (typeof fnOrTrx !== "function" || fn !== undefined) {
63
+ if (typeof fn !== "function") return Promise.reject(new TypeError("afterCommit(fn) expects a function"));
64
+ return queueAfterCommit(fnOrTrx, fn);
65
+ }
66
+ const trx = currentTransaction();
67
+ if (trx) return queueAfterCommit(trx, fnOrTrx);
68
+ try {
69
+ return Promise.resolve(fnOrTrx());
70
+ } catch (error) {
71
+ return Promise.reject(error);
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Registers `fn` to run if `db` - or the transaction it is part of - rolls back (since 0.2.0). The
77
+ * ORM uses it to put tracked documents back to what the database holds after a rollback undid
78
+ * their save(). Callbacks are synchronous and run in reverse order of registration, so several
79
+ * saves of one document unwind to its value before the first. Nothing is registered outside a
80
+ * transaction (an autocommitted write can't roll back).
81
+ *
82
+ * @param {import('knex').Knex} db
83
+ * @param {() => void} fn
84
+ */
85
+ export function onRollback(db, fn) {
86
+ if (!db?.isTransaction) return;
87
+ const root = outermostTransaction(db);
88
+ if (!rollbackQueues.has(root)) rollbackQueues.set(root, []);
89
+ rollbackQueues.get(root).push({ owner: db, fn });
90
+ }
91
+
92
+ /** Runs everything queued on a committed outermost transaction, in order. */
93
+ export async function flushAfterCommit(root) {
94
+ rollbackQueues.delete(root); // committed: nothing left to undo
95
+ const queue = queues.get(root);
96
+ if (!queue) return;
97
+ queues.delete(root);
98
+ const errors = [];
99
+ for (const { fn } of queue) {
100
+ try {
101
+ await fn();
102
+ } catch (error) {
103
+ errors.push(error);
104
+ }
105
+ }
106
+ if (errors.length === 1) throw errors[0];
107
+ if (errors.length > 1) throw new AggregateError(errors, `${errors.length} afterCommit callbacks failed (the transaction had committed)`);
108
+ }
109
+
110
+ /** Drops what was queued inside `trx` (and the savepoints inside it), because it rolled back. */
111
+ export function discardAfterCommit(trx) {
112
+ const root = outermostTransaction(trx);
113
+ const inside = (owner) => {
114
+ for (let t = owner; t; t = t.parentTransaction) if (t === trx) return true;
115
+ return false;
116
+ };
117
+ runRollbackCallbacks(root, trx === root ? () => true : inside);
118
+ if (root === trx) {
119
+ queues.delete(root);
120
+ return;
121
+ }
122
+ const queue = queues.get(root);
123
+ if (!queue) return;
124
+ queues.set(root, queue.filter((entry) => !inside(entry.owner)));
125
+ }
126
+
127
+ /** Runs (newest first) and removes the rollback callbacks registered inside the rolled-back part. */
128
+ function runRollbackCallbacks(root, isInside) {
129
+ const queue = rollbackQueues.get(root);
130
+ if (!queue) return;
131
+ const undone = queue.filter((entry) => isInside(entry.owner));
132
+ const kept = queue.filter((entry) => !isInside(entry.owner));
133
+ if (kept.length) rollbackQueues.set(root, kept);
134
+ else rollbackQueues.delete(root);
135
+ for (let i = undone.length - 1; i >= 0; i--) {
136
+ try {
137
+ undone[i].fn();
138
+ } catch {
139
+ // Restoring in-memory state must never hide the rollback's own error.
140
+ }
141
+ }
142
+ }
@@ -0,0 +1,84 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ /**
4
+ * The transactions open in the current async flow (since 0.2.0).
5
+ *
6
+ * Every transaction started with a container - `db.transaction(async (trx) => ...)`, the global
7
+ * `transaction()`, `client.transaction()`, savepoints inside them, and the ORM's own internal
8
+ * transactions - runs its callback inside a scope recorded here (see instrumentConnection()).
9
+ * Any model call made in that callback, however deep (a hook, a helper in another file), finds
10
+ * the transaction through resolveDb() and joins it, without `{ trx }` being passed along.
11
+ *
12
+ * A scope: { baseClient, trx, parent } - `baseClient` is the Knex client of the connection the
13
+ * transaction belongs to, so a transaction on one connection is never joined by queries meant for
14
+ * another; `parent` is the enclosing scope (nested transactions and savepoints).
15
+ */
16
+ const scopes = new AsyncLocalStorage();
17
+
18
+ /** Runs `fn` inside a scope where `trx` is the open transaction for `baseClient`. */
19
+ export function runInTransactionScope(baseClient, trx, fn) {
20
+ return scopes.run({ baseClient, trx, parent: scopes.getStore() }, fn);
21
+ }
22
+
23
+ /**
24
+ * The transaction open in this async flow for `db`'s connection, or null. A `db` that is already a
25
+ * transaction is used as given (null here). A finished transaction is never returned: code still
26
+ * running after its commit (a timer started inside it, say) goes back to the connection itself.
27
+ *
28
+ * @param {import('knex').Knex} db
29
+ * @returns {import('knex').Knex.Transaction | null}
30
+ */
31
+ export function ambientTransaction(db) {
32
+ if (!db || db.isTransaction || !db.client) return null;
33
+ for (let scope = scopes.getStore(); scope; scope = scope.parent) {
34
+ if (scope.baseClient === db.client) return scope.trx.isCompleted() ? null : scope.trx;
35
+ }
36
+ return null;
37
+ }
38
+
39
+ /**
40
+ * Which connection an operation runs on: an explicit `{ trx }` first, then the transaction open in
41
+ * this async flow, then `db` itself. Every ORM entry point resolves its connection through this.
42
+ *
43
+ * @param {import('knex').Knex} db
44
+ * @param {import('knex').Knex.Transaction} [trx]
45
+ */
46
+ export function resolveDb(db, trx) {
47
+ return trx ?? ambientTransaction(db) ?? db;
48
+ }
49
+
50
+ /**
51
+ * The innermost unfinished transaction open in this async flow, on any connection, or null. For
52
+ * APIs that take no connection at all, like the public `afterCommit(fn)`.
53
+ *
54
+ * @returns {import('knex').Knex.Transaction | null}
55
+ */
56
+ export function currentTransaction() {
57
+ for (let scope = scopes.getStore(); scope; scope = scope.parent) {
58
+ if (!scope.trx.isCompleted()) return scope.trx;
59
+ }
60
+ return null;
61
+ }
62
+
63
+ /** Whether a transaction for `client` is open (and unfinished) in this async flow. */
64
+ export function holdsTransactionFor(client) {
65
+ for (let scope = scopes.getStore(); scope; scope = scope.parent) {
66
+ if (scope.baseClient === client && !scope.trx.isCompleted()) return true;
67
+ }
68
+ return false;
69
+ }
70
+
71
+ /**
72
+ * Runs `fn(db)` in a transaction when `needed` and `db` isn't one already; otherwise on `db` as is.
73
+ * Used to make a write and its hooks one atomic unit only when there are hooks to protect.
74
+ *
75
+ * @template T
76
+ * @param {boolean} needed
77
+ * @param {import('knex').Knex} db
78
+ * @param {(db: import('knex').Knex) => Promise<T>} fn
79
+ * @returns {Promise<T>}
80
+ */
81
+ export function inTransactionIf(needed, db, fn) {
82
+ if (!needed || db.isTransaction) return fn(db);
83
+ return db.transaction((trx) => fn(trx));
84
+ }