@hot-updater/plugin-core 1.2.0-rc.5 → 1.2.0-rc.51
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/dist/coreApi.d.cts +277 -10
- package/dist/coreApi.d.mts +277 -10
- package/dist/database/adapter.d.cts +24 -0
- package/dist/database/adapter.d.mts +24 -0
- package/dist/databaseRows.cjs +4 -2
- package/dist/databaseRows.mjs +4 -2
- package/dist/engine/core/schema.cjs +253 -6
- package/dist/engine/core/schema.d.cts +154 -1
- package/dist/engine/core/schema.d.mts +154 -1
- package/dist/engine/core/schema.mjs +252 -7
- package/dist/engine/createEngine.cjs +1 -2
- package/dist/engine/createEngine.d.cts +1 -6
- package/dist/engine/createEngine.d.mts +1 -6
- package/dist/engine/createEngine.mjs +1 -2
- package/dist/engine/database/aggregateBatching.cjs +87 -129
- package/dist/engine/database/aggregateBatching.mjs +87 -129
- package/dist/engine/database/database.cjs +1 -4
- package/dist/engine/database/database.mjs +1 -4
- package/dist/engine/database/engineTransaction.cjs +21 -1
- package/dist/engine/database/engineTransaction.d.cts +5 -1
- package/dist/engine/database/engineTransaction.d.mts +5 -1
- package/dist/engine/database/engineTransaction.mjs +21 -1
- package/dist/engine/database/kv/kvAdapter.cjs +80 -4
- package/dist/engine/database/kv/kvAdapter.mjs +80 -4
- package/dist/engine/database/resolveSchema.cjs +6 -3
- package/dist/engine/database/resolveSchema.mjs +6 -3
- package/dist/engine/database/sql/sqlAdapter.cjs +36 -12
- package/dist/engine/database/sql/sqlAdapter.mjs +37 -13
- package/dist/engine/database/sql/sqlSchema.cjs +24 -6
- package/dist/engine/database/sql/sqlSchema.d.cts +1 -1
- package/dist/engine/database/sql/sqlSchema.d.mts +1 -1
- package/dist/engine/database/sql/sqlSchema.mjs +24 -6
- package/dist/engine/db/coreDatabase.cjs +10 -5
- package/dist/engine/db/coreDatabase.d.cts +2 -1
- package/dist/engine/db/coreDatabase.d.mts +2 -1
- package/dist/engine/db/coreDatabase.mjs +10 -5
- package/dist/engine/db/engineMigrator.cjs +45 -17
- package/dist/engine/db/engineMigrator.mjs +46 -18
- package/dist/engine/db/engineSql.cjs +25 -0
- package/dist/engine/db/engineSql.d.cts +13 -1
- package/dist/engine/db/engineSql.d.mts +13 -1
- package/dist/engine/db/engineSql.mjs +26 -2
- package/dist/engine/db/engineSqlMigrator.cjs +60 -21
- package/dist/engine/db/engineSqlMigrator.d.cts +2 -0
- package/dist/engine/db/engineSqlMigrator.d.mts +2 -0
- package/dist/engine/db/engineSqlMigrator.mjs +62 -23
- package/dist/engine/db/schemaSettings.cjs +56 -5
- package/dist/engine/db/schemaSettings.d.cts +5 -2
- package/dist/engine/db/schemaSettings.d.mts +5 -2
- package/dist/engine/db/schemaSettings.mjs +55 -6
- package/dist/engine/db/settingsMigrator.cjs +124 -15
- package/dist/engine/db/settingsMigrator.d.cts +18 -8
- package/dist/engine/db/settingsMigrator.d.mts +18 -8
- package/dist/engine/db/settingsMigrator.mjs +121 -16
- package/dist/engine/db/sqlSchemaState.cjs +136 -0
- package/dist/engine/db/sqlSchemaState.mjs +131 -0
- package/dist/engine/db/types.d.cts +6 -0
- package/dist/engine/db/types.d.mts +6 -0
- package/dist/index.cjs +3 -8
- package/dist/index.d.cts +6 -7
- package/dist/index.d.mts +6 -7
- package/dist/index.mjs +4 -5
- package/dist/releaseCatalogCompiler.cjs +18 -7
- package/dist/releaseCatalogCompiler.mjs +18 -7
- package/dist/releaseCatalogMutation.d.cts +6 -0
- package/dist/releaseCatalogMutation.d.mts +6 -0
- package/dist/serverPlugin/coreReads.d.cts +10 -1
- package/dist/serverPlugin/coreReads.d.mts +10 -1
- package/dist/serverPlugin/definitions.d.cts +4 -0
- package/dist/serverPlugin/definitions.d.mts +4 -0
- package/dist/serverPlugin/schema.d.cts +4 -0
- package/dist/serverPlugin/schema.d.mts +4 -0
- package/dist/types/databaseConfig.d.cts +10 -20
- package/dist/types/databaseConfig.d.mts +10 -20
- package/dist/types/databaseRows.d.cts +77 -2
- package/dist/types/databaseRows.d.mts +77 -2
- package/dist/types/index.cjs +3 -0
- package/dist/types/index.d.cts +114 -56
- package/dist/types/index.d.mts +114 -56
- package/dist/types/index.mjs +3 -1
- package/dist/types/models.d.cts +9 -1
- package/dist/types/models.d.mts +9 -1
- package/dist/types/public.d.cts +3 -3
- package/dist/types/public.d.mts +3 -3
- package/package.json +3 -9
- package/dist/remoteBundleSigning.cjs +0 -357
- package/dist/remoteBundleSigning.d.cts +0 -38
- package/dist/remoteBundleSigning.d.mts +0 -38
- package/dist/remoteBundleSigning.mjs +0 -352
|
@@ -1,12 +1,18 @@
|
|
|
1
|
+
import { LATE_COLUMNS, LATE_INDEXES } from "../core/schema.mjs";
|
|
1
2
|
import { SETTINGS_TABLE, readSettings } from "../database/fence.mjs";
|
|
3
|
+
import { refuseNewerSchema } from "./settingsMigrator.mjs";
|
|
2
4
|
//#region src/engine/db/schemaSettings.ts
|
|
3
5
|
const storedSettings = async (adapter, keys) => {
|
|
4
6
|
const rows = await readSettings(adapter, keys);
|
|
5
7
|
return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
|
|
6
8
|
};
|
|
7
|
-
/**
|
|
8
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Writes the settings rows after every table exists, and refuses a database
|
|
11
|
+
* whose `ordered` settings a newer release recorded.
|
|
12
|
+
*/
|
|
13
|
+
const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
|
|
9
14
|
const stored = await storedSettings(adapter, Object.keys(settings));
|
|
15
|
+
refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
|
|
10
16
|
const ops = Object.entries(settings).flatMap(([key, value]) => {
|
|
11
17
|
const row = stored.get(key);
|
|
12
18
|
if (row === null || row === void 0) return [{
|
|
@@ -31,11 +37,54 @@ const writeSchemaSettings = async (adapter, adapterName, settings) => {
|
|
|
31
37
|
if (ops.length === 0) return;
|
|
32
38
|
if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
|
|
33
39
|
};
|
|
34
|
-
/**
|
|
35
|
-
|
|
40
|
+
/**
|
|
41
|
+
* The `LATE_INDEXES` among `tables` whose items some rows lack, as
|
|
42
|
+
* `<table>.<index>`, written unless `dryRun`: none on a store without
|
|
43
|
+
* `migrations.fillIndex`.
|
|
44
|
+
*/
|
|
45
|
+
const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
|
|
46
|
+
const fillIndex = adapter.migrations?.fillIndex;
|
|
47
|
+
if (fillIndex === void 0) return [];
|
|
48
|
+
const lacking = [];
|
|
49
|
+
for (const { table: name, index } of LATE_INDEXES) {
|
|
50
|
+
const table = tables.find((candidate) => candidate.name === name);
|
|
51
|
+
if (table === void 0) continue;
|
|
52
|
+
if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
|
|
53
|
+
}
|
|
54
|
+
return lacking;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* The `LATE_COLUMNS` among `tables` that an existing table lacks, as
|
|
58
|
+
* `<table>.<column>`, added unless `dryRun`: none on a store without
|
|
59
|
+
* `migrations.addColumns`, or for a table not created yet.
|
|
60
|
+
*/
|
|
61
|
+
const addLateColumns = async (adapter, tables, { dryRun = false } = {}) => {
|
|
62
|
+
const addColumns = adapter.migrations?.addColumns;
|
|
63
|
+
if (addColumns === void 0) return [];
|
|
64
|
+
const lacking = [];
|
|
65
|
+
for (const table of tables) {
|
|
66
|
+
const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
|
|
67
|
+
if (columns.length === 0) continue;
|
|
68
|
+
const added = await addColumns(table, columns, { dryRun });
|
|
69
|
+
lacking.push(...added.map((column) => `${table.name}.${column}`));
|
|
70
|
+
}
|
|
71
|
+
return lacking;
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* Adds the late columns existing tables lack, creates or updates every
|
|
75
|
+
* table, writes the late indexes' missing items, then writes the settings
|
|
76
|
+
* rows last. A database a newer release migrated is
|
|
77
|
+
* refused before anything is written: its settings are read first, and a
|
|
78
|
+
* store without them yet, whose read fails, has none to refuse.
|
|
79
|
+
*/
|
|
80
|
+
const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
|
|
36
81
|
if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
|
|
82
|
+
const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
|
|
83
|
+
if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
|
|
84
|
+
await addLateColumns(adapter, tables);
|
|
37
85
|
await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
|
|
38
|
-
await
|
|
86
|
+
await fillLateIndexes(adapter, tables);
|
|
87
|
+
await writeSchemaSettings(adapter, adapterName, settings, ordered);
|
|
39
88
|
};
|
|
40
89
|
//#endregion
|
|
41
|
-
export { migrateSchema, writeSchemaSettings };
|
|
90
|
+
export { addLateColumns, fillLateIndexes, migrateSchema, writeSchemaSettings };
|
|
@@ -3,6 +3,7 @@ const require_fence = require("../database/fence.cjs");
|
|
|
3
3
|
const require_fixedMigratorShared = require("./fixedMigratorShared.cjs");
|
|
4
4
|
const require_sqlSchema = require("../database/sql/sqlSchema.cjs");
|
|
5
5
|
const require_engineSql = require("./engineSql.cjs");
|
|
6
|
+
const require_sqlSchemaState = require("./sqlSchemaState.cjs");
|
|
6
7
|
//#region src/engine/db/settingsMigrator.ts
|
|
7
8
|
/**
|
|
8
9
|
* Every settings row by key and value alone, so a v0 layout reads too; null
|
|
@@ -35,33 +36,129 @@ const refuseV0Database = (adapterName, stored) => {
|
|
|
35
36
|
if (typeof version !== "string" || stored.has("schema.engine")) return;
|
|
36
37
|
throw new require_fence.HotUpdaterSchemaMigrationRequiredError(adapterName, version);
|
|
37
38
|
};
|
|
39
|
+
/** Compares dotted numeric versions, such as "1" and "1.2.0"; NaN when either is not one. */
|
|
40
|
+
const compareVersions = (left, right) => {
|
|
41
|
+
const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
|
|
42
|
+
const [a, b] = [parse(left), parse(right)];
|
|
43
|
+
if ([...a, ...b].some(Number.isNaN)) return NaN;
|
|
44
|
+
for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
|
|
45
|
+
const difference = (a[index] ?? 0) - (b[index] ?? 0);
|
|
46
|
+
if (difference !== 0) return difference;
|
|
47
|
+
}
|
|
48
|
+
return 0;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* The settings whose versions only move forward when a `ToolingTarget` names
|
|
52
|
+
* none. `schema.engine` is a storage layout, not a release: a store refuses
|
|
53
|
+
* another layout itself, and doctor reports it as not migratable.
|
|
54
|
+
*/
|
|
55
|
+
const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
|
|
56
|
+
/**
|
|
57
|
+
* Refuses a database a newer release migrated, one whose `schema.core` is
|
|
58
|
+
* newer than this release's: writing this release's settings would move the
|
|
59
|
+
* schema back, and every server of the newer release would answer 503. Only
|
|
60
|
+
* `ordered` settings are compared, `schema.core` among them, and the message
|
|
61
|
+
* lists each that is newer. An official plugin's
|
|
62
|
+
* newer version alone is no newer release: Insights recorded "1.2.0" in
|
|
63
|
+
* 1.0.0-rc.23 and rc.24, then went back to "1.0.0" with the same tables.
|
|
64
|
+
*/
|
|
65
|
+
const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
|
|
66
|
+
const newer = ordered.flatMap((key) => {
|
|
67
|
+
const found = stored.get(key);
|
|
68
|
+
const expected = settings[key];
|
|
69
|
+
return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
|
|
70
|
+
key,
|
|
71
|
+
found,
|
|
72
|
+
expected
|
|
73
|
+
}] : [];
|
|
74
|
+
});
|
|
75
|
+
const core = newer.find(({ key }) => key === "schema.core");
|
|
76
|
+
if (core === void 0) return;
|
|
77
|
+
throw new Error(`${adapterName}: the database was migrated by Hot Updater ${core.found} (${newer.map(({ key, found, expected }) => `${key} "${found}", this CLI's "${expected}"`).join("; ")}). Upgrade hot-updater to ${core.found} or later; nothing was written.`);
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* The tables, late columns or indexes an ORM has yet to apply, found before `db migrate`
|
|
81
|
+
* writes the settings rows, so the fence never passes over missing tables.
|
|
82
|
+
*/
|
|
83
|
+
var HotUpdaterSchemaTablesMissingError = class extends Error {
|
|
84
|
+
adapterName;
|
|
85
|
+
missing;
|
|
86
|
+
applyTables;
|
|
87
|
+
constructor(adapterName, missing, applyTables) {
|
|
88
|
+
const all = missing.tables.includes(require_fence.SETTINGS_TABLE.name);
|
|
89
|
+
const items = [
|
|
90
|
+
...missing.tables.length === 0 ? [] : [`table${missing.tables.length === 1 ? "" : "s"} ${missing.tables.join(", ")}`],
|
|
91
|
+
...missing.columns.length === 0 ? [] : [`column${missing.columns.length === 1 ? "" : "s"} ${missing.columns.map(({ table, column }) => `${table}.${column.name}`).join(", ")}`],
|
|
92
|
+
...missing.indexes.length === 0 ? [] : [`index${missing.indexes.length === 1 ? "" : "es"} ${missing.indexes.map(({ index }) => index).join(", ")}`]
|
|
93
|
+
];
|
|
94
|
+
super(`${adapterName}: ${all ? "the Hot Updater tables are missing" : `the database lacks ${items.join(" and ")}`}. Run \`hot-updater db generate\`, apply it with ${applyTables}, then migrate again.`);
|
|
95
|
+
this.adapterName = adapterName;
|
|
96
|
+
this.missing = missing;
|
|
97
|
+
this.applyTables = applyTables;
|
|
98
|
+
this.name = "HotUpdaterSchemaTablesMissingError";
|
|
99
|
+
}
|
|
100
|
+
};
|
|
38
101
|
/**
|
|
39
102
|
* `hot-updater db migrate` for an ORM that applies the DDL itself (Drizzle,
|
|
40
|
-
* Prisma)
|
|
41
|
-
*
|
|
103
|
+
* Prisma). Before it writes the settings rows it refuses a v0 database or one
|
|
104
|
+
* a newer release migrated, checks that every table and index the target
|
|
105
|
+
* declares exists, and sets the collations the ORM cannot declare on the
|
|
106
|
+
* columns that lack them. The `createMigrator` of an adapter whose ORM
|
|
42
107
|
* creates the tables returns it, as the Drizzle and Prisma adapters' do.
|
|
43
108
|
*/
|
|
44
109
|
const createSettingsMigrator = (options) => {
|
|
45
110
|
const read = () => readStoredSettings(options.executor);
|
|
46
111
|
const getVersion = async () => storedSchemaVersion(await read());
|
|
112
|
+
const { executor } = options;
|
|
47
113
|
const makeResult = async (migrate = {}) => {
|
|
48
|
-
const stored = await read();
|
|
49
|
-
if (stored === null) throw new Error(`${options.adapterName}: the Hot Updater tables are missing. Run \`hot-updater db generate\`, apply the schema with ${options.applyTables}, then migrate again.`);
|
|
114
|
+
const stored = await read() ?? /* @__PURE__ */ new Map();
|
|
50
115
|
refuseV0Database(options.adapterName, stored);
|
|
51
|
-
|
|
52
|
-
const
|
|
53
|
-
const
|
|
116
|
+
refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
|
|
117
|
+
const shapes = require_sqlSchemaState.targetShapes(executor.dialect, options.schema);
|
|
118
|
+
const missing = require_sqlSchemaState.missingSqlSchema(shapes, await require_sqlSchemaState.readSqlSchemaState(executor));
|
|
119
|
+
const lateTables = new Set(missing.columns.map(({ table }) => table));
|
|
120
|
+
const lateIndexes = missing.indexes.filter(({ table }) => lateTables.has(table));
|
|
121
|
+
const blocking = missing.indexes.filter(({ table }) => !lateTables.has(table));
|
|
122
|
+
if (missing.tables.length > 0 || blocking.length > 0) throw new HotUpdaterSchemaTablesMissingError(options.adapterName, {
|
|
123
|
+
tables: missing.tables,
|
|
124
|
+
columns: [],
|
|
125
|
+
indexes: blocking
|
|
126
|
+
}, options.applyTables);
|
|
127
|
+
const quote = (name) => require_sqlSchema.quoteSql(executor.dialect, name);
|
|
128
|
+
const lateSchema = [...require_sqlSchemaState.addColumnStatements(executor.dialect, missing.columns), ...lateIndexes.map(({ table, index: name }) => {
|
|
129
|
+
const index = shapes.find((shape) => shape.name === table).indexes.find((candidate) => candidate.kind === "index" && candidate.name === name);
|
|
130
|
+
return index.kind === "index" ? `CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quote(name)} ON ${quote(table)} (${index.columns.map(quote).join(", ")})` : "";
|
|
131
|
+
})];
|
|
132
|
+
const collations = options.collate === void 0 ? {
|
|
133
|
+
statements: [],
|
|
134
|
+
columns: 0
|
|
135
|
+
} : await require_sqlSchemaState.collationStatements(executor, shapes.filter((shape) => shape.name !== require_fence.SETTINGS_TABLE.name), options.collate);
|
|
136
|
+
const changed = migrate.updateSettings === false ? [] : Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
|
|
137
|
+
if (lateSchema.length === 0 && collations.statements.length === 0 && changed.length === 0) return require_fixedMigratorShared.getEmptyMigrationResult();
|
|
138
|
+
const statements = [
|
|
139
|
+
...lateSchema,
|
|
140
|
+
...collations.statements,
|
|
141
|
+
...changed.length === 0 ? [] : require_engineSql.settingsStatements(executor.dialect, options.settings)
|
|
142
|
+
];
|
|
54
143
|
return {
|
|
55
|
-
operations: [
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
144
|
+
operations: [
|
|
145
|
+
...missing.columns.map(({ table, column }) => ({
|
|
146
|
+
type: "custom",
|
|
147
|
+
description: `Add column: ${column.name} to ${table}`
|
|
148
|
+
})),
|
|
149
|
+
...lateIndexes.map(({ table, index }) => ({
|
|
150
|
+
type: "custom",
|
|
151
|
+
description: `Create index: ${index} on ${table}`
|
|
152
|
+
})),
|
|
153
|
+
...collations.columns === 0 ? [] : [{
|
|
154
|
+
type: "custom",
|
|
155
|
+
description: `Set the byte-order collation the ORM cannot declare on ${collations.columns} column${collations.columns === 1 ? "" : "s"} of ${collations.statements.length} table${collations.statements.length === 1 ? "" : "s"}`
|
|
156
|
+
}],
|
|
157
|
+
...changed.length === 0 ? [] : [settingsOperation(stored, changed)]
|
|
158
|
+
],
|
|
62
159
|
getSQL: () => statements.map((statement) => `${statement};`).join("\n\n"),
|
|
63
160
|
execute: async () => {
|
|
64
|
-
for (const sql of statements) await
|
|
161
|
+
for (const sql of statements) await executor.execute({
|
|
65
162
|
sql,
|
|
66
163
|
params: []
|
|
67
164
|
});
|
|
@@ -84,8 +181,20 @@ const createSettingsMigrator = (options) => {
|
|
|
84
181
|
migrateToLatest: makeResult
|
|
85
182
|
};
|
|
86
183
|
};
|
|
184
|
+
/** The settings rows a migration changes, each with its stored value. */
|
|
185
|
+
const settingsOperation = (stored, changed) => ({
|
|
186
|
+
type: "custom",
|
|
187
|
+
description: `Record ${changed.map(([key, value]) => {
|
|
188
|
+
const found = stored.get(key);
|
|
189
|
+
return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
|
|
190
|
+
}).join(", ")}`
|
|
191
|
+
});
|
|
87
192
|
//#endregion
|
|
193
|
+
exports.DEFAULT_ORDERED_SETTINGS = DEFAULT_ORDERED_SETTINGS;
|
|
194
|
+
exports.HotUpdaterSchemaTablesMissingError = HotUpdaterSchemaTablesMissingError;
|
|
88
195
|
exports.createSettingsMigrator = createSettingsMigrator;
|
|
89
196
|
exports.readStoredSettings = readStoredSettings;
|
|
197
|
+
exports.refuseNewerSchema = refuseNewerSchema;
|
|
90
198
|
exports.refuseV0Database = refuseV0Database;
|
|
199
|
+
exports.settingsOperation = settingsOperation;
|
|
91
200
|
exports.storedSchemaVersion = storedSchemaVersion;
|
|
@@ -1,24 +1,34 @@
|
|
|
1
|
+
import { ResolvedSchema } from "../database/resolveSchema.cjs";
|
|
1
2
|
import { SchemaSettings } from "../database/fence.cjs";
|
|
2
3
|
import { Migrator } from "./types.cjs";
|
|
4
|
+
import { SqlColumnShape } from "../database/sql/sqlSchema.cjs";
|
|
3
5
|
import { SqlExecutor } from "../database/sql/sqlAdapter.cjs";
|
|
4
6
|
//#region src/engine/db/settingsMigrator.d.ts
|
|
5
7
|
/**
|
|
6
8
|
* `hot-updater db migrate` for an ORM that applies the DDL itself (Drizzle,
|
|
7
|
-
* Prisma)
|
|
8
|
-
*
|
|
9
|
+
* Prisma). Before it writes the settings rows it refuses a v0 database or one
|
|
10
|
+
* a newer release migrated, checks that every table and index the target
|
|
11
|
+
* declares exists, and sets the collations the ORM cannot declare on the
|
|
12
|
+
* columns that lack them. The `createMigrator` of an adapter whose ORM
|
|
9
13
|
* creates the tables returns it, as the Drizzle and Prisma adapters' do.
|
|
10
14
|
*/
|
|
11
15
|
declare const createSettingsMigrator: (options: {
|
|
12
16
|
readonly adapterName: string;
|
|
13
17
|
readonly executor: SqlExecutor;
|
|
18
|
+
/** The tables the ORM applies, which must exist before the settings move. */
|
|
19
|
+
readonly schema: ResolvedSchema;
|
|
14
20
|
readonly settings: SchemaSettings;
|
|
15
|
-
/**
|
|
21
|
+
/** The settings whose versions only move forward; `ToolingTarget.ordered`. */
|
|
22
|
+
readonly ordered?: readonly string[];
|
|
23
|
+
/** The command that applies the generated schema, for the error when tables are missing. */
|
|
16
24
|
readonly applyTables: string;
|
|
17
|
-
/**
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
25
|
+
/**
|
|
26
|
+
* The columns whose collation the ORM cannot declare, which `db migrate`
|
|
27
|
+
* sets where the database lacks it. The settings table is left as it is:
|
|
28
|
+
* it is only read by key, and the migrator has already read it, so
|
|
29
|
+
* altering it would invalidate PostgreSQL's cached plan for that read.
|
|
30
|
+
*/
|
|
31
|
+
readonly collate?: (column: SqlColumnShape) => boolean;
|
|
22
32
|
}) => Migrator;
|
|
23
33
|
//#endregion
|
|
24
34
|
export { createSettingsMigrator };
|
|
@@ -1,24 +1,34 @@
|
|
|
1
|
+
import { ResolvedSchema } from "../database/resolveSchema.mjs";
|
|
1
2
|
import { SchemaSettings } from "../database/fence.mjs";
|
|
2
3
|
import { Migrator } from "./types.mjs";
|
|
4
|
+
import { SqlColumnShape } from "../database/sql/sqlSchema.mjs";
|
|
3
5
|
import { SqlExecutor } from "../database/sql/sqlAdapter.mjs";
|
|
4
6
|
//#region src/engine/db/settingsMigrator.d.ts
|
|
5
7
|
/**
|
|
6
8
|
* `hot-updater db migrate` for an ORM that applies the DDL itself (Drizzle,
|
|
7
|
-
* Prisma)
|
|
8
|
-
*
|
|
9
|
+
* Prisma). Before it writes the settings rows it refuses a v0 database or one
|
|
10
|
+
* a newer release migrated, checks that every table and index the target
|
|
11
|
+
* declares exists, and sets the collations the ORM cannot declare on the
|
|
12
|
+
* columns that lack them. The `createMigrator` of an adapter whose ORM
|
|
9
13
|
* creates the tables returns it, as the Drizzle and Prisma adapters' do.
|
|
10
14
|
*/
|
|
11
15
|
declare const createSettingsMigrator: (options: {
|
|
12
16
|
readonly adapterName: string;
|
|
13
17
|
readonly executor: SqlExecutor;
|
|
18
|
+
/** The tables the ORM applies, which must exist before the settings move. */
|
|
19
|
+
readonly schema: ResolvedSchema;
|
|
14
20
|
readonly settings: SchemaSettings;
|
|
15
|
-
/**
|
|
21
|
+
/** The settings whose versions only move forward; `ToolingTarget.ordered`. */
|
|
22
|
+
readonly ordered?: readonly string[];
|
|
23
|
+
/** The command that applies the generated schema, for the error when tables are missing. */
|
|
16
24
|
readonly applyTables: string;
|
|
17
|
-
/**
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
25
|
+
/**
|
|
26
|
+
* The columns whose collation the ORM cannot declare, which `db migrate`
|
|
27
|
+
* sets where the database lacks it. The settings table is left as it is:
|
|
28
|
+
* it is only read by key, and the migrator has already read it, so
|
|
29
|
+
* altering it would invalidate PostgreSQL's cached plan for that read.
|
|
30
|
+
*/
|
|
31
|
+
readonly collate?: (column: SqlColumnShape) => boolean;
|
|
22
32
|
}) => Migrator;
|
|
23
33
|
//#endregion
|
|
24
34
|
export { createSettingsMigrator };
|
|
@@ -3,6 +3,7 @@ import { HotUpdaterSchemaMigrationRequiredError, SETTINGS_TABLE, isMissingSchema
|
|
|
3
3
|
import { getEmptyMigrationResult } from "./fixedMigratorShared.mjs";
|
|
4
4
|
import { quoteSql } from "../database/sql/sqlSchema.mjs";
|
|
5
5
|
import { settingsStatements } from "./engineSql.mjs";
|
|
6
|
+
import { addColumnStatements, collationStatements, missingSqlSchema, readSqlSchemaState, targetShapes } from "./sqlSchemaState.mjs";
|
|
6
7
|
//#region src/engine/db/settingsMigrator.ts
|
|
7
8
|
/**
|
|
8
9
|
* Every settings row by key and value alone, so a v0 layout reads too; null
|
|
@@ -35,33 +36,129 @@ const refuseV0Database = (adapterName, stored) => {
|
|
|
35
36
|
if (typeof version !== "string" || stored.has("schema.engine")) return;
|
|
36
37
|
throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
|
|
37
38
|
};
|
|
39
|
+
/** Compares dotted numeric versions, such as "1" and "1.2.0"; NaN when either is not one. */
|
|
40
|
+
const compareVersions = (left, right) => {
|
|
41
|
+
const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
|
|
42
|
+
const [a, b] = [parse(left), parse(right)];
|
|
43
|
+
if ([...a, ...b].some(Number.isNaN)) return NaN;
|
|
44
|
+
for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
|
|
45
|
+
const difference = (a[index] ?? 0) - (b[index] ?? 0);
|
|
46
|
+
if (difference !== 0) return difference;
|
|
47
|
+
}
|
|
48
|
+
return 0;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* The settings whose versions only move forward when a `ToolingTarget` names
|
|
52
|
+
* none. `schema.engine` is a storage layout, not a release: a store refuses
|
|
53
|
+
* another layout itself, and doctor reports it as not migratable.
|
|
54
|
+
*/
|
|
55
|
+
const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
|
|
56
|
+
/**
|
|
57
|
+
* Refuses a database a newer release migrated, one whose `schema.core` is
|
|
58
|
+
* newer than this release's: writing this release's settings would move the
|
|
59
|
+
* schema back, and every server of the newer release would answer 503. Only
|
|
60
|
+
* `ordered` settings are compared, `schema.core` among them, and the message
|
|
61
|
+
* lists each that is newer. An official plugin's
|
|
62
|
+
* newer version alone is no newer release: Insights recorded "1.2.0" in
|
|
63
|
+
* 1.0.0-rc.23 and rc.24, then went back to "1.0.0" with the same tables.
|
|
64
|
+
*/
|
|
65
|
+
const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
|
|
66
|
+
const newer = ordered.flatMap((key) => {
|
|
67
|
+
const found = stored.get(key);
|
|
68
|
+
const expected = settings[key];
|
|
69
|
+
return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
|
|
70
|
+
key,
|
|
71
|
+
found,
|
|
72
|
+
expected
|
|
73
|
+
}] : [];
|
|
74
|
+
});
|
|
75
|
+
const core = newer.find(({ key }) => key === "schema.core");
|
|
76
|
+
if (core === void 0) return;
|
|
77
|
+
throw new Error(`${adapterName}: the database was migrated by Hot Updater ${core.found} (${newer.map(({ key, found, expected }) => `${key} "${found}", this CLI's "${expected}"`).join("; ")}). Upgrade hot-updater to ${core.found} or later; nothing was written.`);
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* The tables, late columns or indexes an ORM has yet to apply, found before `db migrate`
|
|
81
|
+
* writes the settings rows, so the fence never passes over missing tables.
|
|
82
|
+
*/
|
|
83
|
+
var HotUpdaterSchemaTablesMissingError = class extends Error {
|
|
84
|
+
adapterName;
|
|
85
|
+
missing;
|
|
86
|
+
applyTables;
|
|
87
|
+
constructor(adapterName, missing, applyTables) {
|
|
88
|
+
const all = missing.tables.includes(SETTINGS_TABLE.name);
|
|
89
|
+
const items = [
|
|
90
|
+
...missing.tables.length === 0 ? [] : [`table${missing.tables.length === 1 ? "" : "s"} ${missing.tables.join(", ")}`],
|
|
91
|
+
...missing.columns.length === 0 ? [] : [`column${missing.columns.length === 1 ? "" : "s"} ${missing.columns.map(({ table, column }) => `${table}.${column.name}`).join(", ")}`],
|
|
92
|
+
...missing.indexes.length === 0 ? [] : [`index${missing.indexes.length === 1 ? "" : "es"} ${missing.indexes.map(({ index }) => index).join(", ")}`]
|
|
93
|
+
];
|
|
94
|
+
super(`${adapterName}: ${all ? "the Hot Updater tables are missing" : `the database lacks ${items.join(" and ")}`}. Run \`hot-updater db generate\`, apply it with ${applyTables}, then migrate again.`);
|
|
95
|
+
this.adapterName = adapterName;
|
|
96
|
+
this.missing = missing;
|
|
97
|
+
this.applyTables = applyTables;
|
|
98
|
+
this.name = "HotUpdaterSchemaTablesMissingError";
|
|
99
|
+
}
|
|
100
|
+
};
|
|
38
101
|
/**
|
|
39
102
|
* `hot-updater db migrate` for an ORM that applies the DDL itself (Drizzle,
|
|
40
|
-
* Prisma)
|
|
41
|
-
*
|
|
103
|
+
* Prisma). Before it writes the settings rows it refuses a v0 database or one
|
|
104
|
+
* a newer release migrated, checks that every table and index the target
|
|
105
|
+
* declares exists, and sets the collations the ORM cannot declare on the
|
|
106
|
+
* columns that lack them. The `createMigrator` of an adapter whose ORM
|
|
42
107
|
* creates the tables returns it, as the Drizzle and Prisma adapters' do.
|
|
43
108
|
*/
|
|
44
109
|
const createSettingsMigrator = (options) => {
|
|
45
110
|
const read = () => readStoredSettings(options.executor);
|
|
46
111
|
const getVersion = async () => storedSchemaVersion(await read());
|
|
112
|
+
const { executor } = options;
|
|
47
113
|
const makeResult = async (migrate = {}) => {
|
|
48
|
-
const stored = await read();
|
|
49
|
-
if (stored === null) throw new Error(`${options.adapterName}: the Hot Updater tables are missing. Run \`hot-updater db generate\`, apply the schema with ${options.applyTables}, then migrate again.`);
|
|
114
|
+
const stored = await read() ?? /* @__PURE__ */ new Map();
|
|
50
115
|
refuseV0Database(options.adapterName, stored);
|
|
51
|
-
|
|
52
|
-
const
|
|
53
|
-
const
|
|
116
|
+
refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
|
|
117
|
+
const shapes = targetShapes(executor.dialect, options.schema);
|
|
118
|
+
const missing = missingSqlSchema(shapes, await readSqlSchemaState(executor));
|
|
119
|
+
const lateTables = new Set(missing.columns.map(({ table }) => table));
|
|
120
|
+
const lateIndexes = missing.indexes.filter(({ table }) => lateTables.has(table));
|
|
121
|
+
const blocking = missing.indexes.filter(({ table }) => !lateTables.has(table));
|
|
122
|
+
if (missing.tables.length > 0 || blocking.length > 0) throw new HotUpdaterSchemaTablesMissingError(options.adapterName, {
|
|
123
|
+
tables: missing.tables,
|
|
124
|
+
columns: [],
|
|
125
|
+
indexes: blocking
|
|
126
|
+
}, options.applyTables);
|
|
127
|
+
const quote = (name) => quoteSql(executor.dialect, name);
|
|
128
|
+
const lateSchema = [...addColumnStatements(executor.dialect, missing.columns), ...lateIndexes.map(({ table, index: name }) => {
|
|
129
|
+
const index = shapes.find((shape) => shape.name === table).indexes.find((candidate) => candidate.kind === "index" && candidate.name === name);
|
|
130
|
+
return index.kind === "index" ? `CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quote(name)} ON ${quote(table)} (${index.columns.map(quote).join(", ")})` : "";
|
|
131
|
+
})];
|
|
132
|
+
const collations = options.collate === void 0 ? {
|
|
133
|
+
statements: [],
|
|
134
|
+
columns: 0
|
|
135
|
+
} : await collationStatements(executor, shapes.filter((shape) => shape.name !== SETTINGS_TABLE.name), options.collate);
|
|
136
|
+
const changed = migrate.updateSettings === false ? [] : Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
|
|
137
|
+
if (lateSchema.length === 0 && collations.statements.length === 0 && changed.length === 0) return getEmptyMigrationResult();
|
|
138
|
+
const statements = [
|
|
139
|
+
...lateSchema,
|
|
140
|
+
...collations.statements,
|
|
141
|
+
...changed.length === 0 ? [] : settingsStatements(executor.dialect, options.settings)
|
|
142
|
+
];
|
|
54
143
|
return {
|
|
55
|
-
operations: [
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
144
|
+
operations: [
|
|
145
|
+
...missing.columns.map(({ table, column }) => ({
|
|
146
|
+
type: "custom",
|
|
147
|
+
description: `Add column: ${column.name} to ${table}`
|
|
148
|
+
})),
|
|
149
|
+
...lateIndexes.map(({ table, index }) => ({
|
|
150
|
+
type: "custom",
|
|
151
|
+
description: `Create index: ${index} on ${table}`
|
|
152
|
+
})),
|
|
153
|
+
...collations.columns === 0 ? [] : [{
|
|
154
|
+
type: "custom",
|
|
155
|
+
description: `Set the byte-order collation the ORM cannot declare on ${collations.columns} column${collations.columns === 1 ? "" : "s"} of ${collations.statements.length} table${collations.statements.length === 1 ? "" : "s"}`
|
|
156
|
+
}],
|
|
157
|
+
...changed.length === 0 ? [] : [settingsOperation(stored, changed)]
|
|
158
|
+
],
|
|
62
159
|
getSQL: () => statements.map((statement) => `${statement};`).join("\n\n"),
|
|
63
160
|
execute: async () => {
|
|
64
|
-
for (const sql of statements) await
|
|
161
|
+
for (const sql of statements) await executor.execute({
|
|
65
162
|
sql,
|
|
66
163
|
params: []
|
|
67
164
|
});
|
|
@@ -84,5 +181,13 @@ const createSettingsMigrator = (options) => {
|
|
|
84
181
|
migrateToLatest: makeResult
|
|
85
182
|
};
|
|
86
183
|
};
|
|
184
|
+
/** The settings rows a migration changes, each with its stored value. */
|
|
185
|
+
const settingsOperation = (stored, changed) => ({
|
|
186
|
+
type: "custom",
|
|
187
|
+
description: `Record ${changed.map(([key, value]) => {
|
|
188
|
+
const found = stored.get(key);
|
|
189
|
+
return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
|
|
190
|
+
}).join(", ")}`
|
|
191
|
+
});
|
|
87
192
|
//#endregion
|
|
88
|
-
export { createSettingsMigrator, readStoredSettings, refuseV0Database, storedSchemaVersion };
|
|
193
|
+
export { DEFAULT_ORDERED_SETTINGS, HotUpdaterSchemaTablesMissingError, createSettingsMigrator, readStoredSettings, refuseNewerSchema, refuseV0Database, settingsOperation, storedSchemaVersion };
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
const require_schema = require("../core/schema.cjs");
|
|
2
|
+
const require_fence = require("../database/fence.cjs");
|
|
3
|
+
const require_sqlSchema = require("../database/sql/sqlSchema.cjs");
|
|
4
|
+
//#region src/engine/db/sqlSchemaState.ts
|
|
5
|
+
/** Each table, and the index tables of its multi-valued indexes. */
|
|
6
|
+
const flattenShapes = (shapes) => shapes.flatMap((shape) => [shape, ...flattenShapes(shape.indexes.flatMap((index) => index.kind === "table" ? [index.table] : []))]);
|
|
7
|
+
/** Every table the target declares, settings table included, as the DDL creates it. */
|
|
8
|
+
const targetShapes = (dialect, schema, tablePrefix = "") => flattenShapes(require_sqlSchema.sqlTableShapes(dialect, [...schema.tables, require_fence.SETTINGS_TABLE], tablePrefix));
|
|
9
|
+
/** PostgreSQL's identifier limit, NAMEDATALEN - 1 bytes. */
|
|
10
|
+
const POSTGRES_NAME_BYTES = 63;
|
|
11
|
+
/** A name as PostgreSQL stores it: cut to its limit on a character boundary. */
|
|
12
|
+
const postgresName = (name) => {
|
|
13
|
+
const encoder = new TextEncoder();
|
|
14
|
+
let bytes = 0;
|
|
15
|
+
let cut = "";
|
|
16
|
+
for (const character of name) {
|
|
17
|
+
bytes += encoder.encode(character).length;
|
|
18
|
+
if (bytes > POSTGRES_NAME_BYTES) break;
|
|
19
|
+
cut += character;
|
|
20
|
+
}
|
|
21
|
+
return cut;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* A name as the catalog reports it, so declared and stored names compare.
|
|
25
|
+
* PostgreSQL cuts a longer name to its limit. MySQL compares index names,
|
|
26
|
+
* and with lower_case_table_names table names, without case, and reports
|
|
27
|
+
* them folded.
|
|
28
|
+
*/
|
|
29
|
+
const fold = (dialect, name) => dialect === "mysql" ? String(name).toLowerCase() : dialect === "postgresql" ? postgresName(String(name)) : String(name);
|
|
30
|
+
const CATALOG = {
|
|
31
|
+
postgresql: {
|
|
32
|
+
tables: "SELECT c.relname AS t FROM pg_class c WHERE c.relkind IN ('r', 'p') AND pg_table_is_visible(c.oid)",
|
|
33
|
+
indexes: "SELECT t.relname AS t, c.relname AS i FROM pg_index x JOIN pg_class c ON c.oid = x.indexrelid JOIN pg_class t ON t.oid = x.indrelid WHERE pg_table_is_visible(t.oid)",
|
|
34
|
+
columns: "SELECT c.relname AS t, a.attname AS c FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid WHERE c.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped AND pg_table_is_visible(c.oid)"
|
|
35
|
+
},
|
|
36
|
+
mysql: {
|
|
37
|
+
tables: "SELECT TABLE_NAME AS t FROM information_schema.tables WHERE TABLE_SCHEMA = DATABASE()",
|
|
38
|
+
indexes: "SELECT DISTINCT TABLE_NAME AS t, INDEX_NAME AS i FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE()",
|
|
39
|
+
columns: "SELECT TABLE_NAME AS t, COLUMN_NAME AS c FROM information_schema.columns WHERE TABLE_SCHEMA = DATABASE()"
|
|
40
|
+
},
|
|
41
|
+
sqlite: {
|
|
42
|
+
tables: "SELECT name AS t FROM sqlite_master WHERE type = 'table'",
|
|
43
|
+
indexes: "SELECT tbl_name AS t, name AS i FROM sqlite_master WHERE type = 'index'",
|
|
44
|
+
columns: "SELECT m.name AS t, p.name AS c FROM sqlite_master m JOIN pragma_table_info(m.name) p WHERE m.type = 'table'"
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
/** Reads which tables, indexes and columns exist: three catalog reads. */
|
|
48
|
+
const readSqlSchemaState = async (executor) => {
|
|
49
|
+
const { dialect } = executor;
|
|
50
|
+
const read = (sql) => executor.execute({
|
|
51
|
+
sql,
|
|
52
|
+
params: []
|
|
53
|
+
});
|
|
54
|
+
const [tables, indexes, columns] = await Promise.all([
|
|
55
|
+
read(CATALOG[dialect].tables),
|
|
56
|
+
read(CATALOG[dialect].indexes),
|
|
57
|
+
read(CATALOG[dialect].columns)
|
|
58
|
+
]);
|
|
59
|
+
const columnNames = new Set(columns.rows.map(({ t, c }) => JSON.stringify([fold(dialect, t), fold(dialect, c)])));
|
|
60
|
+
const tableNames = new Set(tables.rows.map(({ t }) => fold(dialect, t)));
|
|
61
|
+
const indexNames = new Set(indexes.rows.map(({ t, i }) => JSON.stringify([fold(dialect, t), fold(dialect, i)])));
|
|
62
|
+
return {
|
|
63
|
+
hasTable: (table) => tableNames.has(fold(dialect, table)),
|
|
64
|
+
hasIndex: (table, index) => indexNames.has(JSON.stringify([fold(dialect, table), fold(dialect, index)])),
|
|
65
|
+
hasColumn: (table, column) => columnNames.has(JSON.stringify([fold(dialect, table), fold(dialect, column)]))
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* The declared tables, indexes and late columns the database lacks. An index
|
|
70
|
+
* on a late column is missing too while the column is.
|
|
71
|
+
*/
|
|
72
|
+
const missingSqlSchema = (shapes, state, tablePrefix = "") => ({
|
|
73
|
+
columns: require_schema.LATE_COLUMNS.flatMap(({ table, column }) => {
|
|
74
|
+
const shape = shapes.find(({ name }) => name === tablePrefix + table);
|
|
75
|
+
const declared = shape?.columns.find(({ name }) => name === column);
|
|
76
|
+
return shape === void 0 || declared === void 0 || !state.hasTable(shape.name) || state.hasColumn(shape.name, column) ? [] : [{
|
|
77
|
+
table: shape.name,
|
|
78
|
+
column: declared
|
|
79
|
+
}];
|
|
80
|
+
}),
|
|
81
|
+
tables: shapes.filter((shape) => !state.hasTable(shape.name)).map((shape) => shape.name),
|
|
82
|
+
indexes: shapes.filter((shape) => state.hasTable(shape.name)).flatMap((shape) => shape.indexes.flatMap((index) => index.kind === "index" && !state.hasIndex(shape.name, index.name) ? [{
|
|
83
|
+
table: shape.name,
|
|
84
|
+
index: index.name
|
|
85
|
+
}] : []))
|
|
86
|
+
});
|
|
87
|
+
/** The collation a column's DDL type declares, such as `C` or `utf8mb4_0900_bin`. */
|
|
88
|
+
const declaredCollation = (type) => /COLLATE "?([\w]+)"?/u.exec(type)?.[1];
|
|
89
|
+
const COLLATIONS = {
|
|
90
|
+
postgresql: "SELECT c.relname AS t, a.attname AS c, co.collname AS k FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_collation co ON co.oid = a.attcollation WHERE c.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped AND pg_table_is_visible(c.oid)",
|
|
91
|
+
mysql: "SELECT TABLE_NAME AS t, COLUMN_NAME AS c, COLLATION_NAME AS k FROM information_schema.columns WHERE TABLE_SCHEMA = DATABASE() AND COLLATION_NAME IS NOT NULL"
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* The statements that set the collation an ORM cannot declare on each column
|
|
95
|
+
* `collate` selects whose stored collation differs, one per table: PostgreSQL
|
|
96
|
+
* `ALTER COLUMN … TYPE`, MySQL `MODIFY`. One catalog read; none on SQLite,
|
|
97
|
+
* whose text compares by bytes already.
|
|
98
|
+
*/
|
|
99
|
+
const collationStatements = async (executor, shapes, collate) => {
|
|
100
|
+
const { dialect } = executor;
|
|
101
|
+
if (dialect === "sqlite") return {
|
|
102
|
+
statements: [],
|
|
103
|
+
columns: 0
|
|
104
|
+
};
|
|
105
|
+
const { rows } = await executor.execute({
|
|
106
|
+
sql: COLLATIONS[dialect],
|
|
107
|
+
params: []
|
|
108
|
+
});
|
|
109
|
+
const stored = new Map(rows.map(({ t, c, k }) => [JSON.stringify([fold(dialect, t), fold(dialect, c)]), String(k)]));
|
|
110
|
+
const quote = (name) => require_sqlSchema.quoteSql(dialect, name);
|
|
111
|
+
let columns = 0;
|
|
112
|
+
return {
|
|
113
|
+
statements: shapes.flatMap((shape) => {
|
|
114
|
+
const changes = shape.columns.filter((column) => {
|
|
115
|
+
const expected = declaredCollation(column.type);
|
|
116
|
+
return expected !== void 0 && collate(column) && stored.get(JSON.stringify([fold(dialect, shape.name), fold(dialect, column.name)])) !== expected;
|
|
117
|
+
}).map((column) => dialect === "postgresql" ? `ALTER COLUMN ${quote(column.name)} TYPE ${column.type}` : `MODIFY ${quote(column.name)} ${column.type}${column.notNull ? " NOT NULL" : " NULL"}`);
|
|
118
|
+
columns += changes.length;
|
|
119
|
+
return changes.length === 0 ? [] : [`ALTER TABLE ${quote(shape.name)} ${changes.join(", ")}`];
|
|
120
|
+
}),
|
|
121
|
+
columns
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
/**
|
|
125
|
+
* `ALTER TABLE … ADD COLUMN` for each late column a table lacks, which run
|
|
126
|
+
* before the statements that create the table's indexes. Each is nullable,
|
|
127
|
+
* so rows written before it read as null.
|
|
128
|
+
*/
|
|
129
|
+
const addColumnStatements = (dialect, columns) => columns.map(({ table, column }) => `ALTER TABLE ${require_sqlSchema.quoteSql(dialect, table)} ADD COLUMN ${require_sqlSchema.quoteSql(dialect, column.name)} ${column.type}`);
|
|
130
|
+
//#endregion
|
|
131
|
+
exports.addColumnStatements = addColumnStatements;
|
|
132
|
+
exports.collationStatements = collationStatements;
|
|
133
|
+
exports.flattenShapes = flattenShapes;
|
|
134
|
+
exports.missingSqlSchema = missingSqlSchema;
|
|
135
|
+
exports.readSqlSchemaState = readSqlSchemaState;
|
|
136
|
+
exports.targetShapes = targetShapes;
|