@hot-updater/plugin-core 1.2.0-rc.6 → 1.2.0-rc.60

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 (95) hide show
  1. package/dist/coreApi.d.cts +277 -10
  2. package/dist/coreApi.d.mts +277 -10
  3. package/dist/database/adapter.d.cts +24 -0
  4. package/dist/database/adapter.d.mts +24 -0
  5. package/dist/databaseRows.cjs +4 -2
  6. package/dist/databaseRows.mjs +4 -2
  7. package/dist/engine/core/schema.cjs +253 -6
  8. package/dist/engine/core/schema.d.cts +154 -1
  9. package/dist/engine/core/schema.d.mts +154 -1
  10. package/dist/engine/core/schema.mjs +252 -7
  11. package/dist/engine/createEngine.cjs +1 -2
  12. package/dist/engine/createEngine.d.cts +1 -6
  13. package/dist/engine/createEngine.d.mts +1 -6
  14. package/dist/engine/createEngine.mjs +1 -2
  15. package/dist/engine/database/aggregateBatching.cjs +87 -129
  16. package/dist/engine/database/aggregateBatching.mjs +87 -129
  17. package/dist/engine/database/database.cjs +1 -4
  18. package/dist/engine/database/database.mjs +1 -4
  19. package/dist/engine/database/engineTransaction.cjs +26 -2
  20. package/dist/engine/database/engineTransaction.d.cts +5 -1
  21. package/dist/engine/database/engineTransaction.d.mts +5 -1
  22. package/dist/engine/database/engineTransaction.mjs +26 -2
  23. package/dist/engine/database/fence.cjs +24 -2
  24. package/dist/engine/database/fence.d.cts +4 -1
  25. package/dist/engine/database/fence.d.mts +4 -1
  26. package/dist/engine/database/fence.mjs +24 -3
  27. package/dist/engine/database/kv/kvAdapter.cjs +80 -4
  28. package/dist/engine/database/kv/kvAdapter.mjs +80 -4
  29. package/dist/engine/database/resolveSchema.cjs +6 -3
  30. package/dist/engine/database/resolveSchema.mjs +6 -3
  31. package/dist/engine/database/sql/sqlAdapter.cjs +36 -12
  32. package/dist/engine/database/sql/sqlAdapter.mjs +37 -13
  33. package/dist/engine/database/sql/sqlSchema.cjs +24 -6
  34. package/dist/engine/database/sql/sqlSchema.d.cts +1 -1
  35. package/dist/engine/database/sql/sqlSchema.d.mts +1 -1
  36. package/dist/engine/database/sql/sqlSchema.mjs +24 -6
  37. package/dist/engine/db/coreDatabase.cjs +10 -5
  38. package/dist/engine/db/coreDatabase.d.cts +2 -1
  39. package/dist/engine/db/coreDatabase.d.mts +2 -1
  40. package/dist/engine/db/coreDatabase.mjs +10 -5
  41. package/dist/engine/db/engineMigrator.cjs +45 -17
  42. package/dist/engine/db/engineMigrator.mjs +46 -18
  43. package/dist/engine/db/engineSql.cjs +25 -0
  44. package/dist/engine/db/engineSql.d.cts +13 -1
  45. package/dist/engine/db/engineSql.d.mts +13 -1
  46. package/dist/engine/db/engineSql.mjs +26 -2
  47. package/dist/engine/db/engineSqlMigrator.cjs +60 -21
  48. package/dist/engine/db/engineSqlMigrator.d.cts +2 -0
  49. package/dist/engine/db/engineSqlMigrator.d.mts +2 -0
  50. package/dist/engine/db/engineSqlMigrator.mjs +62 -23
  51. package/dist/engine/db/schemaSettings.cjs +56 -5
  52. package/dist/engine/db/schemaSettings.d.cts +5 -2
  53. package/dist/engine/db/schemaSettings.d.mts +5 -2
  54. package/dist/engine/db/schemaSettings.mjs +55 -6
  55. package/dist/engine/db/settingsMigrator.cjs +113 -15
  56. package/dist/engine/db/settingsMigrator.d.cts +18 -8
  57. package/dist/engine/db/settingsMigrator.d.mts +18 -8
  58. package/dist/engine/db/settingsMigrator.mjs +111 -17
  59. package/dist/engine/db/sqlSchemaState.cjs +136 -0
  60. package/dist/engine/db/sqlSchemaState.mjs +131 -0
  61. package/dist/engine/db/types.d.cts +6 -0
  62. package/dist/engine/db/types.d.mts +6 -0
  63. package/dist/index.cjs +4 -8
  64. package/dist/index.d.cts +7 -8
  65. package/dist/index.d.mts +7 -8
  66. package/dist/index.mjs +5 -6
  67. package/dist/releaseCatalogCompiler.cjs +89 -7
  68. package/dist/releaseCatalogCompiler.d.cts +12 -1
  69. package/dist/releaseCatalogCompiler.d.mts +12 -1
  70. package/dist/releaseCatalogCompiler.mjs +89 -8
  71. package/dist/releaseCatalogMutation.d.cts +8 -2
  72. package/dist/releaseCatalogMutation.d.mts +8 -2
  73. package/dist/serverPlugin/coreReads.d.cts +10 -1
  74. package/dist/serverPlugin/coreReads.d.mts +10 -1
  75. package/dist/serverPlugin/definitions.d.cts +4 -0
  76. package/dist/serverPlugin/definitions.d.mts +4 -0
  77. package/dist/serverPlugin/schema.d.cts +4 -0
  78. package/dist/serverPlugin/schema.d.mts +4 -0
  79. package/dist/types/databaseConfig.d.cts +10 -20
  80. package/dist/types/databaseConfig.d.mts +10 -20
  81. package/dist/types/databaseRows.d.cts +77 -2
  82. package/dist/types/databaseRows.d.mts +77 -2
  83. package/dist/types/index.cjs +3 -0
  84. package/dist/types/index.d.cts +114 -56
  85. package/dist/types/index.d.mts +114 -56
  86. package/dist/types/index.mjs +3 -1
  87. package/dist/types/models.d.cts +9 -1
  88. package/dist/types/models.d.mts +9 -1
  89. package/dist/types/public.d.cts +3 -3
  90. package/dist/types/public.d.mts +3 -3
  91. package/package.json +3 -9
  92. package/dist/remoteBundleSigning.cjs +0 -357
  93. package/dist/remoteBundleSigning.d.cts +0 -38
  94. package/dist/remoteBundleSigning.d.mts +0 -38
  95. package/dist/remoteBundleSigning.mjs +0 -352
