@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
@@ -67,10 +67,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
67
67
  const at = row && expiresAt(table, row);
68
68
  return at === void 0 ? {} : { expiresAt: at };
69
69
  };
70
- /** Every index and unique item a row has, by address. */
71
- const itemsOf = (layout, row) => {
70
+ /** Every index and unique item a row has, by address: in `indexes`, if given. */
71
+ const itemsOf = (layout, row, indexes = layout.indexed) => {
72
72
  const items = /* @__PURE__ */ new Map();
73
- for (const index of row === null ? [] : layout.indexed) for (const eq of indexEntries(layout.table, index, row)) {
73
+ for (const index of row === null ? [] : indexes) for (const eq of indexEntries(layout.table, index, row)) {
74
74
  const pk = partition(layout, index, eq);
75
75
  const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
76
76
  items.set(JSON.stringify([pk, sk]), {
@@ -225,6 +225,79 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
225
225
  lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
226
226
  };
227
227
  };
228
+ /** One row's check and its item puts in `index`, copies of the row as it is. */
229
+ const fillOps = (layout, index, row) => [{
230
+ type: "check",
231
+ key: rowItem(layout, rowKey(layout.table, row)),
232
+ condition: { v: Number(row["_v"]) }
233
+ }, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
234
+ type: "put",
235
+ key,
236
+ value: copyOf(layout, row),
237
+ ...stamp(layout.table, row)
238
+ }))];
239
+ /**
240
+ * Writes one row's items in `index`, checking the row's `_v` in the same
241
+ * write: a row that changed is read again, and a deleted one needs none.
242
+ */
243
+ const fillRow = async (layout, index, first) => {
244
+ const key = rowItem(layout, rowKey(layout.table, first));
245
+ let row = first;
246
+ for (let attempt = 0; row !== null; attempt += 1) {
247
+ if (attempt === 8) throw new Error(`${layout.table.name}.${index.name}: a row kept changing while its index items were written; run the migration again.`);
248
+ if ((await store.write(fillOps(layout, index, row))).ok) return;
249
+ [row] = await store.get([key]);
250
+ }
251
+ };
252
+ /**
253
+ * Finds the rows that lack an item in `index` and, unless `dryRun`, writes
254
+ * them, as many rows per atomic write as the store takes. It reads every
255
+ * row and its items, page by page.
256
+ */
257
+ const fillIndex = async (table, name, { dryRun = false } = {}) => {
258
+ const layout = layoutOf(table);
259
+ const index = layout.indexed.find((candidate) => candidate.name === name);
260
+ if (index === void 0) return 0;
261
+ if (index.unique) throw new DatabaseAdapterContractError(`${table.name}.${name} is unique: its items can't be written for rows stored before it, since two of them may hold one value.`);
262
+ const { items: most, bytes } = store.limits;
263
+ let lacking = 0;
264
+ for (let after;;) {
265
+ const page = await store.query({
266
+ pk: layout.rows,
267
+ order: "asc",
268
+ limit: 100,
269
+ after
270
+ });
271
+ const rows = page.items.map(({ value }) => value);
272
+ const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
273
+ const wanted = keys.flat();
274
+ const found = wanted.length === 0 ? [] : await store.get(wanted);
275
+ let at = 0;
276
+ const missing = rows.filter((_, position) => {
277
+ return found.slice(at, at += keys[position].length).some((item) => item === null);
278
+ });
279
+ lacking += missing.length;
280
+ if (!dryRun) {
281
+ let chunk = [];
282
+ let ops = [];
283
+ const flush = async () => {
284
+ if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
285
+ chunk = [];
286
+ ops = [];
287
+ };
288
+ for (const row of missing) {
289
+ const next = fillOps(layout, index, row);
290
+ const size = (list) => list.reduce((sum, op) => sum + encoder.encode(op.key.pk + op.key.sk + JSON.stringify(op.type === "put" ? op.value : null)).length, 0);
291
+ if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
292
+ chunk.push(row);
293
+ ops.push(...next);
294
+ }
295
+ await flush();
296
+ }
297
+ if (!page.more || page.items.length === 0) return lacking;
298
+ after = page.items.at(-1).sk;
299
+ }
300
+ };
228
301
  return {
229
302
  id: store.id,
230
303
  fits(ops) {
@@ -284,7 +357,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
284
357
  const layout = layoutOf(table);
285
358
  return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
286
359
  } },
287
- migrations: { apply: async () => store.migrations?.apply() },
360
+ migrations: {
361
+ apply: async () => store.migrations?.apply(),
362
+ fillIndex
363
+ },
288
364
  ...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
289
365
  };
