@hot-updater/plugin-core 1.2.0-rc.5 → 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 (79) hide show
  1. package/dist/coreApi.d.cts +246 -10
  2. package/dist/coreApi.d.mts +246 -10
  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 +200 -5
  6. package/dist/engine/core/schema.d.cts +127 -1
  7. package/dist/engine/core/schema.d.mts +127 -1
  8. package/dist/engine/core/schema.mjs +200 -6
  9. package/dist/engine/createEngine.cjs +1 -2
  10. package/dist/engine/createEngine.d.cts +1 -6
  11. package/dist/engine/createEngine.d.mts +1 -6
  12. package/dist/engine/createEngine.mjs +1 -2
  13. package/dist/engine/database/aggregateBatching.cjs +87 -129
  14. package/dist/engine/database/aggregateBatching.mjs +87 -129
  15. package/dist/engine/database/database.cjs +1 -4
  16. package/dist/engine/database/database.mjs +1 -4
  17. package/dist/engine/database/engineTransaction.cjs +21 -1
  18. package/dist/engine/database/engineTransaction.d.cts +5 -1
  19. package/dist/engine/database/engineTransaction.d.mts +5 -1
  20. package/dist/engine/database/engineTransaction.mjs +21 -1
  21. package/dist/engine/database/kv/kvAdapter.cjs +80 -4
  22. package/dist/engine/database/kv/kvAdapter.mjs +80 -4
  23. package/dist/engine/database/resolveSchema.cjs +6 -3
  24. package/dist/engine/database/resolveSchema.mjs +6 -3
  25. package/dist/engine/database/sql/sqlAdapter.cjs +9 -4
  26. package/dist/engine/database/sql/sqlAdapter.mjs +9 -4
  27. package/dist/engine/database/sql/sqlSchema.cjs +24 -6
  28. package/dist/engine/database/sql/sqlSchema.d.cts +1 -1
  29. package/dist/engine/database/sql/sqlSchema.d.mts +1 -1
  30. package/dist/engine/database/sql/sqlSchema.mjs +24 -6
  31. package/dist/engine/db/coreDatabase.cjs +10 -5
  32. package/dist/engine/db/coreDatabase.d.cts +2 -1
  33. package/dist/engine/db/coreDatabase.d.mts +2 -1
  34. package/dist/engine/db/coreDatabase.mjs +10 -5
  35. package/dist/engine/db/engineMigrator.cjs +21 -16
  36. package/dist/engine/db/engineMigrator.mjs +22 -17
  37. package/dist/engine/db/engineSqlMigrator.cjs +53 -20
  38. package/dist/engine/db/engineSqlMigrator.d.cts +2 -0
  39. package/dist/engine/db/engineSqlMigrator.d.mts +2 -0
  40. package/dist/engine/db/engineSqlMigrator.mjs +55 -22
  41. package/dist/engine/db/schemaSettings.cjs +36 -5
  42. package/dist/engine/db/schemaSettings.d.cts +5 -2
  43. package/dist/engine/db/schemaSettings.d.mts +5 -2
  44. package/dist/engine/db/schemaSettings.mjs +36 -6
  45. package/dist/engine/db/settingsMigrator.cjs +92 -14
  46. package/dist/engine/db/settingsMigrator.d.cts +18 -8
  47. package/dist/engine/db/settingsMigrator.d.mts +18 -8
  48. package/dist/engine/db/settingsMigrator.mjs +89 -15
  49. package/dist/engine/db/sqlSchemaState.cjs +108 -0
  50. package/dist/engine/db/sqlSchemaState.mjs +104 -0
  51. package/dist/engine/db/types.d.cts +6 -0
  52. package/dist/engine/db/types.d.mts +6 -0
  53. package/dist/index.cjs +2 -8
  54. package/dist/index.d.cts +5 -6
  55. package/dist/index.d.mts +5 -6
  56. package/dist/index.mjs +3 -4
  57. package/dist/serverPlugin/coreReads.d.cts +10 -1
  58. package/dist/serverPlugin/coreReads.d.mts +10 -1
  59. package/dist/serverPlugin/definitions.d.cts +4 -0
  60. package/dist/serverPlugin/definitions.d.mts +4 -0
  61. package/dist/serverPlugin/schema.d.cts +4 -0
  62. package/dist/serverPlugin/schema.d.mts +4 -0
  63. package/dist/types/databaseConfig.d.cts +10 -20
  64. package/dist/types/databaseConfig.d.mts +10 -20
  65. package/dist/types/databaseRows.d.cts +70 -2
  66. package/dist/types/databaseRows.d.mts +70 -2
  67. package/dist/types/index.cjs +3 -0
  68. package/dist/types/index.d.cts +114 -56
  69. package/dist/types/index.d.mts +114 -56
  70. package/dist/types/index.mjs +3 -1
  71. package/dist/types/models.d.cts +9 -1
  72. package/dist/types/models.d.mts +9 -1
  73. package/dist/types/public.d.cts +3 -3
  74. package/dist/types/public.d.mts +3 -3
  75. package/package.json +3 -9
  76. package/dist/remoteBundleSigning.cjs +0 -357
  77. package/dist/remoteBundleSigning.d.cts +0 -38
  78. package/dist/remoteBundleSigning.d.mts +0 -38
  79. package/dist/remoteBundleSigning.mjs +0 -352