@@ -1,12 +1,18 @@
1
+ const require_schema = require("../core/schema.cjs");
1
2
  const require_fence = require("../database/fence.cjs");
3
+ const require_settingsMigrator = require("./settingsMigrator.cjs");
2
4
  //#region src/engine/db/schemaSettings.ts
3
5
  const storedSettings = async (adapter, keys) => {
4
6
  const rows = await require_fence.readSettings(adapter, keys);
5
7
  return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
6
8
  };
7
- /** Writes the settings rows after every table exists. */
8
- const writeSchemaSettings = async (adapter, adapterName, settings) => {
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
+ require_settingsMigrator.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,12 +37,57 @@ 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
- /** Creates or updates every table, then writes the settings rows last. */
35
- const migrateSchema = async (adapter, adapterName, tables, settings) => {
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 require_schema.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 = require_schema.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) require_settingsMigrator.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, require_fence.SETTINGS_TABLE]);
38
- await writeSchemaSettings(adapter, adapterName, settings);
86
+ await fillLateIndexes(adapter, tables);
87
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
39
88
  };
40
89
  //#endregion
90
+ exports.addLateColumns = addLateColumns;
91
+ exports.fillLateIndexes = fillLateIndexes;
41
92
  exports.migrateSchema = migrateSchema;
42
93
  exports.writeSchemaSettings = writeSchemaSettings;
@@ -1,7 +1,10 @@
1
1
  import { DatabaseAdapter } from "../../database/adapter.cjs";
2
2
  import { SchemaSettings } from "../database/fence.cjs";
3
3
  //#region src/engine/db/schemaSettings.d.ts
4
- /** Writes the settings rows after every table exists. */
5
- declare const writeSchemaSettings: (adapter: DatabaseAdapter, adapterName: string, settings: SchemaSettings) => Promise<void>;
4
+ /**
5
+ * Writes the settings rows after every table exists, and refuses a database
6
+ * whose `ordered` settings a newer release recorded.
7
+ */
8
+ declare const writeSchemaSettings: (adapter: DatabaseAdapter, adapterName: string, settings: SchemaSettings, ordered?: readonly string[]) => Promise<void>;
6
9
  //#endregion