290
366
  };
@@ -40,7 +40,8 @@ const fieldProblems = (definition, add) => {
40
40
  else if (field.required === false) add(`key field "${name}" is nullable`);
41
41
  else if (field.type === "json") add(`key field "${name}" is json`);
42
42
  }
43
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
43
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
44
+ for (const [name, { type, maxLength, ascii }] of bounded) {
44
45
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
45
46
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
46
47
  }
@@ -157,11 +158,13 @@ const resolveSchema = (modules) => {
157
158
  ...maxLength === void 0 ? {} : { maxLength },
158
159
  ...ascii ? { ascii } : {}
159
160
  }));
160
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
161
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
161
162
  name: field,
162
163
  type,
163
164
  nullable: true,
164
- ...multi ? { multi } : {}
165
+ ...multi ? { multi } : {},
166
+ ...maxLength === void 0 ? {} : { maxLength },
167
+ ...ascii ? { ascii } : {}
165
168
  });
166
169
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
167
170
  name: metric,
@@ -40,7 +40,8 @@ const fieldProblems = (definition, add) => {
40
40
  else if (field.required === false) add(`key field "${name}" is nullable`);
41
41
  else if (field.type === "json") add(`key field "${name}" is json`);
42
42
  }
43
- for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
43
+ const bounded = [...Object.entries(definition.fields), ...definition.kind === "table" ? Object.entries(definition.derived) : []];
44
+ for (const [name, { type, maxLength, ascii }] of bounded) {
44
45
  if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
45
46
  if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
46
47
  }
@@ -157,11 +158,13 @@ const resolveSchema = (modules) => {
157
158
  ...maxLength === void 0 ? {} : { maxLength },
158
159
  ...ascii ? { ascii } : {}
159
160
  }));
160
- if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
161
+ if (definition.kind === "table") for (const [field, { type, multi, maxLength, ascii }] of Object.entries(definition.derived)) columns.push({
161
162
  name: field,
162
163
  type,
163
164
  nullable: true,
164
- ...multi ? { multi } : {}
165
+ ...multi ? { multi } : {},
166
+ ...maxLength === void 0 ? {} : { maxLength },
167
+ ...ascii ? { ascii } : {}
165
168
  });
166
169
  else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
167
170
  name: metric,
