@hot-updater/plugin-core 1.2.0-rc.49 → 1.2.0-rc.50

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 (47) hide show
  1. package/dist/coreApi.d.cts +20 -1
  2. package/dist/coreApi.d.mts +20 -1
  3. package/dist/database/adapter.d.cts +12 -0
  4. package/dist/database/adapter.d.mts +12 -0
  5. package/dist/engine/core/schema.cjs +21 -2
  6. package/dist/engine/core/schema.d.cts +4 -0
  7. package/dist/engine/core/schema.d.mts +4 -0
  8. package/dist/engine/core/schema.mjs +21 -3
  9. package/dist/engine/database/engineTransaction.cjs +21 -1
  10. package/dist/engine/database/engineTransaction.d.cts +5 -1
  11. package/dist/engine/database/engineTransaction.d.mts +5 -1
  12. package/dist/engine/database/engineTransaction.mjs +21 -1
  13. package/dist/engine/database/kv/kvAdapter.cjs +80 -4
  14. package/dist/engine/database/kv/kvAdapter.mjs +80 -4
  15. package/dist/engine/database/sql/sqlSchema.cjs +6 -2
  16. package/dist/engine/database/sql/sqlSchema.d.cts +1 -1
  17. package/dist/engine/database/sql/sqlSchema.d.mts +1 -1
  18. package/dist/engine/database/sql/sqlSchema.mjs +6 -2
  19. package/dist/engine/db/coreDatabase.cjs +10 -5
  20. package/dist/engine/db/coreDatabase.d.cts +2 -1
  21. package/dist/engine/db/coreDatabase.d.mts +2 -1
  22. package/dist/engine/db/coreDatabase.mjs +10 -5
  23. package/dist/engine/db/engineMigrator.cjs +21 -16
  24. package/dist/engine/db/engineMigrator.mjs +22 -17
  25. package/dist/engine/db/engineSqlMigrator.cjs +23 -22
  26. package/dist/engine/db/engineSqlMigrator.d.cts +2 -0
  27. package/dist/engine/db/engineSqlMigrator.d.mts +2 -0
  28. package/dist/engine/db/engineSqlMigrator.mjs +25 -24
  29. package/dist/engine/db/schemaSettings.cjs +36 -5
  30. package/dist/engine/db/schemaSettings.d.cts +5 -2
  31. package/dist/engine/db/schemaSettings.d.mts +5 -2
  32. package/dist/engine/db/schemaSettings.mjs +36 -6
  33. package/dist/engine/db/settingsMigrator.cjs +92 -14
  34. package/dist/engine/db/settingsMigrator.d.cts +18 -8
  35. package/dist/engine/db/settingsMigrator.d.mts +18 -8
  36. package/dist/engine/db/settingsMigrator.mjs +89 -15
  37. package/dist/engine/db/sqlSchemaState.cjs +108 -0
  38. package/dist/engine/db/sqlSchemaState.mjs +104 -0
  39. package/dist/engine/db/types.d.cts +6 -0
  40. package/dist/engine/db/types.d.mts +6 -0
  41. package/dist/index.cjs +1 -1
  42. package/dist/index.mjs +1 -1
  43. package/dist/serverPlugin/coreReads.d.cts +10 -1
  44. package/dist/serverPlugin/coreReads.d.mts +10 -1
  45. package/dist/types/databaseConfig.d.cts +2 -1
  46. package/dist/types/databaseConfig.d.mts +2 -1
  47. package/package.json +2 -2
@@ -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,98 @@ 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 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 = [...missing.tables.length === 0 ? [] : [`table${missing.tables.length === 1 ? "" : "s"} ${missing.tables.join(", ")}`], ...missing.indexes.length === 0 ? [] : [`index${missing.indexes.length === 1 ? "" : "es"} ${missing.indexes.map(({ index }) => index).join(", ")}`]];
90
+ 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.`);
91
+ this.adapterName = adapterName;
92
+ this.missing = missing;
93
+ this.applyTables = applyTables;
94
+ this.name = "HotUpdaterSchemaTablesMissingError";
95
+ }
96
+ };
38
97
  /**
39
98
  * `hot-updater db migrate` for an ORM that applies the DDL itself (Drizzle,
40
- * Prisma): it sets what the ORM cannot declare, writes the settings rows, and
41
- * refuses a v0 database. The `createMigrator` of an adapter whose ORM
99
+ * Prisma). Before it writes the settings rows it refuses a v0 database or one
100
+ * a newer release migrated, checks that every table and index the target
101
+ * declares exists, and sets the collations the ORM cannot declare on the
102
+ * columns that lack them. The `createMigrator` of an adapter whose ORM
42
103
  * creates the tables returns it, as the Drizzle and Prisma adapters' do.
43
104
  */
44
105
  const createSettingsMigrator = (options) => {
45
106
  const read = () => readStoredSettings(options.executor);
46
107
  const getVersion = async () => storedSchemaVersion(await read());
108
+ const { executor } = options;
47
109
  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.`);