7
10
  export { writeSchemaSettings };
@@ -1,7 +1,10 @@
1
1
  import { DatabaseAdapter } from "../../database/adapter.mjs";
2
2
  import { SchemaSettings } from "../database/fence.mjs";
3
3
  //#region src/engine/db/schemaSettings.d.ts
4
- /** Writes the settings rows after every table exists. */
5
- declare const writeSchemaSettings: (adapter: DatabaseAdapter, adapterName: string, settings: SchemaSettings) => Promise<void>;
4
+ /**
5
+ * Writes the settings rows after every table exists, and refuses a database
6
+ * whose `ordered` settings a newer release recorded.
7
+ */
8
+ declare const writeSchemaSettings: (adapter: DatabaseAdapter, adapterName: string, settings: SchemaSettings, ordered?: readonly string[]) => Promise<void>;
6
9
  //#endregion
7
10
  export { writeSchemaSettings };
@@ -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
- /** Writes the settings rows after every table exists. */
8
- const writeSchemaSettings = async (adapter, adapterName, settings) => {
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
- /** Creates or updates every table, then writes the settings rows last. */
35
- const migrateSchema = async (adapter, adapterName, tables, settings) => {
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 writeSchemaSettings(adapter, adapterName, settings);
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
@@ -36,32 +37,117 @@ const refuseV0Database = (adapterName, stored) => {
36
37
  throw new require_fence.HotUpdaterSchemaMigrationRequiredError(adapterName, version);
37
38
  };
38
39
  /**
40
+ * The settings whose versions only move forward when a `ToolingTarget` names
41
+ * none. `schema.engine` is a storage layout, not a release: a store refuses
42
+ * another layout itself, and doctor reports it as not migratable.
43
+ */
44
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
45
+ /**
46
+ * Refuses a database a newer release migrated, one whose `schema.core` is
47
+ * newer than this release's: writing this release's settings would move the
48
+ * schema back, and every server of the newer release would answer 503. Only
49
+ * `ordered` settings are compared, `schema.core` among them, and the message
50
+ * lists each that is newer. An official plugin's
51
+ * newer version alone is no newer release: Insights recorded "1.2.0" in
52
+ * 1.0.0-rc.23 and rc.24, then went back to "1.0.0" with the same tables.
53
+ */
54
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
55
+ const newer = ordered.flatMap((key) => {
56
+ const found = stored.get(key);
57
+ const expected = settings[key];
58
+ return typeof found === "string" && expected !== void 0 && require_fence.compareVersions(found, expected) > 0 ? [{
59
+ key,
60
+ found,
61
+ expected
62
+ }] : [];
63
+ });
64
+ const core = newer.find(({ key }) => key === "schema.core");
65
+ if (core === void 0) return;
66
+ 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.`);
67
+ };
68
+ /**
69
+ * The tables, late columns or indexes an ORM has yet to apply, found before `db migrate`
70
+ * writes the settings rows, so the fence never passes over missing tables.
71
+ */
72
+ var HotUpdaterSchemaTablesMissingError = class extends Error {
73
+ adapterName;
74
+ missing;
75
+ applyTables;
76
+ constructor(adapterName, missing, applyTables) {
77
+ const all = missing.tables.includes(require_fence.SETTINGS_TABLE.name);
78
+ const items = [
79
+ ...missing.tables.length === 0 ? [] : [`table${missing.tables.length === 1 ? "" : "s"} ${missing.tables.join(", ")}`],
80
+ ...missing.columns.length === 0 ? [] : [`column${missing.columns.length === 1 ? "" : "s"} ${missing.columns.map(({ table, column }) => `${table}.${column.name}`).join(", ")}`],
81
+ ...missing.indexes.length === 0 ? [] : [`index${missing.indexes.length === 1 ? "" : "es"} ${missing.indexes.map(({ index }) => index).join(", ")}`]
82
+ ];
83
+ 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.`);
84
+ this.adapterName = adapterName;
85
+ this.missing = missing;
86
+ this.applyTables = applyTables;
87
+ this.name = "HotUpdaterSchemaTablesMissingError";
88
+ }
89
+ };
90
+ /**
39
91
  * `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
92
+ * Prisma). Before it writes the settings rows it refuses a v0 database or one
93
+ * a newer release migrated, checks that every table and index the target
94
+ * declares exists, and sets the collations the ORM cannot declare on the
95
+ * columns that lack them. The `createMigrator` of an adapter whose ORM
42
96
  * creates the tables returns it, as the Drizzle and Prisma adapters' do.
43
97
  */