@@ -105,20 +105,25 @@ const createSqlAdapter = ({ executor, tablePrefix = "", maxOps = 1e3, maxParams
105
105
  const insert = (bind, into, columns, values) => `INSERT INTO ${into} (${columns.map(quote).join(", ")}) ${when ? `SELECT ${values.join(", ")} WHERE ${when(bind)}` : `VALUES (${values.join(", ")})`}`;
106
106
  /** Inserts `row` into the op's table, each value bound as its column's type. */
107
107
  const insertRow = (bind, row) => insert(bind, name, table.columns.map((column) => column.name), table.columns.map((column) => bind(row[column.name], column)));
108
- /** Replaces the row's entries in the index table of every multi-valued index. */
109
- const entries = (key, row, changed) => table.indexes.flatMap((index) => {
108
+ /**
109
+ * Replaces the row's entries in the index table of every multi-valued
110
+ * index. A row being inserted has none to replace (`stale` false), and
111
+ * deleting them would read the whole index table: its key ends with the
112
+ * row's key, so no index leads with it.
113
+ */
114
+ const entries = (key, row, changed, stale = true) => table.indexes.flatMap((index) => {
110
115
  const columns = [...index.eq, ...require_adapter.indexOrderColumns(table, index)];
111
116
  if (!require_sqlSchema.isMultiIndex(table, index) || changed && !columns.some((column) => changed.includes(column))) return [];
112
117
  const into = tableOf(table, index);
113
118
  const found = row ? require_values.indexEntries(table, index, row) : [];
114
119
  const order = found.length > 0 ? require_values.indexOrderTuple(table, index, row) : [];
115
- return [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`), ...found.map((eq) => sql((bind) => {
120
+ return [...stale ? [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`)] : [], ...found.map((eq) => sql((bind) => {
116
121
  const values = [...eq, ...order].map((value) => bind(value));
117
122
  return insert(bind, into, columns, values);
118
123
  }))];
119
124
  });
120
125
  switch (op.type) {
121
- case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(require_adapter.rowKey(table, op.row), op.row)];
126
+ case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(require_adapter.rowKey(table, op.row), op.row, void 0, false)];
122
127
  case "patch": return [sql((bind) => {
123
128
  const set = Object.entries(op.set).map(([column, value]) => `${quote(column)} = ${bind(value, require_adapter.findPhysicalColumn(table, column))}`);
124
129
  return `UPDATE ${name} SET ${[...set, `${version} = ${version} + 1`].join(", ")} WHERE ${where(bind, op.key, op.guard.v)}`;
@@ -105,20 +105,25 @@ const createSqlAdapter = ({ executor, tablePrefix = "", maxOps = 1e3, maxParams
105
105
  const insert = (bind, into, columns, values) => `INSERT INTO ${into} (${columns.map(quote).join(", ")}) ${when ? `SELECT ${values.join(", ")} WHERE ${when(bind)}` : `VALUES (${values.join(", ")})`}`;
106
106
  /** Inserts `row` into the op's table, each value bound as its column's type. */
107
107
  const insertRow = (bind, row) => insert(bind, name, table.columns.map((column) => column.name), table.columns.map((column) => bind(row[column.name], column)));
108
- /** Replaces the row's entries in the index table of every multi-valued index. */
109
- const entries = (key, row, changed) => table.indexes.flatMap((index) => {
108
+ /**
109
+ * Replaces the row's entries in the index table of every multi-valued
110
+ * index. A row being inserted has none to replace (`stale` false), and
111
+ * deleting them would read the whole index table: its key ends with the
112
+ * row's key, so no index leads with it.
113
+ */
114
+ const entries = (key, row, changed, stale = true) => table.indexes.flatMap((index) => {
110
115
  const columns = [...index.eq, ...indexOrderColumns(table, index)];
111
116
  if (!isMultiIndex(table, index) || changed && !columns.some((column) => changed.includes(column))) return [];
112
117
  const into = tableOf(table, index);
113
118
  const found = row ? indexEntries(table, index, row) : [];
114
119
  const order = found.length > 0 ? indexOrderTuple(table, index, row) : [];
115
- return [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`), ...found.map((eq) => sql((bind) => {
120
+ return [...stale ? [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`)] : [], ...found.map((eq) => sql((bind) => {
116
121
  const values = [...eq, ...order].map((value) => bind(value));
117
122
  return insert(bind, into, columns, values);
118
123
  }))];
119
124
  });
120
125
  switch (op.type) {
121
- case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row)];
126
+ case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row, void 0, false)];
122
127
  case "patch": return [sql((bind) => {
123
128
  const set = Object.entries(op.set).map(([column, value]) => `${quote(column)} = ${bind(value, findPhysicalColumn(table, column))}`);
124
129
  return `UPDATE ${name} SET ${[...set, `${version} = ${version} + 1`].join(", ")} WHERE ${where(bind, op.key, op.guard.v)}`;
@@ -49,7 +49,7 @@ const checkMysqlKey = (table, name, columns) => {
49
49
  };
50
50
  /**
51
51
  * Each table as the DDL creates it, for the DDL below and for ORM schema
52
- * generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index, and an index
52
+ * generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index (an index whose columns the key or an earlier index already orders by needs none), and an index
53
53
  * table `<table>__<index>` for each index over a multi-valued field, keyed by
54
54
  * every column it holds.
55
55
  */
@@ -57,6 +57,7 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
57
57
  const name = tablePrefix + table.name;
58
58
  const indexed = /* @__PURE__ */ new Set([...table.key, ...table.indexes.flatMap(({ eq, sort }) => [...eq, ...sort])]);
59
59
  if (dialect === "mysql") checkMysqlKey(table, "key", table.key);
60
+ const covered = /* @__PURE__ */ new Set([JSON.stringify(table.key)]);
60
61
  const indexes = table.indexes.flatMap((index) => {
61
62
  const columns = [...index.eq, ...require_adapter.indexOrderColumns(table, index)];
62
63
  if (dialect === "mysql") checkMysqlKey(table, `index ${index.name}`, columns);
@@ -72,11 +73,19 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
72
73
  name: `${name}__${index.name}`,
73
74
  columns: entries,
74
75
  key: columns,
75
- indexes: []
76
+ indexes: [{
77
+ kind: "index",
78
+ name: shortSqlName(`${name}__${index.name}__key`),
79
+ unique: false,
80
+ columns: table.key
81
+ }]
76
82
  }
77
83
  }];
78
84
  }
79
- if (!index.unique && columns.join() === table.key.join()) return [];
85
+ if (!index.unique) {
86
+ if (covered.has(JSON.stringify(columns))) return [];
87
+ covered.add(JSON.stringify(columns));
88
+ }
80
89
  return [{
81
90
  kind: "index",
82
91
  name: shortSqlName(`${name}_${index.name}`),
@@ -149,8 +158,9 @@ const retentionOrder = (table) => {
149
158
  * column past `before` keeps. `before` renders the bound each time it
150
159
  * appears. MySQL deletes with ORDER BY and LIMIT. Elsewhere the cutoff is
151
160
  * the last of the `limit` oldest expired rows in that order, a row value
152
- * the index ranges over, and the shapes pass Supabase's apply RPC: no IN, no
153
- * AS, aliases `i` and `b`.
161
+ * the index ranges over. PostgreSQL's shapes pass Supabase's apply RPC: no
162
+ * IN, no AS, aliases `i` and `b`; SQLite's (D1's) delete each doomed row's
163
+ * entries by the index table's key.
154
164
  */
155
165
  const pruneStatements = (dialect, table, tablePrefix, limit) => {
156
166
  const quote = (name) => quoteSql(dialect, name);
@@ -159,9 +169,17 @@ const pruneStatements = (dialect, table, tablePrefix, limit) => {
159
169
  const order = retentionOrder(table).columns.map(quote);
160
170
  const list = (alias, direction = "") => order.map((column) => `${alias}.${column}${direction}`).join(", ");
161
171
  const oldest = (before) => `SELECT ${list("i")} FROM ${name} i WHERE i.${at} <= ${before()} ORDER BY ${list("i", " ASC")} LIMIT ${limit}`;
162
- const doomed = (alias, before) => `${alias}.${at} <= ${before()} AND (${list(alias)}) <= (SELECT ${list("b")} FROM (${oldest(before)}) b ORDER BY ${list("b", " DESC")} LIMIT 1)`;
172
+ const doomed = (alias, before) => `(${list(alias)}) <= (SELECT ${list("b")} FROM (${oldest(before)}) b ORDER BY ${list("b", " DESC")} LIMIT 1) AND ${alias}.${at} <= ${before()}`;
163
173
  const entries = table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => quote(`${tablePrefix}${table.name}__${index.name}`));
164
174
  const keyOf = (left, right) => table.key.map((column) => `${left}.${quote(column)} = ${right}.${quote(column)}`).join(" AND ");
175
+ if (dialect === "sqlite") return [...table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => {
176
+ const columns = [...index.eq, ...require_adapter.indexOrderColumns(table, index)];
177
+ const multi = columns.filter((column) => require_adapter.findPhysicalColumn(table, column).multi);
178
+ const values = columns.map((column) => multi.includes(column) ? `j${multi.indexOf(column)}.${quote("value")}` : `b.${quote(column)}`);
179
+ const each = multi.map((column, at) => `, json_each(b.${quote(column)}) j${at}`);
180
+ const into = quote(`${tablePrefix}${table.name}__${index.name}`);
181
+ return (before) => `DELETE FROM ${into} WHERE (${columns.map(quote).join(", ")}) IN (SELECT ${values.join(", ")} FROM ${name} b${each.join("")} WHERE ${doomed("b", before)})`;
182
+ }), (before) => `DELETE FROM ${name} WHERE ${doomed(name, before)}`];
165
183
  if (dialect === "mysql") return [...entries.map((index) => (before) => `DELETE e FROM ${index} e JOIN (${oldest(before)}) d ON ${keyOf("e", "d")}`), (before) => `DELETE FROM ${name} WHERE ${at} <= ${before()} ORDER BY ${order.join(", ")} LIMIT ${limit}`];
166
184
  return [...entries.map((index) => (before) => `DELETE FROM ${index} WHERE EXISTS (SELECT * FROM ${name} b WHERE ${keyOf("b", index)} AND ${doomed("b", before)})`), (before) => `DELETE FROM ${name} WHERE ${doomed(name, before)}`];
167
185
  };
@@ -34,7 +34,7 @@ interface SqlTableShape {
34
34
  }
35
35
  /**
36
36
  * Each table as the DDL creates it, for the DDL below and for ORM schema
37
- * generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index, and an index
37
+ * generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index (an index whose columns the key or an earlier index already orders by needs none), and an index
38
38
  * table `<table>__<index>` for each index over a multi-valued field, keyed by
39
39
  * every column it holds.
40
40
  */
@@ -34,7 +34,7 @@ interface SqlTableShape {
34
34
  }
35
35
  /**
36
36
  * Each table as the DDL creates it, for the DDL below and for ORM schema
37
- * generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index, and an index
37
+ * generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index (an index whose columns the key or an earlier index already orders by needs none), and an index
38
38
  * table `<table>__<index>` for each index over a multi-valued field, keyed by
39
39
  * every column it holds.
40
40
  */
@@ -49,7 +49,7 @@ const checkMysqlKey = (table, name, columns) => {
49
49
  };
50
50
  /**
51
51
  * Each table as the DDL creates it, for the DDL below and for ORM schema
52
- * generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index, and an index
52
+ * generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index (an index whose columns the key or an earlier index already orders by needs none), and an index
53
53
  * table `<table>__<index>` for each index over a multi-valued field, keyed by
54
54
  * every column it holds.
55
55
  */
@@ -57,6 +57,7 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
57
57
  const name = tablePrefix + table.name;
58
58
  const indexed = /* @__PURE__ */ new Set([...table.key, ...table.indexes.flatMap(({ eq, sort }) => [...eq, ...sort])]);
59
59
  if (dialect === "mysql") checkMysqlKey(table, "key", table.key);
60
+ const covered = /* @__PURE__ */ new Set([JSON.stringify(table.key)]);
60
61
  const indexes = table.indexes.flatMap((index) => {
61
62
  const columns = [...index.eq, ...indexOrderColumns(table, index)];
62
63
  if (dialect === "mysql") checkMysqlKey(table, `index ${index.name}`, columns);
@@ -72,11 +73,19 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
72
73
  name: `${name}__${index.name}`,
73
74
  columns: entries,
74
75
  key: columns,
75
- indexes: []
76
+ indexes: [{
77
+ kind: "index",
78
+ name: shortSqlName(`${name}__${index.name}__key`),
79
+ unique: false,
80
+ columns: table.key
81
+ }]
76
82
  }
77
83
  }];
78
84
  }
79
- if (!index.unique && columns.join() === table.key.join()) return [];
85
+ if (!index.unique) {
86
+ if (covered.has(JSON.stringify(columns))) return [];
87
+ covered.add(JSON.stringify(columns));
88
+ }
80
89
  return [{
81
90
  kind: "index",
82
91
  name: shortSqlName(`${name}_${index.name}`),
@@ -149,8 +158,9 @@ const retentionOrder = (table) => {
149
158
  * column past `before` keeps. `before` renders the bound each time it
150
159
  * appears. MySQL deletes with ORDER BY and LIMIT. Elsewhere the cutoff is
151
160
  * the last of the `limit` oldest expired rows in that order, a row value
152
- * the index ranges over, and the shapes pass Supabase's apply RPC: no IN, no
153
- * AS, aliases `i` and `b`.
161
+ * the index ranges over. PostgreSQL's shapes pass Supabase's apply RPC: no
162
+ * IN, no AS, aliases `i` and `b`; SQLite's (D1's) delete each doomed row's
163
+ * entries by the index table's key.
154
164
  */
155
165
  const pruneStatements = (dialect, table, tablePrefix, limit) => {
156
166
  const quote = (name) => quoteSql(dialect, name);
@@ -159,9 +169,17 @@ const pruneStatements = (dialect, table, tablePrefix, limit) => {
159
169
  const order = retentionOrder(table).columns.map(quote);
160
170
  const list = (alias, direction = "") => order.map((column) => `${alias}.${column}${direction}`).join(", ");
161
171
  const oldest = (before) => `SELECT ${list("i")} FROM ${name} i WHERE i.${at} <= ${before()} ORDER BY ${list("i", " ASC")} LIMIT ${limit}`;
162
- const doomed = (alias, before) => `${alias}.${at} <= ${before()} AND (${list(alias)}) <= (SELECT ${list("b")} FROM (${oldest(before)}) b ORDER BY ${list("b", " DESC")} LIMIT 1)`;
172
+ const doomed = (alias, before) => `(${list(alias)}) <= (SELECT ${list("b")} FROM (${oldest(before)}) b ORDER BY ${list("b", " DESC")} LIMIT 1) AND ${alias}.${at} <= ${before()}`;
163
173
  const entries = table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => quote(`${tablePrefix}${table.name}__${index.name}`));
164
174
  const keyOf = (left, right) => table.key.map((column) => `${left}.${quote(column)} = ${right}.${quote(column)}`).join(" AND ");
175
+ if (dialect === "sqlite") return [...table.indexes.filter((index) => isMultiIndex(table, index)).map((index) => {
176
+ const columns = [...index.eq, ...indexOrderColumns(table, index)];
177
+ const multi = columns.filter((column) => findPhysicalColumn(table, column).multi);
178
+ const values = columns.map((column) => multi.includes(column) ? `j${multi.indexOf(column)}.${quote("value")}` : `b.${quote(column)}`);
179
+ const each = multi.map((column, at) => `, json_each(b.${quote(column)}) j${at}`);
180
+ const into = quote(`${tablePrefix}${table.name}__${index.name}`);
181
+ return (before) => `DELETE FROM ${into} WHERE (${columns.map(quote).join(", ")}) IN (SELECT ${values.join(", ")} FROM ${name} b${each.join("")} WHERE ${doomed("b", before)})`;
182
+ }), (before) => `DELETE FROM ${name} WHERE ${doomed(name, before)}`];
165
183
  if (dialect === "mysql") return [...entries.map((index) => (before) => `DELETE e FROM ${index} e JOIN (${oldest(before)}) d ON ${keyOf("e", "d")}`), (before) => `DELETE FROM ${name} WHERE ${at} <= ${before()} ORDER BY ${order.join(", ")} LIMIT ${limit}`];
166
184
  return [...entries.map((index) => (before) => `DELETE FROM ${index} WHERE EXISTS (SELECT * FROM ${name} b WHERE ${keyOf("b", index)} AND ${doomed("b", before)})`), (before) => `DELETE FROM ${name} WHERE ${doomed(name, before)}`];
167
185
  };
@@ -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,40 @@
1
1
  const require_schema = require("../core/schema.cjs");
2
2
  const require_fixedMigratorShared = require("./fixedMigratorShared.cjs");
3
- const require_schemaSettings = require("./schemaSettings.cjs");
4
3
  const require_settingsMigrator = require("./settingsMigrator.cjs");
4
+ const require_schemaSettings = require("./schemaSettings.cjs");
5
5
  //#region src/engine/db/engineMigrator.ts
6
6
  /**
7
7
  * `hot-updater db migrate` for a store whose adapter creates its own tables
8
8
  * (MongoDB and the key-value stores): the tables and indexes, then the
9
9
  * settings rows, applied when a setting is missing or different, and refused
10
- * on a v0 database.
10
+ * on a v0 database or one a newer release migrated.
11
11
  */
12
12
  const createEngineMigrator = (options) => {
13
13
  const getVersion = async () => require_settingsMigrator.storedSchemaVersion(await options.readSettings());
14
14
  const makeResult = async (migrate = {}) => {
15
15
  const stored = await options.readSettings();
16
16
  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
- }]))
17
+ require_settingsMigrator.refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
18
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
19
+ if (changed.length === 0) {
20
+ const lacking = await require_schemaSettings.fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
21
+ if (lacking.length === 0) return require_fixedMigratorShared.getEmptyMigrationResult();
22
+ return {
23
+ operations: [{
24
+ type: "custom",
25
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
26
+ }],
27
+ execute: async () => {
28
+ await require_schemaSettings.fillLateIndexes(options.adapter, options.schema.tables);
27
29
  }
28
- })), ...migrate.updateSettings === false ? [] : [{
30
+ };
31
+ }
32
+ return {
33
+ operations: [{
29
34
  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)
35
+ description: "Create the tables and indexes the database lacks"
36
+ }, ...migrate.updateSettings === false ? [] : [require_settingsMigrator.settingsOperation(stored, changed)]],
37
+ execute: () => require_schemaSettings.migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
33
38
  };
34
39
  };
