@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.
- package/README.md +27 -15
- package/dist/types/client/model-handle.d.ts +4 -1
- package/dist/types/connection.d.ts +39 -0
- package/dist/types/crud/database-errors.d.ts +61 -0
- package/dist/types/crud/errors.d.ts +10 -0
- package/dist/types/crud/fast-path.d.ts +73 -0
- package/dist/types/crud/index.d.ts +4 -1
- package/dist/types/crud/insert-many.d.ts +1 -1
- package/dist/types/crud/order.d.ts +28 -0
- package/dist/types/crud/repository.d.ts +5 -3
- package/dist/types/crud/upsert.d.ts +39 -0
- package/dist/types/crud/value.d.ts +39 -0
- package/dist/types/dialect/index.d.ts +1 -1
- package/dist/types/dialect/transaction-guard.d.ts +19 -18
- package/dist/types/domain/compile.d.ts +17 -0
- package/dist/types/fields/filter-value.d.ts +21 -0
- package/dist/types/fields/registry.d.ts +1 -0
- package/dist/types/fields/storage.d.ts +28 -0
- package/dist/types/fields/types/date.d.ts +5 -0
- package/dist/types/fields/types/decimal.d.ts +40 -0
- package/dist/types/global/index.d.ts +1 -0
- package/dist/types/global/transaction.d.ts +10 -13
- package/dist/types/index.d.ts +2 -0
- package/dist/types/meta/snapshot.d.ts +10 -0
- package/dist/types/meta/upsert.d.ts +16 -0
- package/dist/types/migrations/diff.d.ts +25 -2
- package/dist/types/models/constraints.d.ts +27 -0
- package/dist/types/schema/alter-column.d.ts +46 -0
- package/dist/types/schema/build-column.d.ts +11 -0
- package/dist/types/schema/introspect-indexes.d.ts +9 -0
- package/dist/types/transaction/after-commit.d.ts +42 -0
- package/dist/types/transaction/context.d.ts +39 -0
- package/dist/types/uow/entity.d.ts +39 -29
- package/dist/types/uow/hooks.d.ts +6 -1
- package/dist/types/uow/lifecycle.d.ts +82 -0
- package/dist/types/uow/unit-of-work.d.ts +11 -7
- package/package.json +5 -4
- package/src/client/model-handle.js +14 -4
- package/src/client/orm-client.js +10 -5
- package/src/connection.js +34 -4
- package/src/crud/aggregate-filter.js +8 -2
- package/src/crud/aggregate-spec.js +2 -2
- package/src/crud/aggregate.js +16 -5
- package/src/crud/create-many.js +52 -29
- package/src/crud/database-errors.js +107 -0
- package/src/crud/errors.js +14 -0
- package/src/crud/fast-path.js +449 -0
- package/src/crud/index.js +4 -1
- package/src/crud/insert-many.js +25 -7
- package/src/crud/map-filter.js +2 -1
- package/src/crud/order.js +59 -9
- package/src/crud/repository.js +106 -38
- package/src/crud/row-mapping.js +32 -7
- package/src/crud/upsert.js +203 -0
- package/src/crud/value.js +71 -0
- package/src/dialect/index.js +1 -1
- package/src/dialect/transaction-guard.js +216 -45
- package/src/domain/compile.js +85 -12
- package/src/dto/field-schema.js +5 -0
- package/src/fields/default-registry.js +3 -1
- package/src/fields/filter-value.js +87 -0
- package/src/fields/registry.js +1 -0
- package/src/fields/storage.js +50 -0
- package/src/fields/types/date.js +16 -3
- package/src/fields/types/decimal.js +147 -0
- package/src/fields/types/integer.js +7 -0
- package/src/global/connect.js +2 -2
- package/src/global/create-model.js +59 -57
- package/src/global/errors.js +1 -1
- package/src/global/index.js +1 -0
- package/src/global/transaction.js +12 -14
- package/src/index.js +2 -0
- package/src/meta/schema.js +10 -0
- package/src/meta/snapshot.js +5 -0
- package/src/meta/upsert.js +28 -0
- package/src/migrations/describe.js +49 -0
- package/src/migrations/diff.js +50 -7
- package/src/migrations/generate.js +38 -2
- package/src/migrations/render.js +30 -12
- package/src/migrations/runner.js +2 -1
- package/src/models/constraints.js +96 -0
- package/src/models/define-model.js +4 -0
- package/src/models/inheritance.js +4 -1
- package/src/models/registry.js +2 -1
- package/src/relations/cascade-delete.js +2 -1
- package/src/relations/eager-load.js +45 -40
- package/src/reports/report-handle.js +2 -1
- package/src/schema/alter-column.js +219 -0
- package/src/schema/build-column.js +28 -2
- package/src/schema/default-column-builders.js +16 -2
- package/src/schema/introspect-indexes.js +22 -0
- package/src/schema/sync.js +15 -1
- package/src/transaction/after-commit.js +142 -0
- package/src/transaction/context.js +84 -0
- package/src/uow/entity.js +133 -133
- package/src/uow/hooks.js +9 -0
- package/src/uow/lifecycle.js +162 -0
- package/src/uow/unit-of-work.js +44 -56
- package/src/uow/with-unit-of-work.js +2 -1
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
import { fromRow } from "../crud/row-mapping.js";
|
|
2
2
|
import { isPostgres } from "../crud/sequence.js";
|
|
3
|
+
import { dialectOfClient } from "../fields/storage.js";
|
|
3
4
|
import { IN_LIST_CHUNK } from "../crud/chunk.js";
|
|
5
|
+
import { nullsClause, orderWithNulls } from "../crud/order.js";
|
|
4
6
|
import { chunkArray } from "../crud/insert-many.js";
|
|
5
7
|
import { planSelect, stripHidden } from "../crud/select.js";
|
|
6
8
|
import { RelationError } from "./errors.js";
|
|
7
9
|
import { resolveLocalKey } from "./keys.js";
|
|
8
10
|
import { normalizeWith, parentKeysNeeded } from "./with-spec.js";
|
|
9
11
|
import { primaryKeyOf } from "../models/primary-key.js";
|
|
12
|
+
import { compileFastFind, runFast } from "../crud/fast-path.js";
|
|
10
13
|
|
|
11
14
|
/**
|
|
12
15
|
* Fails clearly when the records being loaded onto don't carry the field a relation is
|
|
@@ -27,7 +30,7 @@ function assertKeysLoaded(records, keys, relationName, model) {
|
|
|
27
30
|
/**
|
|
28
31
|
* Batch-loads one relation for a whole set of already-fetched records
|
|
29
32
|
* and attaches the result onto each record under `relationName`.
|
|
30
|
-
* Exactly one additional query is issued (
|
|
33
|
+
* Exactly one additional query is issued per relation (since 0.2.0 belongsToMany too; before, one
|
|
31
34
|
* against the pivot table, one against the related table) regardless
|
|
32
35
|
* of how many records are in `records` - this is the N+1 prevention
|
|
33
36
|
* the roadmap calls for. See defineRelation() for what `foreignKey`/
|
|
@@ -60,14 +63,14 @@ async function loadOneRelation(db, modelRegistry, model, records, relationName,
|
|
|
60
63
|
const table = relatedModel.tableName;
|
|
61
64
|
const windowed = node.limit !== undefined || node.offset !== undefined;
|
|
62
65
|
|
|
63
|
-
const toRecords = (rows, plan) => rows.map((row) => fromRow(relatedModel, row, fieldTypeRegistry, { computed: plan.computed, jsonParsed: isPostgres(db) }));
|
|
66
|
+
const toRecords = (rows, plan) => rows.map((row) => fromRow(relatedModel, row, fieldTypeRegistry, { computed: plan.computed, jsonParsed: isPostgres(db), dialect: dialectOfClient(db.client) }));
|
|
64
67
|
|
|
65
68
|
/** ORDER BY for the related rows: the requested order, then the primary key so ties (and a limit) are deterministic. */
|
|
66
69
|
const orderFor = (prefix) => {
|
|
67
70
|
const entries = [...node.order];
|
|
68
71
|
const key = primaryKeyOf(relatedModel);
|
|
69
72
|
if ((windowed || entries.length > 0) && key !== null && !entries.some((e) => e.field === key)) entries.push({ field: key, direction: "asc" });
|
|
70
|
-
return entries.map((e) => ({ column: `${prefix}${relatedModel.columns[e.field]}`, direction: e.direction }));
|
|
73
|
+
return entries.map((e) => ({ column: `${prefix}${relatedModel.columns[e.field]}`, direction: e.direction, nulls: e.nulls, field: e.field === key ? null : relatedModel.fields[e.field] }));
|
|
71
74
|
};
|
|
72
75
|
|
|
73
76
|
/**
|
|
@@ -79,15 +82,25 @@ async function loadOneRelation(db, modelRegistry, model, records, relationName,
|
|
|
79
82
|
*/
|
|
80
83
|
const read = async (matchColumn, values, ownKey) => {
|
|
81
84
|
const plan = planSelect(relatedModel, node.select, [ownKey, ...nestedKeys]);
|
|
82
|
-
const rows = await inChunks(values, (chunk) => readChunk(matchColumn, chunk, plan));
|
|
85
|
+
const rows = await inChunks(values, (chunk) => readChunk(matchColumn, chunk, plan, ownKey));
|
|
83
86
|
return { hidden: plan.hidden, related: toRecords(rows, plan) };
|
|
84
87
|
};
|
|
85
|
-
const readChunk = async (matchColumn, values, plan) => {
|
|
88
|
+
const readChunk = async (matchColumn, values, plan, ownKey) => {
|
|
89
|
+
if (!windowed || values.length === 1) {
|
|
90
|
+
// The plain read (no per-parent window) is a find() on the related model: written directly
|
|
91
|
+
// when it can be (crud/fast-path.js), like any find.
|
|
92
|
+
const order = orderFor("").map((o) => [relatedModelField(o.column), o.direction, o.nulls]);
|
|
93
|
+
const filter = [[ownKey, "in", values], ...(node.where === undefined ? [] : [asDomain(node.where)])];
|
|
94
|
+
const paging = windowed ? { limit: node.limit, offset: node.offset } : {};
|
|
95
|
+
const fast = compileFastFind(db, relatedModel, filter, plan.columns, { orderBy: order, ...paging }, fieldTypeRegistry);
|
|
96
|
+
const rows = fast ? await runFast(db, fast) : undefined;
|
|
97
|
+
if (rows !== undefined) return rows;
|
|
98
|
+
}
|
|
86
99
|
let query = db(table).whereIn(matchColumn, values);
|
|
87
100
|
if (node.whereFn) query = query.where(node.whereFn);
|
|
88
101
|
|
|
89
102
|
let rows;
|
|
90
|
-
if (windowed) {
|
|
103
|
+
if (windowed && values.length > 1) {
|
|
91
104
|
const order = orderFor("");
|
|
92
105
|
const orderBy = order.map((o) => `?? ${o.direction === "desc" ? "DESC" : "ASC"}`).join(", ");
|
|
93
106
|
const inner = query
|
|
@@ -96,11 +109,18 @@ async function loadOneRelation(db, modelRegistry, model, records, relationName,
|
|
|
96
109
|
rows = await rankWindow(db, inner, plan.columns, node);
|
|
97
110
|
} else {
|
|
98
111
|
if (plan.columns) query = query.select(plan.columns);
|
|
99
|
-
for (const { column, direction } of orderFor("")) query = query
|
|
112
|
+
for (const { column, direction, nulls, field } of orderFor("")) query = orderWithNulls(query, column, direction, nullsClause(query, field, direction, nulls));
|
|
113
|
+
// One parent: a limit per parent is just a LIMIT, no window function needed (since 0.2.0).
|
|
114
|
+
if (windowed) {
|
|
115
|
+
if (node.limit !== undefined) query = query.limit(node.limit);
|
|
116
|
+
if (node.offset) query = query.offset(node.offset);
|
|
117
|
+
}
|
|
100
118
|
rows = await query;
|
|
101
119
|
}
|
|
102
120
|
return rows;
|
|
103
121
|
};
|
|
122
|
+
const fieldOfColumn = new Map(Object.entries(relatedModel.columns).map(([field, column]) => [column, field]));
|
|
123
|
+
const relatedModelField = (column) => fieldOfColumn.get(column);
|
|
104
124
|
const nothing = { relatedModel, related: [], hidden: [] };
|
|
105
125
|
|
|
106
126
|
if (relation.type === "belongsTo") {
|
|
@@ -158,11 +178,12 @@ async function loadOneRelation(db, modelRegistry, model, records, relationName,
|
|
|
158
178
|
);
|
|
159
179
|
}
|
|
160
180
|
|
|
161
|
-
//
|
|
162
|
-
//
|
|
163
|
-
|
|
181
|
+
// One joined statement: the pivot and the related rows together (since 0.2.0 also when there's
|
|
182
|
+
// no order or limit; before, that case read the pivot, then the related rows - two round trips).
|
|
183
|
+
{
|
|
164
184
|
const plan = planSelect(relatedModel, node.select, [relatedKey, ...nestedKeys]);
|
|
165
|
-
|
|
185
|
+
// A `where` on the related rows needs them as a subquery; otherwise join the table itself.
|
|
186
|
+
const related = node.whereFn ? db(table).where(node.whereFn).as("t") : `${table} as t`;
|
|
166
187
|
const order = orderFor("t.");
|
|
167
188
|
|
|
168
189
|
const rows = await inChunks(localValues, async (chunk) => {
|
|
@@ -172,16 +193,21 @@ async function loadOneRelation(db, modelRegistry, model, records, relationName,
|
|
|
172
193
|
.select(db.raw("?? AS ??", [`pv.${relation.foreignKey}`, PARENT]))
|
|
173
194
|
.select(plan.columns ? plan.columns.map((c) => `t.${c}`) : "t.*");
|
|
174
195
|
|
|
175
|
-
if (windowed) {
|
|
196
|
+
if (windowed && chunk.length > 1) {
|
|
176
197
|
const orderBy = order.map((o) => `?? ${o.direction === "desc" ? "DESC" : "ASC"}`).join(", ");
|
|
177
198
|
query = query.select(db.raw(`row_number() OVER (PARTITION BY ?? ORDER BY ${orderBy}) AS ??`, [`pv.${relation.foreignKey}`, ...order.map((o) => o.column), RANK]));
|
|
178
199
|
return rankWindow(db, query, plan.columns ? [...plan.columns.map((c) => c), PARENT] : null, node, PARENT);
|
|
179
200
|
}
|
|
180
|
-
for (const { column, direction } of order) query = query
|
|
201
|
+
for (const { column, direction, nulls, field } of order) query = orderWithNulls(query, column, direction, nullsClause(query, field, direction, nulls));
|
|
202
|
+
if (windowed) {
|
|
203
|
+
// One parent: the per-parent limit is a plain LIMIT.
|
|
204
|
+
if (node.limit !== undefined) query = query.limit(node.limit);
|
|
205
|
+
if (node.offset) query = query.offset(node.offset);
|
|
206
|
+
}
|
|
181
207
|
return query;
|
|
182
208
|
});
|
|
183
209
|
|
|
184
|
-
// The same related row may sit under several parents: one object, shared
|
|
210
|
+
// The same related row may sit under several parents: one object, shared between them.
|
|
185
211
|
const byKey = new Map();
|
|
186
212
|
const byParent = new Map();
|
|
187
213
|
for (const row of rows) {
|
|
@@ -195,32 +221,6 @@ async function loadOneRelation(db, modelRegistry, model, records, relationName,
|
|
|
195
221
|
return { relatedModel, related: [...byKey.values()], hidden: plan.hidden };
|
|
196
222
|
}
|
|
197
223
|
|
|
198
|
-
// Only the two link columns are needed from the pivot table.
|
|
199
|
-
const pivotRows = await inChunks(localValues, (chunk) =>
|
|
200
|
-
db(relation.through).select(relation.foreignKey, relation.otherKey).whereIn(relation.foreignKey, chunk)
|
|
201
|
-
);
|
|
202
|
-
const relatedIds = uniqueDefined(pivotRows.map((row) => row[relation.otherKey]));
|
|
203
|
-
|
|
204
|
-
let related = [];
|
|
205
|
-
let hidden = [];
|
|
206
|
-
let relatedById = new Map();
|
|
207
|
-
if (relatedIds.length > 0) {
|
|
208
|
-
({ related, hidden } = await read(relatedModel.columns[relatedKey], relatedIds, relatedKey));
|
|
209
|
-
relatedById = new Map(related.map((rec) => [rec[relatedKey], rec]));
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
const idsByLocalKey = new Map();
|
|
213
|
-
for (const row of pivotRows) {
|
|
214
|
-
const key = row[relation.foreignKey];
|
|
215
|
-
if (!idsByLocalKey.has(key)) idsByLocalKey.set(key, []);
|
|
216
|
-
idsByLocalKey.get(key).push(row[relation.otherKey]);
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
for (const r of records) {
|
|
220
|
-
const ids = idsByLocalKey.get(r[localKey]) ?? [];
|
|
221
|
-
r[relationName] = ids.map((id) => relatedById.get(id)).filter((rec) => rec !== undefined);
|
|
222
|
-
}
|
|
223
|
-
return { relatedModel, related, hidden };
|
|
224
224
|
}
|
|
225
225
|
|
|
226
226
|
return nothing;
|
|
@@ -242,6 +242,11 @@ async function rankWindow(db, inner, columns, node, extraColumn = null) {
|
|
|
242
242
|
return outer.orderBy(RANK);
|
|
243
243
|
}
|
|
244
244
|
|
|
245
|
+
/** A `where` of a `with` entry as a domain (a plain object is equality on each of its fields). */
|
|
246
|
+
function asDomain(where) {
|
|
247
|
+
return Array.isArray(where) ? where : Object.entries(where).map(([field, value]) => [field, "=", value]);
|
|
248
|
+
}
|
|
249
|
+
|
|
245
250
|
function uniqueDefined(values) {
|
|
246
251
|
return [...new Set(values.filter((v) => v !== null && v !== undefined))];
|
|
247
252
|
}
|
|
@@ -5,6 +5,7 @@ import { planAggregate } from "../crud/aggregate-spec.js";
|
|
|
5
5
|
import { defaultFieldTypeRegistry } from "../fields/default-registry.js";
|
|
6
6
|
import { toAggregateOptions } from "./define-report.js";
|
|
7
7
|
import { ReportDefinitionError } from "./errors.js";
|
|
8
|
+
import { resolveDb } from "../transaction/context.js";
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
11
|
* Runs a report (see defineReport()). Every call is one SQL statement, whatever the grain,
|
|
@@ -102,7 +103,7 @@ export class ReportHandle {
|
|
|
102
103
|
|
|
103
104
|
const fieldTypeRegistry = this.#env.fieldTypeRegistry ?? defaultFieldTypeRegistry;
|
|
104
105
|
const ctx = {
|
|
105
|
-
db:
|
|
106
|
+
db: resolveDb(this.#env.db(), options.trx),
|
|
106
107
|
model,
|
|
107
108
|
filter: [...toTerms(descriptor.where), ...toTerms(filter)],
|
|
108
109
|
options: { ...this.#prepared.aggregateOptions, orderBy, limit: options.limit, offset: options.offset },
|
|
@@ -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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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();
|
|
@@ -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
|
+
}
|
package/src/schema/sync.js
CHANGED
|
@@ -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));
|