44
98
  const createSettingsMigrator = (options) => {
45
99
  const read = () => readStoredSettings(options.executor);
46
100
  const getVersion = async () => storedSchemaVersion(await read());
101
+ const { executor } = options;
47
102
  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.`);
103
+ const stored = await read() ?? /* @__PURE__ */ new Map();
50
104
  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)];
105
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
106
+ const shapes = require_sqlSchemaState.targetShapes(executor.dialect, options.schema);
107
+ const missing = require_sqlSchemaState.missingSqlSchema(shapes, await require_sqlSchemaState.readSqlSchemaState(executor));
108
+ const lateTables = new Set(missing.columns.map(({ table }) => table));
109
+ const lateIndexes = missing.indexes.filter(({ table }) => lateTables.has(table));
110
+ const blocking = missing.indexes.filter(({ table }) => !lateTables.has(table));
111
+ if (missing.tables.length > 0 || blocking.length > 0) throw new HotUpdaterSchemaTablesMissingError(options.adapterName, {
112
+ tables: missing.tables,
113
+ columns: [],
114
+ indexes: blocking
115
+ }, options.applyTables);
116
+ const quote = (name) => require_sqlSchema.quoteSql(executor.dialect, name);
117
+ const lateSchema = [...require_sqlSchemaState.addColumnStatements(executor.dialect, missing.columns), ...lateIndexes.map(({ table, index: name }) => {
118
+ const index = shapes.find((shape) => shape.name === table).indexes.find((candidate) => candidate.kind === "index" && candidate.name === name);
119
+ return index.kind === "index" ? `CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quote(name)} ON ${quote(table)} (${index.columns.map(quote).join(", ")})` : "";
120
+ })];
121
+ const collations = options.collate === void 0 ? {
122
+ statements: [],
123
+ columns: 0
124
+ } : await require_sqlSchemaState.collationStatements(executor, shapes.filter((shape) => shape.name !== require_fence.SETTINGS_TABLE.name), options.collate);
125
+ const changed = migrate.updateSettings === false ? [] : Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
126
+ if (lateSchema.length === 0 && collations.statements.length === 0 && changed.length === 0) return require_fixedMigratorShared.getEmptyMigrationResult();
127
+ const statements = [
128
+ ...lateSchema,
129
+ ...collations.statements,
130
+ ...changed.length === 0 ? [] : require_engineSql.settingsStatements(executor.dialect, options.settings)
131
+ ];
54
132
  return {
55
- operations: [...fixups.length === 0 ? [] : [{
56
- type: "custom",
57
- description: options.fixups.description
58
- }], {
59
- type: "custom",
60
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
61
- }],
133
+ operations: [
134
+ ...missing.columns.map(({ table, column }) => ({
135
+ type: "custom",
136
+ description: `Add column: ${column.name} to ${table}`
137
+ })),
138
+ ...lateIndexes.map(({ table, index }) => ({
139
+ type: "custom",
140
+ description: `Create index: ${index} on ${table}`
141
+ })),
142
+ ...collations.columns === 0 ? [] : [{
143
+ type: "custom",
144
+ 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"}`
145
+ }],
146
+ ...changed.length === 0 ? [] : [settingsOperation(stored, changed)]
147
+ ],
62
148
  getSQL: () => statements.map((statement) => `${statement};`).join("\n\n"),