35
40
  return {
@@ -1,35 +1,40 @@
1
1
  import { HOT_UPDATER_SCHEMA_VERSION } from "../core/schema.mjs";
2
2
  import { getEmptyMigrationResult } from "./fixedMigratorShared.mjs";
3
- import { migrateSchema } from "./schemaSettings.mjs";
4
- import { refuseV0Database, storedSchemaVersion } from "./settingsMigrator.mjs";
3
+ import { refuseNewerSchema, refuseV0Database, settingsOperation, storedSchemaVersion } from "./settingsMigrator.mjs";
4
+ import { fillLateIndexes, migrateSchema } from "./schemaSettings.mjs";
5
5
  //#region src/engine/db/engineMigrator.ts
6
6
  /**
7
7
  * `hot-updater db migrate` for a store whose adapter creates its own tables
8
8
  * (MongoDB and the key-value stores): the tables and indexes, then the
9
9
  * settings rows, applied when a setting is missing or different, and refused
10
- * on a v0 database.
10
+ * on a v0 database or one a newer release migrated.
11
11
  */
12
12
  const createEngineMigrator = (options) => {
13
13
  const getVersion = async () => storedSchemaVersion(await options.readSettings());
14
14
  const makeResult = async (migrate = {}) => {
15
15
  const stored = await options.readSettings();
16
16
  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
- }]))
17
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
18
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
19
+ if (changed.length === 0) {
20
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
21
+ if (lacking.length === 0) return getEmptyMigrationResult();
22
+ return {
23
+ operations: [{
24
+ type: "custom",
25
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
26
+ }],
27
+ execute: async () => {
28
+ await fillLateIndexes(options.adapter, options.schema.tables);
27
29
  }
28
- })), ...migrate.updateSettings === false ? [] : [{
30
+ };
31
+ }
32
+ return {
33
+ operations: [{
29
34
  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)
35
+ description: "Create the tables and indexes the database lacks"
36
+ }, ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]],
37
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
33
38
  };
34
39
  };
35
40
  return {