110
+ const stored = await read() ?? /* @__PURE__ */ new Map();
50
111
  refuseV0Database(options.adapterName, stored);
51
- if (migrate.updateSettings === false || Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return require_fixedMigratorShared.getEmptyMigrationResult();
52
- const fixups = options.fixups?.statements ?? [];
53
- const statements = [...fixups, ...require_engineSql.settingsStatements(options.executor.dialect, options.settings)];
112
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
113
+ const shapes = require_sqlSchemaState.targetShapes(executor.dialect, options.schema);
114
+ const missing = require_sqlSchemaState.missingSqlSchema(shapes, await require_sqlSchemaState.readSqlSchemaState(executor));
115
+ if (missing.tables.length > 0 || missing.indexes.length > 0) throw new HotUpdaterSchemaTablesMissingError(options.adapterName, missing, options.applyTables);
116
+ const collations = options.collate === void 0 ? {
117
+ statements: [],
118
+ columns: 0
119
+ } : await require_sqlSchemaState.collationStatements(executor, shapes.filter((shape) => shape.name !== require_fence.SETTINGS_TABLE.name), options.collate);
120
+ const changed = migrate.updateSettings === false ? [] : Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
121
+ if (collations.statements.length === 0 && changed.length === 0) return require_fixedMigratorShared.getEmptyMigrationResult();
122
+ const statements = [...collations.statements, ...changed.length === 0 ? [] : require_engineSql.settingsStatements(executor.dialect, options.settings)];
54
123
  return {
55
- operations: [...fixups.length === 0 ? [] : [{
56
- type: "custom",
57
- description: options.fixups.description
58
- }], {
124
+ operations: [...collations.columns === 0 ? [] : [{
59
125
  type: "custom",
60
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
61
- }],
126
+ 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"}`
127
+ }], ...changed.length === 0 ? [] : [settingsOperation(stored, changed)]],
62
128
  getSQL: () => statements.map((statement) => `${statement};`).join("\n\n"),
63
129
  execute: async () => {
64
- for (const sql of statements) await options.executor.execute({
130
+ for (const sql of statements) await executor.execute({
65
131
  sql,
66
132
  params: []
67
133
  });
@@ -84,8 +150,20 @@ const createSettingsMigrator = (options) => {
84
150
  migrateToLatest: makeResult
85
151
  };
86
152
  };
153
+ /** The settings rows a migration changes, each with its stored value. */
154
+ const settingsOperation = (stored, changed) => ({
155
+ type: "custom",
156
+ description: `Record ${changed.map(([key, value]) => {
157
+ const found = stored.get(key);
158
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
159
+ }).join(", ")}`
160
+ });
87
161
  //#endregion
162
+ exports.DEFAULT_ORDERED_SETTINGS = DEFAULT_ORDERED_SETTINGS;
163
+ exports.HotUpdaterSchemaTablesMissingError = HotUpdaterSchemaTablesMissingError;
88
164
  exports.createSettingsMigrator = createSettingsMigrator;
89
165
  exports.readStoredSettings = readStoredSettings;
166
+ exports.refuseNewerSchema = refuseNewerSchema;
90
167
  exports.refuseV0Database = refuseV0Database;
168
+ exports.settingsOperation = settingsOperation;
91
169
  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): it sets what the ORM cannot declare, writes the settings rows, and
8
- * refuses a v0 database. The `createMigrator` of an adapter whose ORM
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
- /** How the ORM applies the tables, for the error when they are missing. */
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
- /** What the ORM cannot declare, set before the settings rows. */
18
- readonly fixups?: {
19
- readonly description: string;
20
- readonly statements: readonly string[];
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): it sets what the ORM cannot declare, writes the settings rows, and
8
- * refuses a v0 database. The `createMigrator` of an adapter whose ORM
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
- /** How the ORM applies the tables, for the error when they are missing. */
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
- /** What the ORM cannot declare, set before the settings rows. */
18
- readonly fixups?: {
19
- readonly description: string;
20
- readonly statements: readonly string[];
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 { 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,98 @@ 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 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 = [...missing.tables.length === 0 ? [] : [`table${missing.tables.length === 1 ? "" : "s"} ${missing.tables.join(", ")}`], ...missing.indexes.length === 0 ? [] : [`index${missing.indexes.length === 1 ? "" : "es"} ${missing.indexes.map(({ index }) => index).join(", ")}`]];
90
+ 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.`);
91
+ this.adapterName = adapterName;
92
+ this.missing = missing;
93
+ this.applyTables = applyTables;
94
+ this.name = "HotUpdaterSchemaTablesMissingError";
95
+ }
96
+ };
38
97
  /**
39
98
  * `hot-updater db migrate` for an ORM that applies the DDL itself (Drizzle,
40
- * Prisma): it sets what the ORM cannot declare, writes the settings rows, and
41
- * refuses a v0 database. The `createMigrator` of an adapter whose ORM
99
+ * Prisma). Before it writes the settings rows it refuses a v0 database or one
100
+ * a newer release migrated, checks that every table and index the target
101
+ * declares exists, and sets the collations the ORM cannot declare on the
102
+ * columns that lack them. The `createMigrator` of an adapter whose ORM
42
103
  * creates the tables returns it, as the Drizzle and Prisma adapters' do.
43
104
  */
44
105
  const createSettingsMigrator = (options) => {
45
106
  const read = () => readStoredSettings(options.executor);
46
107
  const getVersion = async () => storedSchemaVersion(await read());
108
+ const { executor } = options;
47
109
  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.`);
110
+ const stored = await read() ?? /* @__PURE__ */ new Map();
50
111
  refuseV0Database(options.adapterName, stored);
51
- if (migrate.updateSettings === false || Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
52
- const fixups = options.fixups?.statements ?? [];
53
- const statements = [...fixups, ...settingsStatements(options.executor.dialect, options.settings)];
112
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
113
+ const shapes = targetShapes(executor.dialect, options.schema);
114
+ const missing = missingSqlSchema(shapes, await readSqlSchemaState(executor));
115
+ if (missing.tables.length > 0 || missing.indexes.length > 0) throw new HotUpdaterSchemaTablesMissingError(options.adapterName, missing, options.applyTables);
116
+ const collations = options.collate === void 0 ? {
117
+ statements: [],
118
+ columns: 0
119
+ } : await collationStatements(executor, shapes.filter((shape) => shape.name !== SETTINGS_TABLE.name), options.collate);
120
+ const changed = migrate.updateSettings === false ? [] : Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
121
+ if (collations.statements.length === 0 && changed.length === 0) return getEmptyMigrationResult();
122
+ const statements = [...collations.statements, ...changed.length === 0 ? [] : settingsStatements(executor.dialect, options.settings)];
54
123
  return {
55
- operations: [...fixups.length === 0 ? [] : [{
56
- type: "custom",
57
- description: options.fixups.description
58
- }], {
124
+ operations: [...collations.columns === 0 ? [] : [{
59
125
  type: "custom",
60
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
61
- }],
126
+ 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"}`
127
+ }], ...changed.length === 0 ? [] : [settingsOperation(stored, changed)]],
62
128
  getSQL: () => statements.map((statement) => `${statement};`).join("\n\n"),
63
129
  execute: async () => {
64
- for (const sql of statements) await options.executor.execute({
130
+ for (const sql of statements) await executor.execute({
65
131
  sql,
66
132
  params: []
67
133
  });
@@ -84,5 +150,13 @@ const createSettingsMigrator = (options) => {
84
150
  migrateToLatest: makeResult
85
151
  };
86
152
  };
153
+ /** The settings rows a migration changes, each with its stored value. */
154
+ const settingsOperation = (stored, changed) => ({
155
+ type: "custom",
156
+ description: `Record ${changed.map(([key, value]) => {
157
+ const found = stored.get(key);
158
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
159
+ }).join(", ")}`
160
+ });
87
161
  //#endregion
88
- export { createSettingsMigrator, readStoredSettings, refuseV0Database, storedSchemaVersion };
162
+ export { DEFAULT_ORDERED_SETTINGS, HotUpdaterSchemaTablesMissingError, createSettingsMigrator, readStoredSettings, refuseNewerSchema, refuseV0Database, settingsOperation, storedSchemaVersion };
@@ -0,0 +1,108 @@
1
+ const require_fence = require("../database/fence.cjs");
2
+ const require_sqlSchema = require("../database/sql/sqlSchema.cjs");
3
+ //#region src/engine/db/sqlSchemaState.ts
4
+ /** Each table, and the index tables of its multi-valued indexes. */
5
+ const flattenShapes = (shapes) => shapes.flatMap((shape) => [shape, ...flattenShapes(shape.indexes.flatMap((index) => index.kind === "table" ? [index.table] : []))]);
6
+ /** Every table the target declares, settings table included, as the DDL creates it. */
7
+ const targetShapes = (dialect, schema, tablePrefix = "") => flattenShapes(require_sqlSchema.sqlTableShapes(dialect, [...schema.tables, require_fence.SETTINGS_TABLE], tablePrefix));
8
+ /** PostgreSQL's identifier limit, NAMEDATALEN - 1 bytes. */
9
+ const POSTGRES_NAME_BYTES = 63;
10
+ /** A name as PostgreSQL stores it: cut to its limit on a character boundary. */
11
+ const postgresName = (name) => {
12
+ const encoder = new TextEncoder();
13
+ let bytes = 0;
14
+ let cut = "";
15
+ for (const character of name) {
16
+ bytes += encoder.encode(character).length;
17
+ if (bytes > POSTGRES_NAME_BYTES) break;
18
+ cut += character;
19
+ }
20
+ return cut;
21
+ };
22
+ /**
23
+ * A name as the catalog reports it, so declared and stored names compare.
24
+ * PostgreSQL cuts a longer name to its limit. MySQL compares index names,
25
+ * and with lower_case_table_names table names, without case, and reports
26
+ * them folded.
27
+ */
28
+ const fold = (dialect, name) => dialect === "mysql" ? String(name).toLowerCase() : dialect === "postgresql" ? postgresName(String(name)) : String(name);
29
+ const CATALOG = {
30
+ postgresql: {
31
+ tables: "SELECT c.relname AS t FROM pg_class c WHERE c.relkind IN ('r', 'p') AND pg_table_is_visible(c.oid)",
32
+ 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)"
33
+ },
34
+ mysql: {
35
+ tables: "SELECT TABLE_NAME AS t FROM information_schema.tables WHERE TABLE_SCHEMA = DATABASE()",
36
+ indexes: "SELECT DISTINCT TABLE_NAME AS t, INDEX_NAME AS i FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE()"
37
+ },
38
+ sqlite: {
39
+ tables: "SELECT name AS t FROM sqlite_master WHERE type = 'table'",
40
+ indexes: "SELECT tbl_name AS t, name AS i FROM sqlite_master WHERE type = 'index'"
41
+ }
42
+ };
43
+ /** Reads which tables and indexes exist: two catalog reads. */
44
+ const readSqlSchemaState = async (executor) => {
45
+ const { dialect } = executor;
46
+ const read = (sql) => executor.execute({
47
+ sql,
48
+ params: []
49
+ });
50
+ const [tables, indexes] = await Promise.all([read(CATALOG[dialect].tables), read(CATALOG[dialect].indexes)]);
51
+ const tableNames = new Set(tables.rows.map(({ t }) => fold(dialect, t)));
52
+ const indexNames = new Set(indexes.rows.map(({ t, i }) => JSON.stringify([fold(dialect, t), fold(dialect, i)])));
53
+ return {
54
+ hasTable: (table) => tableNames.has(fold(dialect, table)),
55
+ hasIndex: (table, index) => indexNames.has(JSON.stringify([fold(dialect, table), fold(dialect, index)]))
56
+ };
57
+ };
58
+ /** The declared tables and indexes the database lacks. */
59
+ const missingSqlSchema = (shapes, state) => ({
60
+ tables: shapes.filter((shape) => !state.hasTable(shape.name)).map((shape) => shape.name),
61
+ indexes: shapes.filter((shape) => state.hasTable(shape.name)).flatMap((shape) => shape.indexes.flatMap((index) => index.kind === "index" && !state.hasIndex(shape.name, index.name) ? [{
62
+ table: shape.name,
63
+ index: index.name
64
+ }] : []))
65
+ });
66
+ /** The collation a column's DDL type declares, such as `C` or `utf8mb4_0900_bin`. */
67
+ const declaredCollation = (type) => /COLLATE "?([\w]+)"?/u.exec(type)?.[1];
68
+ const COLLATIONS = {
69
+ 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)",
70
+ 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"
71
+ };
72
+ /**
73
+ * The statements that set the collation an ORM cannot declare on each column
74
+ * `collate` selects whose stored collation differs, one per table: PostgreSQL
75
+ * `ALTER COLUMN … TYPE`, MySQL `MODIFY`. One catalog read; none on SQLite,
76
+ * whose text compares by bytes already.
77
+ */
78
+ const collationStatements = async (executor, shapes, collate) => {
79
+ const { dialect } = executor;
80
+ if (dialect === "sqlite") return {
81
+ statements: [],
82
+ columns: 0
83
+ };
84
+ const { rows } = await executor.execute({
85
+ sql: COLLATIONS[dialect],
86
+ params: []
87
+ });
88
+ const stored = new Map(rows.map(({ t, c, k }) => [JSON.stringify([fold(dialect, t), fold(dialect, c)]), String(k)]));
89
+ const quote = (name) => require_sqlSchema.quoteSql(dialect, name);
90
+ let columns = 0;
91
+ return {
92
+ statements: shapes.flatMap((shape) => {
93
+ const changes = shape.columns.filter((column) => {
94
+ const expected = declaredCollation(column.type);
95
+ return expected !== void 0 && collate(column) && stored.get(JSON.stringify([fold(dialect, shape.name), fold(dialect, column.name)])) !== expected;
96
+ }).map((column) => dialect === "postgresql" ? `ALTER COLUMN ${quote(column.name)} TYPE ${column.type}` : `MODIFY ${quote(column.name)} ${column.type}${column.notNull ? " NOT NULL" : " NULL"}`);
97
+ columns += changes.length;
98
+ return changes.length === 0 ? [] : [`ALTER TABLE ${quote(shape.name)} ${changes.join(", ")}`];
99
+ }),
100
+ columns
101
+ };
102
+ };
103
+ //#endregion
104
+ exports.collationStatements = collationStatements;
105
+ exports.flattenShapes = flattenShapes;
106
+ exports.missingSqlSchema = missingSqlSchema;
107
+ exports.readSqlSchemaState = readSqlSchemaState;
108
+ exports.targetShapes = targetShapes;
@@ -0,0 +1,104 @@
1
+ import { SETTINGS_TABLE } from "../database/fence.mjs";
2
+ import { quoteSql, sqlTableShapes } from "../database/sql/sqlSchema.mjs";
3
+ //#region src/engine/db/sqlSchemaState.ts
4
+ /** Each table, and the index tables of its multi-valued indexes. */
5
+ const flattenShapes = (shapes) => shapes.flatMap((shape) => [shape, ...flattenShapes(shape.indexes.flatMap((index) => index.kind === "table" ? [index.table] : []))]);
6
+ /** Every table the target declares, settings table included, as the DDL creates it. */
7
+ const targetShapes = (dialect, schema, tablePrefix = "") => flattenShapes(sqlTableShapes(dialect, [...schema.tables, SETTINGS_TABLE], tablePrefix));
8
+ /** PostgreSQL's identifier limit, NAMEDATALEN - 1 bytes. */
9
+ const POSTGRES_NAME_BYTES = 63;
10
+ /** A name as PostgreSQL stores it: cut to its limit on a character boundary. */
11
+ const postgresName = (name) => {
12
+ const encoder = new TextEncoder();
13
+ let bytes = 0;
14
+ let cut = "";
15
+ for (const character of name) {
16
+ bytes += encoder.encode(character).length;
17
+ if (bytes > POSTGRES_NAME_BYTES) break;
18
+ cut += character;
19
+ }
20
+ return cut;
21
+ };
22
+ /**
23
+ * A name as the catalog reports it, so declared and stored names compare.
24
+ * PostgreSQL cuts a longer name to its limit. MySQL compares index names,
25
+ * and with lower_case_table_names table names, without case, and reports
26
+ * them folded.
27
+ */
28
+ const fold = (dialect, name) => dialect === "mysql" ? String(name).toLowerCase() : dialect === "postgresql" ? postgresName(String(name)) : String(name);
29
+ const CATALOG = {
30
+ postgresql: {
31
+ tables: "SELECT c.relname AS t FROM pg_class c WHERE c.relkind IN ('r', 'p') AND pg_table_is_visible(c.oid)",
32
+ 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)"
33
+ },
34
+ mysql: {
35
+ tables: "SELECT TABLE_NAME AS t FROM information_schema.tables WHERE TABLE_SCHEMA = DATABASE()",
36
+ indexes: "SELECT DISTINCT TABLE_NAME AS t, INDEX_NAME AS i FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE()"
37
+ },
38
+ sqlite: {
39
+ tables: "SELECT name AS t FROM sqlite_master WHERE type = 'table'",
40
+ indexes: "SELECT tbl_name AS t, name AS i FROM sqlite_master WHERE type = 'index'"
41
+ }
42
+ };
43
+ /** Reads which tables and indexes exist: two catalog reads. */
44
+ const readSqlSchemaState = async (executor) => {
45
+ const { dialect } = executor;
46
+ const read = (sql) => executor.execute({
47
+ sql,
48
+ params: []
49
+ });
50
+ const [tables, indexes] = await Promise.all([read(CATALOG[dialect].tables), read(CATALOG[dialect].indexes)]);
51
+ const tableNames = new Set(tables.rows.map(({ t }) => fold(dialect, t)));
52
+ const indexNames = new Set(indexes.rows.map(({ t, i }) => JSON.stringify([fold(dialect, t), fold(dialect, i)])));
53
+ return {
54
+ hasTable: (table) => tableNames.has(fold(dialect, table)),
55
+ hasIndex: (table, index) => indexNames.has(JSON.stringify([fold(dialect, table), fold(dialect, index)]))
56
+ };
57
+ };
58
+ /** The declared tables and indexes the database lacks. */
59
+ const missingSqlSchema = (shapes, state) => ({
60
+ tables: shapes.filter((shape) => !state.hasTable(shape.name)).map((shape) => shape.name),
61
+ indexes: shapes.filter((shape) => state.hasTable(shape.name)).flatMap((shape) => shape.indexes.flatMap((index) => index.kind === "index" && !state.hasIndex(shape.name, index.name) ? [{
62
+ table: shape.name,
63
+ index: index.name
64
+ }] : []))
65
+ });
66
+ /** The collation a column's DDL type declares, such as `C` or `utf8mb4_0900_bin`. */
67
+ const declaredCollation = (type) => /COLLATE "?([\w]+)"?/u.exec(type)?.[1];
68
+ const COLLATIONS = {
69
+ 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)",
70
+ 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"
71
+ };
72
+ /**
73
+ * The statements that set the collation an ORM cannot declare on each column
74
+ * `collate` selects whose stored collation differs, one per table: PostgreSQL
75
+ * `ALTER COLUMN … TYPE`, MySQL `MODIFY`. One catalog read; none on SQLite,
76
+ * whose text compares by bytes already.
77
+ */
78
+ const collationStatements = async (executor, shapes, collate) => {
79
+ const { dialect } = executor;
80
+ if (dialect === "sqlite") return {
81
+ statements: [],
82
+ columns: 0
83
+ };
84
+ const { rows } = await executor.execute({
85
+ sql: COLLATIONS[dialect],
86
+ params: []
87
+ });
88
+ const stored = new Map(rows.map(({ t, c, k }) => [JSON.stringify([fold(dialect, t), fold(dialect, c)]), String(k)]));
89
+ const quote = (name) => quoteSql(dialect, name);
90
+ let columns = 0;
91
+ return {
92
+ statements: shapes.flatMap((shape) => {
93
+ const changes = shape.columns.filter((column) => {
94
+ const expected = declaredCollation(column.type);
95
+ return expected !== void 0 && collate(column) && stored.get(JSON.stringify([fold(dialect, shape.name), fold(dialect, column.name)])) !== expected;
96
+ }).map((column) => dialect === "postgresql" ? `ALTER COLUMN ${quote(column.name)} TYPE ${column.type}` : `MODIFY ${quote(column.name)} ${column.type}${column.notNull ? " NOT NULL" : " NULL"}`);
97
+ columns += changes.length;
98
+ return changes.length === 0 ? [] : [`ALTER TABLE ${quote(shape.name)} ${changes.join(", ")}`];
99
+ }),
100
+ columns
101
+ };
102
+ };
103
+ //#endregion
104
+ export { collationStatements, flattenShapes, missingSqlSchema, readSqlSchemaState, targetShapes };
@@ -56,6 +56,12 @@ interface Migrator {
56
56
  interface ToolingTarget {
57
57
  readonly schema: ResolvedSchema;
58
58
  readonly settings: SchemaSettings;
59
+ /**
60
+ * The settings keys whose versions only move forward: core's and the
61
+ * official plugins'. A migrator refuses a database that
62
+ * recorded a newer one than `settings` instead of writing it back.
63
+ */
64
+ readonly ordered?: readonly string[];
59
65
  }
60
66
  type SchemaGenerator = (version: string | "latest", name?: string, target?: ToolingTarget) => {
61
67
  code: string;
@@ -56,6 +56,12 @@ interface Migrator {
56
56
  interface ToolingTarget {
57
57
  readonly schema: ResolvedSchema;
58
58
  readonly settings: SchemaSettings;
59
+ /**
60
+ * The settings keys whose versions only move forward: core's and the
61
+ * official plugins'. A migrator refuses a database that
62
+ * recorded a newer one than `settings` instead of writing it back.
63
+ */
64
+ readonly ordered?: readonly string[];
59
65
  }
60
66
  type SchemaGenerator = (version: string | "latest", name?: string, target?: ToolingTarget) => {
61
67
  code: string;
package/dist/index.cjs CHANGED
@@ -30,10 +30,10 @@ const require_memoryAdapter = require("./database/memoryAdapter.cjs");
30
30
  const require_verifyAdapter = require("./database/verifyAdapter.cjs");
31
31
  const require_fence = require("./engine/database/fence.cjs");
32
32
  const require_readMeter = require("./engine/database/readMeter.cjs");
33
- const require_schemaSettings = require("./engine/db/schemaSettings.cjs");
34
33
  const require_sqlSchema = require("./engine/database/sql/sqlSchema.cjs");
35
34
  const require_engineSql = require("./engine/db/engineSql.cjs");
36
35
  const require_settingsMigrator = require("./engine/db/settingsMigrator.cjs");
36
+ const require_schemaSettings = require("./engine/db/schemaSettings.cjs");
37
37
  const require_coreDatabase = require("./engine/db/coreDatabase.cjs");
38
38
  const require_createEngine = require("./engine/createEngine.cjs");
39
39
  const require_kvAdapter = require("./engine/database/kv/kvAdapter.cjs");
package/dist/index.mjs CHANGED
@@ -29,10 +29,10 @@ import { createMemoryAdapter } from "./database/memoryAdapter.mjs";
29
29
  import { DatabaseAdapterContractError, verifyAdapter } from "./database/verifyAdapter.mjs";
30
30
  import { HotUpdaterSchemaMigrationRequiredError, SETTINGS_TABLE } from "./engine/database/fence.mjs";
31
31
  import { meterReads } from "./engine/database/readMeter.mjs";
32
- import { writeSchemaSettings } from "./engine/db/schemaSettings.mjs";
33
32
  import { createTableStatements, isMultiIndex, quoteSql, sqlTableShapes } from "./engine/database/sql/sqlSchema.mjs";
34
33
  import { generateEngineSql } from "./engine/db/engineSql.mjs";
35
34
  import { createSettingsMigrator } from "./engine/db/settingsMigrator.mjs";
35
+ import { writeSchemaSettings } from "./engine/db/schemaSettings.mjs";
36
36
  import { aggregateBatchingTables, coreSchema, coreSettings, coreTarget, createEngineDatabase, migrateCoreSchema, toolingTargetOf } from "./engine/db/coreDatabase.mjs";
37
37
  import { createEngine } from "./engine/createEngine.mjs";
38
38
  import { createKvAdapter, encodeKvKey } from "./engine/database/kv/kvAdapter.mjs";