63
149
  execute: async () => {
64
- for (const sql of statements) await options.executor.execute({
150
+ for (const sql of statements) await executor.execute({
65
151
  sql,
66
152
  params: []
67
153
  });
@@ -84,8 +170,20 @@ const createSettingsMigrator = (options) => {
84
170
  migrateToLatest: makeResult
85
171
  };
86
172
  };
173
+ /** The settings rows a migration changes, each with its stored value. */
174
+ const settingsOperation = (stored, changed) => ({
175
+ type: "custom",
176
+ description: `Record ${changed.map(([key, value]) => {
177
+ const found = stored.get(key);
178
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
179
+ }).join(", ")}`
180
+ });
87
181
  //#endregion
182
+ exports.DEFAULT_ORDERED_SETTINGS = DEFAULT_ORDERED_SETTINGS;
183
+ exports.HotUpdaterSchemaTablesMissingError = HotUpdaterSchemaTablesMissingError;
88
184
  exports.createSettingsMigrator = createSettingsMigrator;
89
185
  exports.readStoredSettings = readStoredSettings;
186
+ exports.refuseNewerSchema = refuseNewerSchema;
90
187
  exports.refuseV0Database = refuseV0Database;
188
+ exports.settingsOperation = settingsOperation;
91
189
  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 };
@@ -1,8 +1,9 @@
1
1
  import { HOT_UPDATER_SCHEMA_VERSION } from "../core/schema.mjs";
2
- import { HotUpdaterSchemaMigrationRequiredError, SETTINGS_TABLE, isMissingSchemaError } from "../database/fence.mjs";
2
+ import { HotUpdaterSchemaMigrationRequiredError, SETTINGS_TABLE, compareVersions, isMissingSchemaError } from "../database/fence.mjs";
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
@@ -36,32 +37,117 @@ const refuseV0Database = (adapterName, stored) => {
36
37
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
37
38
  };
38
39
  /**
40
+ * The settings whose versions only move forward when a `ToolingTarget` names
41
+ * none. `schema.engine` is a storage layout, not a release: a store refuses
42
+ * another layout itself, and doctor reports it as not migratable.
43
+ */
44
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
45
+ /**
46
+ * Refuses a database a newer release migrated, one whose `schema.core` is
47
+ * newer than this release's: writing this release's settings would move the
48
+ * schema back, and every server of the newer release would answer 503. Only
49
+ * `ordered` settings are compared, `schema.core` among them, and the message
50
+ * lists each that is newer. An official plugin's
51
+ * newer version alone is no newer release: Insights recorded "1.2.0" in
52
+ * 1.0.0-rc.23 and rc.24, then went back to "1.0.0" with the same tables.
53
+ */
54
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
55
+ const newer = ordered.flatMap((key) => {
56
+ const found = stored.get(key);
57
+ const expected = settings[key];
58
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
59
+ key,
60
+ found,
61
+ expected
62
+ }] : [];
63
+ });
64
+ const core = newer.find(({ key }) => key === "schema.core");
65
+ if (core === void 0) return;
66
+ 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.`);
67
+ };
68
+ /**
69
+ * The tables, late columns or indexes an ORM has yet to apply, found before `db migrate`
70
+ * writes the settings rows, so the fence never passes over missing tables.
71
+ */
72
+ var HotUpdaterSchemaTablesMissingError = class extends Error {
73
+ adapterName;
74
+ missing;
75
+ applyTables;
76
+ constructor(adapterName, missing, applyTables) {
77
+ const all = missing.tables.includes(SETTINGS_TABLE.name);
78
+ const items = [
79
+ ...missing.tables.length === 0 ? [] : [`table${missing.tables.length === 1 ? "" : "s"} ${missing.tables.join(", ")}`],
80
+ ...missing.columns.length === 0 ? [] : [`column${missing.columns.length === 1 ? "" : "s"} ${missing.columns.map(({ table, column }) => `${table}.${column.name}`).join(", ")}`],
81
+ ...missing.indexes.length === 0 ? [] : [`index${missing.indexes.length === 1 ? "" : "es"} ${missing.indexes.map(({ index }) => index).join(", ")}`]
82
+ ];
83
+ 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.`);
84
+ this.adapterName = adapterName;
85
+ this.missing = missing;
86
+ this.applyTables = applyTables;
87
+ this.name = "HotUpdaterSchemaTablesMissingError";
88
+ }
89
+ };
90
+ /**
39
91
  * `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
92
+ * Prisma). Before it writes the settings rows it refuses a v0 database or one
93
+ * a newer release migrated, checks that every table and index the target
94
+ * declares exists, and sets the collations the ORM cannot declare on the
95
+ * columns that lack them. The `createMigrator` of an adapter whose ORM
42
96
  * creates the tables returns it, as the Drizzle and Prisma adapters' do.
43
97
  */
