@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.
- package/dist/coreApi.d.cts +277 -10
- package/dist/coreApi.d.mts +277 -10
- package/dist/database/adapter.d.cts +24 -0
- package/dist/database/adapter.d.mts +24 -0
- package/dist/databaseRows.cjs +4 -2
- package/dist/databaseRows.mjs +4 -2
- package/dist/engine/core/schema.cjs +253 -6
- package/dist/engine/core/schema.d.cts +154 -1
- package/dist/engine/core/schema.d.mts +154 -1
- package/dist/engine/core/schema.mjs +252 -7
- package/dist/engine/createEngine.cjs +1 -2
- package/dist/engine/createEngine.d.cts +1 -6
- package/dist/engine/createEngine.d.mts +1 -6
- package/dist/engine/createEngine.mjs +1 -2
- package/dist/engine/database/aggregateBatching.cjs +87 -129
- package/dist/engine/database/aggregateBatching.mjs +87 -129
- package/dist/engine/database/database.cjs +1 -4
- package/dist/engine/database/database.mjs +1 -4
- package/dist/engine/database/engineTransaction.cjs +26 -2
- package/dist/engine/database/engineTransaction.d.cts +5 -1
- package/dist/engine/database/engineTransaction.d.mts +5 -1
- package/dist/engine/database/engineTransaction.mjs +26 -2
- package/dist/engine/database/fence.cjs +24 -2
- package/dist/engine/database/fence.d.cts +4 -1
- package/dist/engine/database/fence.d.mts +4 -1
- package/dist/engine/database/fence.mjs +24 -3
- package/dist/engine/database/kv/kvAdapter.cjs +80 -4
- package/dist/engine/database/kv/kvAdapter.mjs +80 -4
- package/dist/engine/database/resolveSchema.cjs +6 -3
- package/dist/engine/database/resolveSchema.mjs +6 -3
- package/dist/engine/database/sql/sqlAdapter.cjs +36 -12
- package/dist/engine/database/sql/sqlAdapter.mjs +37 -13
- package/dist/engine/database/sql/sqlSchema.cjs +24 -6
- package/dist/engine/database/sql/sqlSchema.d.cts +1 -1
- package/dist/engine/database/sql/sqlSchema.d.mts +1 -1
- package/dist/engine/database/sql/sqlSchema.mjs +24 -6
- package/dist/engine/db/coreDatabase.cjs +10 -5
- package/dist/engine/db/coreDatabase.d.cts +2 -1
- package/dist/engine/db/coreDatabase.d.mts +2 -1
- package/dist/engine/db/coreDatabase.mjs +10 -5
- package/dist/engine/db/engineMigrator.cjs +45 -17
- package/dist/engine/db/engineMigrator.mjs +46 -18
- package/dist/engine/db/engineSql.cjs +25 -0
- package/dist/engine/db/engineSql.d.cts +13 -1
- package/dist/engine/db/engineSql.d.mts +13 -1
- package/dist/engine/db/engineSql.mjs +26 -2
- package/dist/engine/db/engineSqlMigrator.cjs +60 -21
- package/dist/engine/db/engineSqlMigrator.d.cts +2 -0
- package/dist/engine/db/engineSqlMigrator.d.mts +2 -0
- package/dist/engine/db/engineSqlMigrator.mjs +62 -23
- package/dist/engine/db/schemaSettings.cjs +56 -5
- package/dist/engine/db/schemaSettings.d.cts +5 -2
- package/dist/engine/db/schemaSettings.d.mts +5 -2
- package/dist/engine/db/schemaSettings.mjs +55 -6
- package/dist/engine/db/settingsMigrator.cjs +113 -15
- package/dist/engine/db/settingsMigrator.d.cts +18 -8
- package/dist/engine/db/settingsMigrator.d.mts +18 -8
- package/dist/engine/db/settingsMigrator.mjs +111 -17
- package/dist/engine/db/sqlSchemaState.cjs +136 -0
- package/dist/engine/db/sqlSchemaState.mjs +131 -0
- package/dist/engine/db/types.d.cts +6 -0
- package/dist/engine/db/types.d.mts +6 -0
- package/dist/index.cjs +4 -8
- package/dist/index.d.cts +7 -8
- package/dist/index.d.mts +7 -8
- package/dist/index.mjs +5 -6
- package/dist/releaseCatalogCompiler.cjs +89 -7
- package/dist/releaseCatalogCompiler.d.cts +12 -1
- package/dist/releaseCatalogCompiler.d.mts +12 -1
- package/dist/releaseCatalogCompiler.mjs +89 -8
- package/dist/releaseCatalogMutation.d.cts +8 -2
- package/dist/releaseCatalogMutation.d.mts +8 -2
- package/dist/serverPlugin/coreReads.d.cts +10 -1
- package/dist/serverPlugin/coreReads.d.mts +10 -1
- package/dist/serverPlugin/definitions.d.cts +4 -0
- package/dist/serverPlugin/definitions.d.mts +4 -0
- package/dist/serverPlugin/schema.d.cts +4 -0
- package/dist/serverPlugin/schema.d.mts +4 -0
- package/dist/types/databaseConfig.d.cts +10 -20
- package/dist/types/databaseConfig.d.mts +10 -20
- package/dist/types/databaseRows.d.cts +77 -2
- package/dist/types/databaseRows.d.mts +77 -2
- package/dist/types/index.cjs +3 -0
- package/dist/types/index.d.cts +114 -56
- package/dist/types/index.d.mts +114 -56
- package/dist/types/index.mjs +3 -1
- package/dist/types/models.d.cts +9 -1
- package/dist/types/models.d.mts +9 -1
- package/dist/types/public.d.cts +3 -3
- package/dist/types/public.d.mts +3 -3
- package/package.json +3 -9
- package/dist/remoteBundleSigning.cjs +0 -357
- package/dist/remoteBundleSigning.d.cts +0 -38
- package/dist/remoteBundleSigning.d.mts +0 -38
- package/dist/remoteBundleSigning.mjs +0 -352
|
@@ -33,6 +33,23 @@ const SETTINGS_TABLE = {
|
|
|
33
33
|
/** The engine's storage-layout generation; it changes only with a migration. */
|
|
34
34
|
const ENGINE_SCHEMA_KEY = "schema.engine";
|
|
35
35
|
const CORE_SCHEMA_KEY = "schema.core";
|
|
36
|
+
/** Compares dotted numeric versions, such as "1" and "1.2.0"; NaN when either is not one. */
|
|
37
|
+
const compareVersions = (left, right) => {
|
|
38
|
+
const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
|
|
39
|
+
const [a, b] = [parse(left), parse(right)];
|
|
40
|
+
if ([...a, ...b].some(Number.isNaN)) return NaN;
|
|
41
|
+
for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
|
|
42
|
+
const difference = (a[index] ?? 0) - (b[index] ?? 0);
|
|
43
|
+
if (difference !== 0) return difference;
|
|
44
|
+
}
|
|
45
|
+
return 0;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* The `schema.core` a newer release recorded, which `hot-updater db migrate`
|
|
49
|
+
* never moves back: the fix is to upgrade, not to migrate.
|
|
50
|
+
*/
|
|
51
|
+
const newerCore = (settings) => settings.find(({ key, expected, found }) => key === CORE_SCHEMA_KEY && found !== null && compareVersions(found, expected) > 0);
|
|
52
|
+
const newerMessage = (adapterName, { key, expected, found }) => `Hot Updater schema setting "${key}" for ${adapterName} is "${found}"; expected "${expected}". The database was migrated by Hot Updater ${found}: upgrade hot-updater and the @hot-updater packages to ${found} or later.`;
|
|
36
53
|
const stored = ({ key, expected, found }) => `"${key}" is ${found === null ? "missing" : `"${found}"`}; expected "${expected}"`;
|
|
37
54
|
/**
|
|
38
55
|
* How to migrate a database the fence refused: doctor names the command for
|
|
@@ -46,7 +63,10 @@ const pluginOf = ({ key }) => key.startsWith("schema.") && key !== "schema.engin
|
|
|
46
63
|
const listed = (items) => items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
|
|
47
64
|
const settingsMessage = (adapterName, settings) => `Hot Updater schema settings for ${adapterName} are not migrated: ${settings.map(stored).join(", and ")}. ${MIGRATE_SCHEMA_FIX}`;
|
|
48
65
|
const pluginsMessage = (adapterName, plugins, settings, fix) => `The tables of ${plugins.length === 1 ? "plugin" : "plugins"} ${listed(plugins.map((id) => `"${id}"`))} are not migrated on ${adapterName}: schema ${settings.length === 1 ? "setting" : "settings"} ${settings.map(stored).join(", and ")}. ${fix}`;
|
|
49
|
-
/**
|
|
66
|
+
/**
|
|
67
|
+
* The database needs `hot-updater db migrate`, a new database, or a newer
|
|
68
|
+
* Hot Updater; the handler answers 503.
|
|
69
|
+
*/
|
|
50
70
|
var HotUpdaterSchemaMigrationRequiredError = class extends Error {
|
|
51
71
|
adapterName;
|
|
52
72
|
currentVersion;
|
|
@@ -61,7 +81,8 @@ var HotUpdaterSchemaMigrationRequiredError = class extends Error {
|
|
|
61
81
|
constructor(adapterName, currentVersion, setting, options) {
|
|
62
82
|
const settings = options?.settings ?? (setting === void 0 ? [] : [setting]);
|
|
63
83
|
const plugins = settings.flatMap((mismatch) => pluginOf(mismatch) ?? []);
|
|
64
|
-
|
|
84
|
+
const newer = newerCore(settings);
|
|
85
|
+
super(newer !== void 0 ? newerMessage(adapterName, newer) : setting === void 0 ? currentVersion === void 0 ? `Hot Updater database schema is not initialized for ${adapterName}. ${MIGRATE_SCHEMA_FIX}` : `Hot Updater v1 cannot migrate schema ${currentVersion} in place. Create a new empty database and run \`hot-updater db migrate\`.` : plugins.length > 0 && plugins.length === settings.length ? pluginsMessage(adapterName, plugins, settings, options?.fix ?? MIGRATE_SCHEMA_FIX) : settings.length > 1 && !(setting.key === "schema.engine" && setting.found === null) ? settingsMessage(adapterName, settings) : settingMessage(adapterName, setting), options?.cause === void 0 ? void 0 : { cause: options.cause });
|
|
65
86
|
this.adapterName = adapterName;
|
|
66
87
|
this.currentVersion = currentVersion;
|
|
67
88
|
this.setting = setting;
|
|
@@ -172,4 +193,4 @@ const withSchemaFence = (adapter, adapterName, expected, fix) => {
|
|
|
172
193
|
};
|
|
173
194
|
};
|
|
174
195
|
//#endregion
|
|
175
|
-
export { ENGINE_SCHEMA_KEY, HotUpdaterSchemaMigrationRequiredError, SETTINGS_TABLE, checkSchemaFence, fencedName, isMissingSchemaError, readSettings, withSchemaFence };
|
|
196
|
+
export { ENGINE_SCHEMA_KEY, HotUpdaterSchemaMigrationRequiredError, SETTINGS_TABLE, checkSchemaFence, compareVersions, fencedName, isMissingSchemaError, readSettings, withSchemaFence };
|
|
@@ -67,10 +67,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
|
|
|
67
67
|
const at = row && require_adapter.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 ? [] :
|
|
73
|
+
for (const index of row === null ? [] : indexes) for (const eq of require_values.indexEntries(layout.table, index, row)) {
|
|
74
74
|
const pk = partition(layout, index, eq);
|
|
75
75
|
const sk = index.unique ? ONLY : encodeKvKey(require_values.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, require_adapter.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, require_adapter.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 require_verifyAdapter.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, require_adapter.rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
|
|
286
359
|
} },
|
|
287
|
-
migrations: {
|
|
360
|
+
migrations: {
|
|
361
|
+
apply: async () => store.migrations?.apply(),
|
|
362
|
+
fillIndex
|
|
363
|
+
},
|
|
288
364
|
...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
|
|
289
365
|
};
|
|
290
366
|
};
|
|
@@ -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 ? [] :
|
|
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: {
|
|
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
|
-
|
|
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
|
-
|
|
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,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const require_adapter = require("../../../database/adapter.cjs");
|
|
2
2
|
const require_values = require("../../../database/values.cjs");
|
|
3
3
|
const require_sqlSchema = require("./sqlSchema.cjs");
|
|
4
|
+
const require_sqlSchemaState = require("../../db/sqlSchemaState.cjs");
|
|
4
5
|
//#region src/engine/database/sql/sqlAdapter.ts
|
|
5
6
|
/** Where a batch write records its first failed op, before any change applies. */
|
|
6
7
|
const WRITE_GUARD_TABLE = {
|
|
@@ -105,20 +106,25 @@ const createSqlAdapter = ({ executor, tablePrefix = "", maxOps = 1e3, maxParams
|
|
|
105
106
|
const insert = (bind, into, columns, values) => `INSERT INTO ${into} (${columns.map(quote).join(", ")}) ${when ? `SELECT ${values.join(", ")} WHERE ${when(bind)}` : `VALUES (${values.join(", ")})`}`;
|
|
106
107
|
/** Inserts `row` into the op's table, each value bound as its column's type. */
|
|
107
108
|
const insertRow = (bind, row) => insert(bind, name, table.columns.map((column) => column.name), table.columns.map((column) => bind(row[column.name], column)));
|
|
108
|
-
/**
|
|
109
|
-
|
|
109
|
+
/**
|
|
110
|
+
* Replaces the row's entries in the index table of every multi-valued
|
|
111
|
+
* index. A row being inserted has none to replace (`stale` false), and
|
|
112
|
+
* deleting them would read the whole index table: its key ends with the
|
|
113
|
+
* row's key, so no index leads with it.
|
|
114
|
+
*/
|
|
115
|
+
const entries = (key, row, changed, stale = true) => table.indexes.flatMap((index) => {
|
|
110
116
|
const columns = [...index.eq, ...require_adapter.indexOrderColumns(table, index)];
|
|
111
117
|
if (!require_sqlSchema.isMultiIndex(table, index) || changed && !columns.some((column) => changed.includes(column))) return [];
|
|
112
118
|
const into = tableOf(table, index);
|
|
113
119
|
const found = row ? require_values.indexEntries(table, index, row) : [];
|
|
114
120
|
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) => {
|
|
121
|
+
return [...stale ? [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`)] : [], ...found.map((eq) => sql((bind) => {
|
|
116
122
|
const values = [...eq, ...order].map((value) => bind(value));
|
|
117
123
|
return insert(bind, into, columns, values);
|
|
118
124
|
}))];
|
|
119
125
|
});
|
|
120
126
|
switch (op.type) {
|
|
121
|
-
case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(require_adapter.rowKey(table, op.row), op.row)];
|
|
127
|
+
case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(require_adapter.rowKey(table, op.row), op.row, void 0, false)];
|
|
122
128
|
case "patch": return [sql((bind) => {
|
|
123
129
|
const set = Object.entries(op.set).map(([column, value]) => `${quote(column)} = ${bind(value, require_adapter.findPhysicalColumn(table, column))}`);
|
|
124
130
|
return `UPDATE ${name} SET ${[...set, `${version} = ${version} + 1`].join(", ")} WHERE ${where(bind, op.key, op.guard.v)}`;
|
|
@@ -274,14 +280,32 @@ const createSqlAdapter = ({ executor, tablePrefix = "", maxOps = 1e3, maxParams
|
|
|
274
280
|
return done;
|
|
275
281
|
})).at(-1)?.changes ?? 0;
|
|
276
282
|
},
|
|
277
|
-
migrations: {
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
283
|
+
migrations: {
|
|
284
|
+
async apply(tables) {
|
|
285
|
+
const created = executor.batch && !tables.includes(WRITE_GUARD_TABLE) ? [...tables, WRITE_GUARD_TABLE] : tables;
|
|
286
|
+
const statements = require_sqlSchema.createTableStatements(dialect, created, tablePrefix);
|
|
287
|
+
for (const text of statements) await executor.execute({
|
|
288
|
+
sql: text,
|
|
289
|
+
params: []
|
|
290
|
+
});
|
|
291
|
+
},
|
|
292
|
+
async addColumns(table, columns, { dryRun = false } = {}) {
|
|
293
|
+
const [shape] = require_sqlSchema.sqlTableShapes(dialect, [table], tablePrefix);
|
|
294
|
+
const state = await require_sqlSchemaState.readSqlSchemaState(executor);
|
|
295
|
+
if (shape === void 0 || !state.hasTable(shape.name)) return [];
|
|
296
|
+
const missing = columns.filter((column) => !state.hasColumn(shape.name, column));
|
|
297
|
+
if (dryRun) return missing;
|
|
298
|
+
for (const name of missing) {
|
|
299
|
+
const column = shape.columns.find((candidate) => candidate.name === name);
|
|
300
|
+
if (column === void 0 || column.notNull) throw new Error(`${table.name}.${name} can't be added to an existing table: only an optional column can.`);
|
|
301
|
+
await executor.execute({
|
|
302
|
+
sql: `ALTER TABLE ${require_sqlSchema.quoteSql(dialect, shape.name)} ADD COLUMN ${require_sqlSchema.quoteSql(dialect, name)} ${column.type}`,
|
|
303
|
+
params: []
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
return missing;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
285
309
|
};
|
|
286
310
|
};
|
|
287
311
|
//#endregion
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { findPhysicalColumn, findPhysicalIndex, indexOrderColumns, rowKey } from "../../../database/adapter.mjs";
|
|
2
2
|
import { indexEntries, indexOrderTuple, normalizeStoredRow } from "../../../database/values.mjs";
|
|
3
|
-
import { createTableStatements, isMultiIndex, pruneStatements, quoteSql } from "./sqlSchema.mjs";
|
|
3
|
+
import { createTableStatements, isMultiIndex, pruneStatements, quoteSql, sqlTableShapes } from "./sqlSchema.mjs";
|
|
4
|
+
import { readSqlSchemaState } from "../../db/sqlSchemaState.mjs";
|
|
4
5
|
//#region src/engine/database/sql/sqlAdapter.ts
|
|
5
6
|
/** Where a batch write records its first failed op, before any change applies. */
|
|
6
7
|
const WRITE_GUARD_TABLE = {
|
|
@@ -105,20 +106,25 @@ const createSqlAdapter = ({ executor, tablePrefix = "", maxOps = 1e3, maxParams
|
|
|
105
106
|
const insert = (bind, into, columns, values) => `INSERT INTO ${into} (${columns.map(quote).join(", ")}) ${when ? `SELECT ${values.join(", ")} WHERE ${when(bind)}` : `VALUES (${values.join(", ")})`}`;
|
|
106
107
|
/** Inserts `row` into the op's table, each value bound as its column's type. */
|
|
107
108
|
const insertRow = (bind, row) => insert(bind, name, table.columns.map((column) => column.name), table.columns.map((column) => bind(row[column.name], column)));
|
|
108
|
-
/**
|
|
109
|
-
|
|
109
|
+
/**
|
|
110
|
+
* Replaces the row's entries in the index table of every multi-valued
|
|
111
|
+
* index. A row being inserted has none to replace (`stale` false), and
|
|
112
|
+
* deleting them would read the whole index table: its key ends with the
|
|
113
|
+
* row's key, so no index leads with it.
|
|
114
|
+
*/
|
|
115
|
+
const entries = (key, row, changed, stale = true) => table.indexes.flatMap((index) => {
|
|
110
116
|
const columns = [...index.eq, ...indexOrderColumns(table, index)];
|
|
111
117
|
if (!isMultiIndex(table, index) || changed && !columns.some((column) => changed.includes(column))) return [];
|
|
112
118
|
const into = tableOf(table, index);
|
|
113
119
|
const found = row ? indexEntries(table, index, row) : [];
|
|
114
120
|
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) => {
|
|
121
|
+
return [...stale ? [sql((bind) => `DELETE FROM ${into} WHERE ${where(bind, key)}`)] : [], ...found.map((eq) => sql((bind) => {
|
|
116
122
|
const values = [...eq, ...order].map((value) => bind(value));
|
|
117
123
|
return insert(bind, into, columns, values);
|
|
118
124
|
}))];
|
|
119
125
|
});
|
|
120
126
|
switch (op.type) {
|
|
121
|
-
case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row)];
|
|
127
|
+
case "insert": return [sql((bind) => insertRow(bind, op.row)), ...entries(rowKey(table, op.row), op.row, void 0, false)];
|
|
122
128
|
case "patch": return [sql((bind) => {
|
|
123
129
|
const set = Object.entries(op.set).map(([column, value]) => `${quote(column)} = ${bind(value, findPhysicalColumn(table, column))}`);
|
|
124
130
|
return `UPDATE ${name} SET ${[...set, `${version} = ${version} + 1`].join(", ")} WHERE ${where(bind, op.key, op.guard.v)}`;
|
|
@@ -274,14 +280,32 @@ const createSqlAdapter = ({ executor, tablePrefix = "", maxOps = 1e3, maxParams
|
|
|
274
280
|
return done;
|
|
275
281
|
})).at(-1)?.changes ?? 0;
|
|
276
282
|
},
|
|
277
|
-
migrations: {
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
283
|
+
migrations: {
|
|
284
|
+
async apply(tables) {
|
|
285
|
+
const created = executor.batch && !tables.includes(WRITE_GUARD_TABLE) ? [...tables, WRITE_GUARD_TABLE] : tables;
|
|
286
|
+
const statements = createTableStatements(dialect, created, tablePrefix);
|
|
287
|
+
for (const text of statements) await executor.execute({
|
|
288
|
+
sql: text,
|
|
289
|
+
params: []
|
|
290
|
+
});
|
|
291
|
+
},
|
|
292
|
+
async addColumns(table, columns, { dryRun = false } = {}) {
|
|
293
|
+
const [shape] = sqlTableShapes(dialect, [table], tablePrefix);
|
|
294
|
+
const state = await readSqlSchemaState(executor);
|
|
295
|
+
if (shape === void 0 || !state.hasTable(shape.name)) return [];
|
|
296
|
+
const missing = columns.filter((column) => !state.hasColumn(shape.name, column));
|
|
297
|
+
if (dryRun) return missing;
|
|
298
|
+
for (const name of missing) {
|
|
299
|
+
const column = shape.columns.find((candidate) => candidate.name === name);
|
|
300
|
+
if (column === void 0 || column.notNull) throw new Error(`${table.name}.${name} can't be added to an existing table: only an optional column can.`);
|
|
301
|
+
await executor.execute({
|
|
302
|
+
sql: `ALTER TABLE ${quoteSql(dialect, shape.name)} ADD COLUMN ${quoteSql(dialect, name)} ${column.type}`,
|
|
303
|
+
params: []
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
return missing;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
285
309
|
};
|
|
286
310
|
};
|
|
287
311
|
//#endregion
|
|
@@ -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
|
|
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
|
|
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) =>
|
|
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
|
|
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
|
|
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) =>
|
|
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
|
};
|