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

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
@@ -15,8 +15,11 @@ const coreSettings = {
15
15
  /** What `hot-updater db` creates for a server without plugins. */
16
16
  const coreTarget = {
17
17
  schema: coreSchema,
18
- settings: coreSettings
18
+ settings: coreSettings,
19
+ ordered: ["schema.core"]
19
20
  };
21
+ /** The brand Hot Updater's own plugin factories set, read as the server reads it. */
22
+ const isOfficialPlugin = (plugin) => Reflect.get(plugin, Symbol.for("@hot-updater/server/official-plugin")) === true;
20
23
  /**
21
24
  * The log and lease tables a database with `aggregateBatching` writes
22
25
  * beside core's and the plugins', which a provider's access policy names,
@@ -40,15 +43,16 @@ const toolingTargetOf = (plugins) => plugins.length === 0 ? coreTarget : {
40
43
  settings: {
41
44
  ...coreSettings,
42
45
  ...pluginSettings(plugins)
43
- }
46
+ },
47
+ ordered: [...coreTarget.ordered, ...plugins.flatMap((plugin) => isOfficialPlugin(plugin) ? [`schema.${plugin.id}`] : [])]
44
48
  };
45
49
  /**
46
50
  * Creates core's tables and those of `plugins`, then writes their settings
47
51
  * rows: what a provider's setup runs for the plugins its server runs.
48
52
  */
49
53
  const migrateCoreSchema = (adapter, name, plugins = []) => {
50
- const { schema, settings } = toolingTargetOf(plugins);
51
- return require_schemaSettings.migrateSchema(adapter, name, schema.tables, settings);
54
+ const { schema, settings, ordered } = toolingTargetOf(plugins);
55
+ return require_schemaSettings.migrateSchema(adapter, name, schema.tables, settings, ordered);
52
56
  };
53
57
  /**
54
58
  * A provider's database on the storage engine: its adapter behind the schema
@@ -59,11 +63,12 @@ const migrateCoreSchema = (adapter, name, plugins = []) => {
59
63
  */
60
64
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
61
65
  const fenced = require_fence.withSchemaFence(adapter, name, coreSettings);
62
- const createMigrator = ({ schema, settings } = coreTarget) => require_engineMigrator.createEngineMigrator({
66
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => require_engineMigrator.createEngineMigrator({
63
67
  adapterName: name,
64
68
  adapter,
65
69
  schema,
66
70
  settings,
71
+ ordered,
67
72
  readSettings: readStored ?? (async () => {
68
73
  const rows = await require_fence.readSettings(adapter, Object.keys(settings)).catch((error) => {
69
74
  if (require_fence.isMissingSchemaError(error)) return [];
@@ -55,7 +55,8 @@ interface EngineDatabaseOptions {
55
55
  /**
56
56
  * How a transaction that conflicts with another write runs again: more
57
57
  * attempts for a store many writers contend on, and `onRetry` to observe
58
- * each rerun. 8 attempts by default.
58
+ * each rerun. 8 attempts by default; an aggregate write that lost to
59
+ * another writer's commit is resent without spending one.
59
60
  */
60
61
  readonly retry?: RetryOptions;
61
62
  /**
@@ -55,7 +55,8 @@ interface EngineDatabaseOptions {
55
55
  /**
56
56
  * How a transaction that conflicts with another write runs again: more
57
57
  * attempts for a store many writers contend on, and `onRetry` to observe
58
- * each rerun. 8 attempts by default.
58
+ * each rerun. 8 attempts by default; an aggregate write that lost to
59
+ * another writer's commit is resent without spending one.
59
60
  */
60
61
  readonly retry?: RetryOptions;
61
62
  /**
@@ -15,8 +15,11 @@ const coreSettings = {
15
15
  /** What `hot-updater db` creates for a server without plugins. */
16
16
  const coreTarget = {
17
17
  schema: coreSchema,
18
- settings: coreSettings
18
+ settings: coreSettings,
19
+ ordered: ["schema.core"]
19
20
  };
21
+ /** The brand Hot Updater's own plugin factories set, read as the server reads it. */
22
+ const isOfficialPlugin = (plugin) => Reflect.get(plugin, Symbol.for("@hot-updater/server/official-plugin")) === true;
20
23
  /**
21
24
  * The log and lease tables a database with `aggregateBatching` writes
22
25
  * beside core's and the plugins', which a provider's access policy names,
@@ -40,15 +43,16 @@ const toolingTargetOf = (plugins) => plugins.length === 0 ? coreTarget : {
40
43
  settings: {
41
44
  ...coreSettings,
42
45
  ...pluginSettings(plugins)
43
- }
46
+ },
47
+ ordered: [...coreTarget.ordered, ...plugins.flatMap((plugin) => isOfficialPlugin(plugin) ? [`schema.${plugin.id}`] : [])]
44
48
  };
45
49
  /**
46
50
  * Creates core's tables and those of `plugins`, then writes their settings
47
51
  * rows: what a provider's setup runs for the plugins its server runs.
48
52
  */
49
53
  const migrateCoreSchema = (adapter, name, plugins = []) => {
50
- const { schema, settings } = toolingTargetOf(plugins);
51
- return migrateSchema(adapter, name, schema.tables, settings);
54
+ const { schema, settings, ordered } = toolingTargetOf(plugins);
55
+ return migrateSchema(adapter, name, schema.tables, settings, ordered);
52
56
  };
53
57
  /**
54
58
  * A provider's database on the storage engine: its adapter behind the schema
@@ -59,11 +63,12 @@ const migrateCoreSchema = (adapter, name, plugins = []) => {
59
63
  */
60
64
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
61
65
  const fenced = withSchemaFence(adapter, name, coreSettings);
62
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
66
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
63
67
  adapterName: name,
64
68
  adapter,
65
69
  schema,
66
70
  settings,
71
+ ordered,
67
72
  readSettings: readStored ?? (async () => {
68
73
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
69
74
  if (isMissingSchemaError(error)) return [];
@@ -1,35 +1,63 @@
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");
3
- const require_schemaSettings = require("./schemaSettings.cjs");
4
4
  const require_settingsMigrator = require("./settingsMigrator.cjs");
5
+ const require_schemaSettings = require("./schemaSettings.cjs");
5
6
  //#region src/engine/db/engineMigrator.ts
6
7
  /**
7
8
  * `hot-updater db migrate` for a store whose adapter creates its own tables
8
9
  * (MongoDB and the key-value stores): the tables and indexes, then the
9
10
  * settings rows, applied when a setting is missing or different, and refused
10
- * on a v0 database.
11
+ * on a v0 database or one a newer release migrated.
11
12
  */
12
13
  const createEngineMigrator = (options) => {
13
14
  const getVersion = async () => require_settingsMigrator.storedSchemaVersion(await options.readSettings());
14
15
  const makeResult = async (migrate = {}) => {
15
16
  const stored = await options.readSettings();
16
17
  require_settingsMigrator.refuseV0Database(options.adapterName, stored);
17
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return require_fixedMigratorShared.getEmptyMigrationResult();
18
- return {
19
- operations: [...options.schema.tables.map((table) => ({
20
- type: "create-table",
21
- value: {
22
- ormName: table.name,
23
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
24
- ormName: column.name,
25
- type: column.type
26
- }]))
18
+ require_settingsMigrator.refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
19
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
20
+ if (changed.length === 0) {
21
+ const columns = await require_schemaSettings.addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
22
+ const lacking = await require_schemaSettings.fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
23
+ if (columns.length === 0 && lacking.length === 0) return require_fixedMigratorShared.getEmptyMigrationResult();
24
+ return {
25
+ operations: [
26
+ ...columns.map((column) => ({
27
+ type: "custom",
28
+ description: `Add column: ${column}`
29
+ })),
30
+ ...columns.length === 0 ? [] : [{
31
+ type: "custom",
32
+ description: "Create the tables and indexes the database lacks"
33
+ }],
34
+ ...lacking.length === 0 ? [] : [{
35
+ type: "custom",
36
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
37
+ }]
38
+ ],
39
+ execute: async () => {
40
+ if (columns.length > 0) {
41
+ await require_schemaSettings.addLateColumns(options.adapter, options.schema.tables);
42
+ await options.adapter.migrations.apply([...options.schema.tables, require_fence.SETTINGS_TABLE]);
43
+ }
44
+ await require_schemaSettings.fillLateIndexes(options.adapter, options.schema.tables);
27
45
  }
28
- })), ...migrate.updateSettings === false ? [] : [{
29
- type: "custom",
30
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
31
- }]],
32
- execute: () => require_schemaSettings.migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
46
+ };
47
+ }
48
+ return {
49
+ operations: [
50
+ ...(await require_schemaSettings.addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
51
+ type: "custom",
52
+ description: `Add column: ${column}`
53
+ })),
54
+ {
55
+ type: "custom",
56
+ description: "Create the tables and indexes the database lacks"
57
+ },
58
+ ...migrate.updateSettings === false ? [] : [require_settingsMigrator.settingsOperation(stored, changed)]
59
+ ],
60
+ execute: () => require_schemaSettings.migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
33
61
  };
34
62
  };
35
63
  return {
@@ -1,35 +1,63 @@
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 { migrateSchema } from "./schemaSettings.mjs";
4
- import { refuseV0Database, storedSchemaVersion } from "./settingsMigrator.mjs";
4
+ import { refuseNewerSchema, refuseV0Database, settingsOperation, storedSchemaVersion } from "./settingsMigrator.mjs";
5
+ import { addLateColumns, fillLateIndexes, migrateSchema } from "./schemaSettings.mjs";
5
6
  //#region src/engine/db/engineMigrator.ts
6
7
  /**
7
8
  * `hot-updater db migrate` for a store whose adapter creates its own tables
8
9
  * (MongoDB and the key-value stores): the tables and indexes, then the
9
10
  * settings rows, applied when a setting is missing or different, and refused
10
- * on a v0 database.
11
+ * on a v0 database or one a newer release migrated.
11
12
  */
12
13
  const createEngineMigrator = (options) => {
13
14
  const getVersion = async () => storedSchemaVersion(await options.readSettings());
14
15
  const makeResult = async (migrate = {}) => {
15
16
  const stored = await options.readSettings();
16
17
  refuseV0Database(options.adapterName, stored);
17
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
18
- return {
19
- operations: [...options.schema.tables.map((table) => ({
20
- type: "create-table",
21
- value: {
22
- ormName: table.name,
23
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
24
- ormName: column.name,
25
- type: column.type
26
- }]))
18
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
19
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
20
+ if (changed.length === 0) {
21
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
22
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
23
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
24
+ return {
25
+ operations: [
26
+ ...columns.map((column) => ({
27
+ type: "custom",
28
+ description: `Add column: ${column}`
29
+ })),
30
+ ...columns.length === 0 ? [] : [{
31
+ type: "custom",
32
+ description: "Create the tables and indexes the database lacks"
33
+ }],
34
+ ...lacking.length === 0 ? [] : [{
35
+ type: "custom",
36
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
37
+ }]
38
+ ],
39
+ execute: async () => {
40
+ if (columns.length > 0) {
41
+ await addLateColumns(options.adapter, options.schema.tables);
42
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
43
+ }
44
+ await fillLateIndexes(options.adapter, options.schema.tables);
27
45
  }
28
- })), ...migrate.updateSettings === false ? [] : [{
29
- type: "custom",
30
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
31
- }]],
32
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
46
+ };
47
+ }
48
+ return {
49
+ operations: [
50
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
51
+ type: "custom",
52
+ description: `Add column: ${column}`
53
+ })),
54
+ {
55
+ type: "custom",
56
+ description: "Create the tables and indexes the database lacks"
57
+ },
58
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]
59
+ ],
60
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
33
61
  };
34
62
  };
35
63
  return {
@@ -1,3 +1,4 @@
1
+ const require_schema = require("../core/schema.cjs");
1
2
  const require_fence = require("../database/fence.cjs");
2
3
  const require_sqlSchema = require("../database/sql/sqlSchema.cjs");
3
4
  //#region src/engine/db/engineSql.ts
@@ -21,6 +22,30 @@ const settingsStatements = (dialect, settings, tablePrefix = "") => {
21
22
  * database foreign keys: the engine keeps references itself.
22
23
  */
23
24
  const generateEngineSql = (dialect, schema, settings, options = {}) => [...require_sqlSchema.createTableStatements(dialect, [...schema.tables, require_fence.SETTINGS_TABLE], options.tablePrefix), ...settingsStatements(dialect, settings, options.tablePrefix)];
25
+ /**
26
+ * A managed provider's numbered migration needs these: an
27
+ * `ALTER TABLE … ADD COLUMN` for each column added to a table a released
28
+ * schema created, where neither an `earlier` migration's `CREATE TABLE` nor
29
+ * an earlier `ALTER TABLE … ADD COLUMN` has it. A
30
+ * migration that diffs statements skips the changed `CREATE TABLE IF NOT
31
+ * EXISTS`, which an existing table ignores anyway, so the D1 and Supabase
32
+ * generators put these first, before the statements that index the column.
33
+ * SQLite has no `ADD COLUMN IF NOT EXISTS`, so only a migration that runs once
34
+ * holds them, never statements a later migration repeats.
35
+ */
36
+ const lateColumnStatements = (dialect, schema, earlier, { tablePrefix = "" } = {}) => {
37
+ const quote = (name) => require_sqlSchema.quoteSql(dialect, name);
38
+ const shapes = require_sqlSchema.sqlTableShapes(dialect, schema.tables, tablePrefix);
39
+ return require_schema.LATE_COLUMNS.flatMap(({ table, column }) => {
40
+ const name = tablePrefix + table;
41
+ const created = earlier.find((sql) => sql.startsWith(`CREATE TABLE IF NOT EXISTS ${quote(name)} (`));
42
+ const declared = shapes.find((shape) => shape.name === name)?.columns.find((candidate) => candidate.name === column);
43
+ const added = earlier.some((sql) => sql.replace(" ADD COLUMN IF NOT EXISTS ", " ADD COLUMN ").startsWith(`ALTER TABLE ${quote(name)} ADD COLUMN ${quote(column)} `));
44
+ if (created === void 0 || declared === void 0 || added || created.includes(`${quote(column)} `)) return [];
45
+ return [`ALTER TABLE ${quote(name)} ADD COLUMN ${dialect === "postgresql" ? "IF NOT EXISTS " : ""}${quote(column)} ${declared.type}`];
46
+ });
47
+ };
24
48
  //#endregion
25
49
  exports.generateEngineSql = generateEngineSql;
50
+ exports.lateColumnStatements = lateColumnStatements;
26
51
  exports.settingsStatements = settingsStatements;
@@ -12,5 +12,17 @@ interface EngineSqlOptions {
12
12
  * database foreign keys: the engine keeps references itself.
13
13
  */
14
14
  declare const generateEngineSql: (dialect: SqlDialect, schema: ResolvedSchema, settings: SchemaSettings, options?: EngineSqlOptions) => string[];
15
+ /**
16
+ * A managed provider's numbered migration needs these: an
17
+ * `ALTER TABLE … ADD COLUMN` for each column added to a table a released
18
+ * schema created, where neither an `earlier` migration's `CREATE TABLE` nor
19
+ * an earlier `ALTER TABLE … ADD COLUMN` has it. A
20
+ * migration that diffs statements skips the changed `CREATE TABLE IF NOT
21
+ * EXISTS`, which an existing table ignores anyway, so the D1 and Supabase
22
+ * generators put these first, before the statements that index the column.
23
+ * SQLite has no `ADD COLUMN IF NOT EXISTS`, so only a migration that runs once
24
+ * holds them, never statements a later migration repeats.
25
+ */
26
+ declare const lateColumnStatements: (dialect: SqlDialect, schema: ResolvedSchema, earlier: readonly string[], { tablePrefix }?: EngineSqlOptions) => string[];
15
27
  //#endregion
16
- export { EngineSqlOptions, generateEngineSql };
28
+ export { EngineSqlOptions, generateEngineSql, lateColumnStatements };
@@ -12,5 +12,17 @@ interface EngineSqlOptions {
12
12
  * database foreign keys: the engine keeps references itself.
13
13
  */
14
14
  declare const generateEngineSql: (dialect: SqlDialect, schema: ResolvedSchema, settings: SchemaSettings, options?: EngineSqlOptions) => string[];
15
+ /**
16
+ * A managed provider's numbered migration needs these: an
17
+ * `ALTER TABLE … ADD COLUMN` for each column added to a table a released
18
+ * schema created, where neither an `earlier` migration's `CREATE TABLE` nor
19
+ * an earlier `ALTER TABLE … ADD COLUMN` has it. A
20
+ * migration that diffs statements skips the changed `CREATE TABLE IF NOT
21
+ * EXISTS`, which an existing table ignores anyway, so the D1 and Supabase
22
+ * generators put these first, before the statements that index the column.
23
+ * SQLite has no `ADD COLUMN IF NOT EXISTS`, so only a migration that runs once
24
+ * holds them, never statements a later migration repeats.
25
+ */
26
+ declare const lateColumnStatements: (dialect: SqlDialect, schema: ResolvedSchema, earlier: readonly string[], { tablePrefix }?: EngineSqlOptions) => string[];
15
27
  //#endregion
16
- export { EngineSqlOptions, generateEngineSql };
28
+ export { EngineSqlOptions, generateEngineSql, lateColumnStatements };
@@ -1,5 +1,6 @@
1
+ import { LATE_COLUMNS } from "../core/schema.mjs";
1
2
  import { SETTINGS_TABLE } from "../database/fence.mjs";
2
- import { createTableStatements, quoteSql } from "../database/sql/sqlSchema.mjs";
3
+ import { createTableStatements, quoteSql, sqlTableShapes } from "../database/sql/sqlSchema.mjs";
3
4
  //#region src/engine/db/engineSql.ts
4
5
  const literal = (text) => `'${text.replaceAll("'", "''")}'`;
5
6
  /** Upserts of the settings rows the fence reads. */
@@ -21,5 +22,28 @@ const settingsStatements = (dialect, settings, tablePrefix = "") => {
21
22
  * database foreign keys: the engine keeps references itself.
22
23
  */
23
24
  const generateEngineSql = (dialect, schema, settings, options = {}) => [...createTableStatements(dialect, [...schema.tables, SETTINGS_TABLE], options.tablePrefix), ...settingsStatements(dialect, settings, options.tablePrefix)];
25
+ /**
26
+ * A managed provider's numbered migration needs these: an
27
+ * `ALTER TABLE … ADD COLUMN` for each column added to a table a released
28
+ * schema created, where neither an `earlier` migration's `CREATE TABLE` nor
29
+ * an earlier `ALTER TABLE … ADD COLUMN` has it. A
30
+ * migration that diffs statements skips the changed `CREATE TABLE IF NOT
31
+ * EXISTS`, which an existing table ignores anyway, so the D1 and Supabase
32
+ * generators put these first, before the statements that index the column.
33
+ * SQLite has no `ADD COLUMN IF NOT EXISTS`, so only a migration that runs once
34
+ * holds them, never statements a later migration repeats.
35
+ */
36
+ const lateColumnStatements = (dialect, schema, earlier, { tablePrefix = "" } = {}) => {
37
+ const quote = (name) => quoteSql(dialect, name);
38
+ const shapes = sqlTableShapes(dialect, schema.tables, tablePrefix);
39
+ return LATE_COLUMNS.flatMap(({ table, column }) => {
40
+ const name = tablePrefix + table;
41
+ const created = earlier.find((sql) => sql.startsWith(`CREATE TABLE IF NOT EXISTS ${quote(name)} (`));
42
+ const declared = shapes.find((shape) => shape.name === name)?.columns.find((candidate) => candidate.name === column);
43
+ const added = earlier.some((sql) => sql.replace(" ADD COLUMN IF NOT EXISTS ", " ADD COLUMN ").startsWith(`ALTER TABLE ${quote(name)} ADD COLUMN ${quote(column)} `));
44
+ if (created === void 0 || declared === void 0 || added || created.includes(`${quote(column)} `)) return [];
45
+ return [`ALTER TABLE ${quote(name)} ADD COLUMN ${dialect === "postgresql" ? "IF NOT EXISTS " : ""}${quote(column)} ${declared.type}`];
46
+ });
47
+ };
24
48
  //#endregion
25
- export { generateEngineSql, settingsStatements };
49
+ export { generateEngineSql, lateColumnStatements, settingsStatements };
@@ -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,36 @@ 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
+ 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), options.tablePrefix);
59
+ if (changed.length === 0 && missing.columns.length === 0) return require_fixedMigratorShared.getEmptyMigrationResult();
60
+ const addColumns = require_sqlSchemaState.addColumnStatements(options.executor.dialect, missing.columns);
30
61
  const statements = require_engineSql.generateEngineSql(options.executor.dialect, options.schema, options.settings, options);
62
+ const settingsSql = require_engineSql.settingsStatements(options.executor.dialect, options.settings, options.tablePrefix);
63
+ const tablesSql = [...addColumns, ...statements.slice(0, -settingsSql.length || void 0)];
64
+ const writesSettings = changed.length > 0 && migrate.updateSettings !== false;
31
65
  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
- }]],
45
- getSQL: () => statements.map((statement) => `${statement};`).join("\n\n"),
46
- execute: () => run(options.executor, statements)
66
+ operations: [
67
+ ...missing.columns.map(({ table, column }) => ({
68
+ type: "custom",
69
+ description: `Add column: ${column.name} to ${table}`
70
+ })),
71
+ ...missing.tables.map((table) => ({
72
+ type: "create-table",
73
+ value: {
74
+ ormName: table,
75
+ columns: {}
76
+ }
77
+ })),
78
+ ...missing.indexes.map(({ table, index }) => ({
79
+ type: "custom",
80
+ description: `Create index: ${index} on ${table}`
81
+ })),
82
+ ...writesSettings ? [require_settingsMigrator.settingsOperation(stored, changed)] : []
83
+ ],
84
+ getSQL: () => [...addColumns, ...statements].map((statement) => `${statement};`).join("\n\n"),
85
+ execute: () => run(options.executor, tablesSql, changed.length > 0 ? settingsSql : [], options.schema, options.tablePrefix)
47
86
  };
48
87
  };
49
88
  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 { addColumnStatements, 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,36 @@ 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
+ const missing = missingSqlSchema(targetShapes(options.executor.dialect, options.schema, options.tablePrefix).filter((shape) => shape.name !== (options.tablePrefix ?? "") + SETTINGS_TABLE.name), await readSqlSchemaState(options.executor), options.tablePrefix);
59
+ if (changed.length === 0 && missing.columns.length === 0) return getEmptyMigrationResult();
60
+ const addColumns = addColumnStatements(options.executor.dialect, missing.columns);
30
61
  const statements = generateEngineSql(options.executor.dialect, options.schema, options.settings, options);
62
+ const settingsSql = settingsStatements(options.executor.dialect, options.settings, options.tablePrefix);
63
+ const tablesSql = [...addColumns, ...statements.slice(0, -settingsSql.length || void 0)];
64
+ const writesSettings = changed.length > 0 && migrate.updateSettings !== false;
31
65
  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
- }]],
45
- getSQL: () => statements.map((statement) => `${statement};`).join("\n\n"),
46
- execute: () => run(options.executor, statements)
66
+ operations: [
67
+ ...missing.columns.map(({ table, column }) => ({
68
+ type: "custom",
69
+ description: `Add column: ${column.name} to ${table}`
70
+ })),
71
+ ...missing.tables.map((table) => ({
72
+ type: "create-table",
73
+ value: {
74
+ ormName: table,
75
+ columns: {}
76
+ }
77
+ })),
78
+ ...missing.indexes.map(({ table, index }) => ({
79
+ type: "custom",
80
+ description: `Create index: ${index} on ${table}`
81
+ })),
82
+ ...writesSettings ? [settingsOperation(stored, changed)] : []
83
+ ],
84
+ getSQL: () => [...addColumns, ...statements].map((statement) => `${statement};`).join("\n\n"),
85
+ execute: () => run(options.executor, tablesSql, changed.length > 0 ? settingsSql : [], options.schema, options.tablePrefix)
47
86
  };
48
87
  };
49
88
  return {