44
98
  const createSettingsMigrator = (options) => {
45
99
  const read = () => readStoredSettings(options.executor);
46
100
  const getVersion = async () => storedSchemaVersion(await read());
101
+ const { executor } = options;
47
102
  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.`);
103
+ const stored = await read() ?? /* @__PURE__ */ new Map();
50
104
  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)];
105
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
106
+ const shapes = targetShapes(executor.dialect, options.schema);
107
+ const missing = missingSqlSchema(shapes, await readSqlSchemaState(executor));
108
+ const lateTables = new Set(missing.columns.map(({ table }) => table));
109
+ const lateIndexes = missing.indexes.filter(({ table }) => lateTables.has(table));
110
+ const blocking = missing.indexes.filter(({ table }) => !lateTables.has(table));
111
+ if (missing.tables.length > 0 || blocking.length > 0) throw new HotUpdaterSchemaTablesMissingError(options.adapterName, {
112
+ tables: missing.tables,
113
+ columns: [],
114
+ indexes: blocking
115
+ }, options.applyTables);
116
+ const quote = (name) => quoteSql(executor.dialect, name);
117
+ const lateSchema = [...addColumnStatements(executor.dialect, missing.columns), ...lateIndexes.map(({ table, index: name }) => {
118
+ const index = shapes.find((shape) => shape.name === table).indexes.find((candidate) => candidate.kind === "index" && candidate.name === name);
119
+ return index.kind === "index" ? `CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quote(name)} ON ${quote(table)} (${index.columns.map(quote).join(", ")})` : "";
120
+ })];
121
+ const collations = options.collate === void 0 ? {
122
+ statements: [],
123
+ columns: 0
124
+ } : await collationStatements(executor, shapes.filter((shape) => shape.name !== SETTINGS_TABLE.name), options.collate);
125
+ const changed = migrate.updateSettings === false ? [] : Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
126
+ if (lateSchema.length === 0 && collations.statements.length === 0 && changed.length === 0) return getEmptyMigrationResult();
127
+ const statements = [
128
+ ...lateSchema,
129
+ ...collations.statements,
130
+ ...changed.length === 0 ? [] : settingsStatements(executor.dialect, options.settings)
131
+ ];
54
132
  return {
55
- operations: [...fixups.length === 0 ? [] : [{
56
- type: "custom",
57
- description: options.fixups.description
58
- }], {
59
- type: "custom",
60
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
61
- }],
133
+ operations: [
134
+ ...missing.columns.map(({ table, column }) => ({
135
+ type: "custom",
136
+ description: `Add column: ${column.name} to ${table}`
137
+ })),
138
+ ...lateIndexes.map(({ table, index }) => ({
139
+ type: "custom",
140
+ description: `Create index: ${index} on ${table}`
141
+ })),
142
+ ...collations.columns === 0 ? [] : [{
143
+ type: "custom",
144
+ 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"}`
145
+ }],
146
+ ...changed.length === 0 ? [] : [settingsOperation(stored, changed)]
147
+ ],
62
148
  getSQL: () => statements.map((statement) => `${statement};`).join("\n\n"),
63
149
  execute: async () => {
64
- for (const sql of statements) await options.executor.execute({
150
+ for (const sql of statements) await executor.execute({
65
151
  sql,
66
152
  params: []
67
153
  });
@@ -84,5 +170,13 @@ const createSettingsMigrator = (options) => {
84
170
  migrateToLatest: makeResult
85
171
  };
86
172
  };
173
+ /** The settings rows a migration changes, each with its stored value. */
174
+ const settingsOperation = (stored, changed) => ({
175
+ type: "custom",
176
+ description: `Record ${changed.map(([key, value]) => {
177
+ const found = stored.get(key);
178
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
179
+ }).join(", ")}`
180
+ });
87
181
  //#endregion
88
- export { createSettingsMigrator, readStoredSettings, refuseV0Database, storedSchemaVersion };
182
+ export { DEFAULT_ORDERED_SETTINGS, HotUpdaterSchemaTablesMissingError, createSettingsMigrator, readStoredSettings, refuseNewerSchema, refuseV0Database, settingsOperation, storedSchemaVersion };