@@ -1,17 +1,44 @@
1
1
  const require_schema = require("../core/schema.cjs");
2
+ const require_fence = require("../database/fence.cjs");
2
3
  const require_fixedMigratorShared = require("./fixedMigratorShared.cjs");
4
+ const require_sqlSchema = require("../database/sql/sqlSchema.cjs");
3
5
  const require_engineSql = require("./engineSql.cjs");
6
+ const require_sqlSchemaState = require("./sqlSchemaState.cjs");
4
7
  const require_settingsMigrator = require("./settingsMigrator.cjs");
5
8
  //#region src/engine/db/engineSqlMigrator.ts
6
- /** Runs the statements in one transaction where the dialect's DDL is transactional. */
7
- const run = async (executor, statements) => {
8
- const each = async (connection) => {
9
- for (const sql of statements) await connection.execute({
9
+ /**
10
+ * MySQL declares a table's indexes in its CREATE TABLE, which a table an
11
+ * earlier release created skips, and has no CREATE INDEX IF NOT EXISTS: the
12
+ * indexes the tables lack, created one by one.
13
+ */
14
+ const missingMysqlIndexes = async (executor, schema, tablePrefix) => {
15
+ const quote = (name) => require_sqlSchema.quoteSql("mysql", name);
16
+ const shapes = require_sqlSchemaState.targetShapes("mysql", schema, tablePrefix);
17
+ return require_sqlSchemaState.missingSqlSchema(shapes, await require_sqlSchemaState.readSqlSchemaState(executor)).indexes.map(({ table, index: name }) => {
18
+ const index = shapes.find((shape) => shape.name === table).indexes.find((candidate) => candidate.kind === "index" && candidate.name === name);
19
+ return `CREATE ${index.kind === "index" && index.unique ? "UNIQUE " : ""}INDEX ${quote(name)} ON ${quote(table)} (${index.kind === "index" ? index.columns.map(quote).join(", ") : ""})`;
20
+ });
21
+ };
22
+ /**
23
+ * Runs the tables' statements, then the settings rows last, in one
24
+ * transaction where the dialect's DDL is transactional. On MySQL the indexes
25
+ * existing tables lack go between them, so the settings move only once
26
+ * every index exists.
27
+ */
28
+ const run = async (executor, tables, settings, schema, tablePrefix) => {
29
+ const each = async (connection, sqls) => {
30
+ for (const sql of sqls) await connection.execute({
10
31
  sql,
11
32
  params: []
12
33
  });
13
34
  };
14
- await (executor.dialect === "mysql" ? each(executor) : executor.transaction(each));
35
+ if (executor.dialect !== "mysql") {
36
+ await executor.transaction((connection) => each(connection, [...tables, ...settings]));
37
+ return;
38
+ }
39
+ await each(executor, tables);
40
+ await each(executor, await missingMysqlIndexes(executor, schema, tablePrefix));
41
+ await each(executor, settings);
15
42
  };
16
43
  /**
17
44
  * `hot-updater db migrate` and `db generate` for an SQL provider on the
@@ -26,24 +53,30 @@ const createEngineSqlMigrator = (options) => {
26
53
  const makeResult = async (migrate = {}) => {
27
54
  const stored = await read();
28
55
  require_settingsMigrator.refuseV0Database(options.adapterName, stored);
29
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return require_fixedMigratorShared.getEmptyMigrationResult();
56
+ require_settingsMigrator.refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
57
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
58
+ if (changed.length === 0) return require_fixedMigratorShared.getEmptyMigrationResult();
30
59
  const statements = require_engineSql.generateEngineSql(options.executor.dialect, options.schema, options.settings, options);
60
+ const settingsSql = require_engineSql.settingsStatements(options.executor.dialect, options.settings, options.tablePrefix);
61
+ const tablesSql = statements.slice(0, -settingsSql.length || void 0);
62
+ const missing = require_sqlSchemaState.missingSqlSchema(require_sqlSchemaState.targetShapes(options.executor.dialect, options.schema, options.tablePrefix).filter((shape) => shape.name !== (options.tablePrefix ?? "") + require_fence.SETTINGS_TABLE.name), await require_sqlSchemaState.readSqlSchemaState(options.executor));
31
63
  return {
32
- operations: [...options.schema.tables.map((table) => ({
33
- type: "create-table",
34
- value: {
35
- ormName: table.name,
36
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
37
- ormName: column.name,
38
- type: column.type
39
- }]))
40
- }
41
- })), ...migrate.updateSettings === false ? [] : [{
42
- type: "custom",
43
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
44
- }]],
64
+ operations: [
65
+ ...missing.tables.map((table) => ({
66
+ type: "create-table",
67
+ value: {
68
+ ormName: table,
69
+ columns: {}
70
+ }
71
+ })),
72
+ ...missing.indexes.map(({ table, index }) => ({
73
+ type: "custom",
74
+ description: `Create index: ${index} on ${table}`
75
+ })),
76
+ ...migrate.updateSettings === false ? [] : [require_settingsMigrator.settingsOperation(stored, changed)]
77
+ ],
45
78
  getSQL: () => statements.map((statement) => `${statement};`).join("\n\n"),
46
- execute: () => run(options.executor, statements)
79
+ execute: () => run(options.executor, tablesSql, settingsSql, options.schema, options.tablePrefix)
47
80
  };
48
81
  };
49
82
  return {
@@ -9,6 +9,8 @@ interface EngineSqlMigratorOptions extends EngineSqlOptions {
9
9
  readonly executor: SqlExecutor;
10
10
  readonly schema: ResolvedSchema;
11
11
  readonly settings: SchemaSettings;
12
+ /** The settings whose versions only move forward; `ToolingTarget.ordered`. */
13
+ readonly ordered?: readonly string[];
12
14
  }
13
15
  /**
14
16
  * `hot-updater db migrate` and `db generate` for an SQL provider on the
@@ -9,6 +9,8 @@ interface EngineSqlMigratorOptions extends EngineSqlOptions {
9
9
  readonly executor: SqlExecutor;
10
10
  readonly schema: ResolvedSchema;
11
11
  readonly settings: SchemaSettings;
12
+ /** The settings whose versions only move forward; `ToolingTarget.ordered`. */
13
+ readonly ordered?: readonly string[];
12
14
  }
13
15
  /**
14
16
  * `hot-updater db migrate` and `db generate` for an SQL provider on the
@@ -1,17 +1,44 @@
1
1
  import { HOT_UPDATER_SCHEMA_VERSION } from "../core/schema.mjs";
2
+ import { SETTINGS_TABLE } from "../database/fence.mjs";
2
3
  import { getEmptyMigrationResult } from "./fixedMigratorShared.mjs";
3
- import { generateEngineSql } from "./engineSql.mjs";
4
- import { readStoredSettings, refuseV0Database, storedSchemaVersion } from "./settingsMigrator.mjs";
4
+ import { quoteSql } from "../database/sql/sqlSchema.mjs";
5
+ import { generateEngineSql, settingsStatements } from "./engineSql.mjs";
6
+ import { missingSqlSchema, readSqlSchemaState, targetShapes } from "./sqlSchemaState.mjs";
7
+ import { readStoredSettings, refuseNewerSchema, refuseV0Database, settingsOperation, storedSchemaVersion } from "./settingsMigrator.mjs";
5
8
  //#region src/engine/db/engineSqlMigrator.ts
6
- /** Runs the statements in one transaction where the dialect's DDL is transactional. */
7
- const run = async (executor, statements) => {
8
- const each = async (connection) => {
9
- for (const sql of statements) await connection.execute({
9
+ /**
10
+ * MySQL declares a table's indexes in its CREATE TABLE, which a table an
11
+ * earlier release created skips, and has no CREATE INDEX IF NOT EXISTS: the
12
+ * indexes the tables lack, created one by one.
13
+ */
14
+ const missingMysqlIndexes = async (executor, schema, tablePrefix) => {
15
+ const quote = (name) => quoteSql("mysql", name);
16
+ const shapes = targetShapes("mysql", schema, tablePrefix);
17
+ return missingSqlSchema(shapes, await readSqlSchemaState(executor)).indexes.map(({ table, index: name }) => {
18
+ const index = shapes.find((shape) => shape.name === table).indexes.find((candidate) => candidate.kind === "index" && candidate.name === name);
19
+ return `CREATE ${index.kind === "index" && index.unique ? "UNIQUE " : ""}INDEX ${quote(name)} ON ${quote(table)} (${index.kind === "index" ? index.columns.map(quote).join(", ") : ""})`;
20
+ });
21
+ };
22
+ /**
23
+ * Runs the tables' statements, then the settings rows last, in one
24
+ * transaction where the dialect's DDL is transactional. On MySQL the indexes
25
+ * existing tables lack go between them, so the settings move only once
26
+ * every index exists.
27
+ */
28
+ const run = async (executor, tables, settings, schema, tablePrefix) => {
29
+ const each = async (connection, sqls) => {
30
+ for (const sql of sqls) await connection.execute({
10
31
  sql,
11
32
  params: []
12
33
  });
13
34
  };
14
- await (executor.dialect === "mysql" ? each(executor) : executor.transaction(each));
35
+ if (executor.dialect !== "mysql") {
36
+ await executor.transaction((connection) => each(connection, [...tables, ...settings]));
37
+ return;
38
+ }
39
+ await each(executor, tables);
40
+ await each(executor, await missingMysqlIndexes(executor, schema, tablePrefix));
41
+ await each(executor, settings);
15
42
  };
16
43
  /**
17
44
  * `hot-updater db migrate` and `db generate` for an SQL provider on the
@@ -26,24 +53,30 @@ const createEngineSqlMigrator = (options) => {
26
53
  const makeResult = async (migrate = {}) => {
27
54
  const stored = await read();
28
55
  refuseV0Database(options.adapterName, stored);
29
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
56
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
57
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
58
+ if (changed.length === 0) return getEmptyMigrationResult();
30
59
  const statements = generateEngineSql(options.executor.dialect, options.schema, options.settings, options);
60
+ const settingsSql = settingsStatements(options.executor.dialect, options.settings, options.tablePrefix);
61
+ const tablesSql = statements.slice(0, -settingsSql.length || void 0);
62
+ const missing = missingSqlSchema(targetShapes(options.executor.dialect, options.schema, options.tablePrefix).filter((shape) => shape.name !== (options.tablePrefix ?? "") + SETTINGS_TABLE.name), await readSqlSchemaState(options.executor));
31
63
  return {
32
- operations: [...options.schema.tables.map((table) => ({
33
- type: "create-table",
34
- value: {
35
- ormName: table.name,
36
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
37
- ormName: column.name,
38
- type: column.type
39
- }]))
40
- }
41
- })), ...migrate.updateSettings === false ? [] : [{
42
- type: "custom",
43
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
44
- }]],
64
+ operations: [
65
+ ...missing.tables.map((table) => ({
66
+ type: "create-table",
67
+ value: {
68
+ ormName: table,
69
+ columns: {}
70
+ }
71
+ })),
72
+ ...missing.indexes.map(({ table, index }) => ({
73
+ type: "custom",
74
+ description: `Create index: ${index} on ${table}`
75
+ })),
76
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]
77
+ ],
45
78
  getSQL: () => statements.map((statement) => `${statement};`).join("\n\n"),
46
- execute: () => run(options.executor, statements)
79
+ execute: () => run(options.executor, tablesSql, settingsSql, options.schema, options.tablePrefix)
47
80
  };
48
81
  };
49
82
  return {
@@ -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,37 @@ 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
+ * Creates or updates every table, writes the late indexes' missing items,
58
+ * then writes the settings rows last. A database a newer release migrated is
59
+ * refused before anything is written: its settings are read first, and a
60
+ * store without them yet, whose read fails, has none to refuse.
61
+ */
62
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
36
63
  if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
64
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
65
+ if (stored !== void 0) require_settingsMigrator.refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
37
66
  await adapter.migrations.apply([...tables, require_fence.SETTINGS_TABLE]);
38
- await writeSchemaSettings(adapter, adapterName, settings);
67
+ await fillLateIndexes(adapter, tables);
68
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
39
69
  };
40
70
  //#endregion
71
+ exports.fillLateIndexes = fillLateIndexes;
41
72
  exports.migrateSchema = migrateSchema;
42
73
  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_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,35 @@ 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
+ * Creates or updates every table, writes the late indexes' missing items,
58
+ * then writes the settings rows last. A database a newer release migrated is
59
+ * refused before anything is written: its settings are read first, and a
60
+ * store without them yet, whose read fails, has none to refuse.
61
+ */
62
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
36
63
  if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
64
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
65
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
37
66
  await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
38
- await writeSchemaSettings(adapter, adapterName, settings);
67
+ await fillLateIndexes(adapter, tables);
68
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
39
69
  };
40
70
  //#endregion
41
- export { migrateSchema, writeSchemaSettings };
71
+ export { 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,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 };