@hot-updater/plugin-core 1.2.0-rc.44 → 1.2.0-rc.46

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.
@@ -243,14 +243,21 @@ interface HotUpdaterCoreApi {
243
243
  findChannelByName(name: string): Promise<ChannelRow | null>;
244
244
  /** A native build by ID: one read of its key. */
245
245
  getNativeBuild(id: string): Promise<NativeBuildRow | null>;
246
+ /**
247
+ * The native build whose built-in bundle is `bundleId`, the MIN_BUNDLE_ID
248
+ * it compiled in, or null: one read of its unique index.
249
+ */
250
+ findNativeBuildByBuiltInBundle(bundleId: string): Promise<NativeBuildRow | null>;
246
251
  /**
247
252
  * The newest native build of a scope: the one registered last, in one read
248
253
  * of its index. With `buildKey`, the newest of the scope registered with that
249
254
  * native build key, also one read. With `storeBuild`, the scope's marked
250
255
  * build or null, also one read. With `builtInOlderThan`, the newest of the
251
256
  * scope whose built-in bundle is older than that bundle: one read when the
252
- * newest is, and then a page of older builds per read until one is, when
253
- * builds made after the bundle are in the way. With `buildKey` too, only
257
+ * newest is, and then a page of 20 older builds per read until one is, when
258
+ * builds made after the bundle are in the way. It reads at most 5 such
259
+ * pages, and answers null when none of those 100 builds is older than the
260
+ * bundle, as when the scope has none. With `buildKey` too, only
254
261
  * builds of that key. With `scope.sandbox`, sandbox builds on any channel;
255
262
  * without it, never one. A sandbox build's built-in bundle is no patch
256
263
  * base, so with `builtInOlderThan` a sandbox scope answers null without a
@@ -243,14 +243,21 @@ interface HotUpdaterCoreApi {
243
243
  findChannelByName(name: string): Promise<ChannelRow | null>;
244
244
  /** A native build by ID: one read of its key. */
245
245
  getNativeBuild(id: string): Promise<NativeBuildRow | null>;
246
+ /**
247
+ * The native build whose built-in bundle is `bundleId`, the MIN_BUNDLE_ID
248
+ * it compiled in, or null: one read of its unique index.
249
+ */
250
+ findNativeBuildByBuiltInBundle(bundleId: string): Promise<NativeBuildRow | null>;
246
251
  /**
247
252
  * The newest native build of a scope: the one registered last, in one read
248
253
  * of its index. With `buildKey`, the newest of the scope registered with that
249
254
  * native build key, also one read. With `storeBuild`, the scope's marked
250
255
  * build or null, also one read. With `builtInOlderThan`, the newest of the
251
256
  * scope whose built-in bundle is older than that bundle: one read when the
252
- * newest is, and then a page of older builds per read until one is, when
253
- * builds made after the bundle are in the way. With `buildKey` too, only
257
+ * newest is, and then a page of 20 older builds per read until one is, when
258
+ * builds made after the bundle are in the way. It reads at most 5 such
259
+ * pages, and answers null when none of those 100 builds is older than the
260
+ * bundle, as when the scope has none. With `buildKey` too, only
254
261
  * builds of that key. With `scope.sandbox`, sandbox builds on any channel;
255
262
  * without it, never one. A sandbox build's built-in bundle is no patch
256
263
  * base, so with `builtInOlderThan` a sandbox scope answers null without a
@@ -516,6 +516,10 @@ const iosDevices = require_schema.defineTable({
516
516
  eq: ["status"],
517
517
  sort: ["id"]
518
518
  },
519
+ byRegistration: {
520
+ eq: [],
521
+ sort: ["registered_at_ms"]
522
+ },
519
523
  all: {
520
524
  eq: [],
521
525
  sort: ["id"]
@@ -499,6 +499,10 @@ declare const coreSchema: {
499
499
  readonly eq: readonly ["status"];
500
500
  readonly sort: readonly ["id"];
501
501
  };
502
+ readonly byRegistration: {
503
+ readonly eq: readonly [];
504
+ readonly sort: readonly ["registered_at_ms"];
505
+ };
502
506
  readonly all: {
503
507
  readonly eq: readonly [];
504
508
  readonly sort: readonly ["id"];
@@ -499,6 +499,10 @@ declare const coreSchema: {
499
499
  readonly eq: readonly ["status"];
500
500
  readonly sort: readonly ["id"];
501
501
  };
502
+ readonly byRegistration: {
503
+ readonly eq: readonly [];
504
+ readonly sort: readonly ["registered_at_ms"];
505
+ };
502
506
  readonly all: {
503
507
  readonly eq: readonly [];
504
508
  readonly sort: readonly ["id"];
@@ -516,6 +516,10 @@ const iosDevices = defineTable({
516
516
  eq: ["status"],
517
517
  sort: ["id"]
518
518
  },
519
+ byRegistration: {
520
+ eq: [],
521
+ sort: ["registered_at_ms"]
522
+ },
519
523
  all: {
520
524
  eq: [],
521
525
  sort: ["id"]
@@ -24,6 +24,12 @@ const WINDOW_MS = 6e4;
24
24
  /** Log rows a compaction reads from each log table for one group. */
25
25
  const LOG_PAGE = 200;
26
26
  /**
27
+ * How old a log row this process can't apply must be before its reads step
28
+ * past it: older than any transaction still committing, between servers
29
+ * whose clocks agree this closely.
30
+ */
31
+ const SKIP_AFTER_MS = 3e5;
32
+ /**
27
33
  * Groups one compaction applies: after a commit, so the request that runs
28
34
  * it waits for one group; before a read; and on flush.
29
35
  */
@@ -154,23 +160,41 @@ const rewrite = (change, key, current) => {
154
160
  previous: current
155
161
  };
156
162
  };
163
+ /** A shard row's place in what `readCurrent` read. */
164
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
165
+ /** The shard key each change writes: shard 0, since one compaction runs at a time. */
166
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
157
167
  /**
158
- * The write for each change on shard 0, since one compaction runs at a time:
159
- * a blind increment that creates the row for counters, and a guarded rewrite
160
- * for gauges and sketches, whose rows are read in one batch per table.
168
+ * The current rows of the changes that rewrite theirs (gauges and sketches),
169
+ * each once, in one batch per table.
161
170
  */
162
- const compile = async (adapter, changes) => {
163
- const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
171
+ const readCurrent = async (adapter, changes) => {
172
+ const keys = keysOf(changes);
164
173
  const reads = /* @__PURE__ */ new Map();
165
174
  changes.forEach((change, at) => {
166
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
175
+ if (!rewrites(change)) return;
176
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
177
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
178
+ reads.set(change.model, wanted);
167
179
  });
168
180
  const current = /* @__PURE__ */ new Map();
169
- await Promise.all([...reads].map(async ([model, positions]) => {
170
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
171
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
181
+ await Promise.all([...reads].map(async ([model, wanted]) => {
182
+ const keys = [...wanted.values()];
183
+ const rows = await adapter.get(model.table, keys);
184
+ keys.forEach((key, at) => {
185
+ current.set(rowId(model, key), rows[at] ?? null);
186
+ });
172
187
  }));
173
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
188
+ return current;
189
+ };
190
+ /**
191
+ * The write for each change: a blind increment that creates the row for
192
+ * counters, and a guarded rewrite for gauges and sketches, over the rows
193
+ * `current` read.
194
+ */
195
+ const build = (changes, current) => {
196
+ const keys = keysOf(changes);
197
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
174
198
  };
175
199
  const isOp = (op) => op !== void 0;
176
200
  const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
@@ -252,6 +276,16 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
252
276
  let compacting;
253
277
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
254
278
  const known = /* @__PURE__ */ new Map();
279
+ /**
280
+ * Each log table's last row of a run at its head that this process can't
281
+ * apply (it names an aggregate or metric this schema lacks), whose reads
282
+ * start past it. The rows wait for a process that can apply them, and a
283
+ * restart reads them again.
284
+ */
285
+ const skipped = LOG_TABLES.map(() => void 0);
286
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
287
+ /** When a log row's transaction stamped its ID. */
288
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
255
289
  const idOf = (shard, id) => JSON.stringify([shard, id]);
256
290
  /** The lease row as stored once `set` is written over it. */
257
291
  const leaseOp = (held, set) => {
@@ -367,14 +401,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
367
401
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
368
402
  const page = await engine.reads.findMany(name, {
369
403
  index: "oldest",
370
- limit: LOG_PAGE
404
+ limit: LOG_PAGE,
405
+ ...past(shard)
371
406
  });
372
407
  more ||= page.next !== void 0;
373
- return (await Promise.all(page.rows.map(async (row) => ({
408
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
374
409
  shard,
375
410
  row,
376
411
  changes: await decode(String(row.changes))
377
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
412
+ })));
413
+ const settled = now() - SKIP_AFTER_MS;
414
+ for (const { row, changes } of decoded) {
415
+ const id = String(row.id);
416
+ if (changes !== void 0 || stampOf(id) >= settled) break;
417
+ skipped[shard] = id;
418
+ }
419
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
378
420
  ...entry,
379
421
  changes
380
422
  }]);
@@ -382,7 +424,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
382
424
  more
383
425
  };
384
426
  };
385
- const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
386
427
  /**
387
428
  * Applies the oldest pending log rows whose merged changes fit in one
388
429
  * atomic write with the lease, which lists them as applied; the rows are
@@ -391,12 +432,14 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
391
432
  * log rows it applied whole, or undefined when a conflict stopped it.
392
433
  */
393
434
  const applyGroup = async (held, logs) => {
435
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
436
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
394
437
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
395
438
  const batch = logs.slice(0, count);
396
439
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
397
440
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
398
441
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
399
- const ops = [...await rowsFor([...changes.values()]), lease.op];
442
+ const ops = [...rowsFor([...changes.values()]), lease.op];
400
443
  if (!adapter.fits(ops)) continue;
401
444
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
402
445
  return await commit(ops) ? {
@@ -418,7 +461,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
418
461
  };
419
462
  const lease = leaseOp(held, {});
420
463
  const ops = [
421
- ...await rowsFor(entries.slice(0, take)),
464
+ ...rowsFor(entries.slice(0, take)),
422
465
  kept,
423
466
  lease.op
424
467
  ];
@@ -439,11 +482,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
439
482
  if (held === void 0) return;
440
483
  let pending = true;
441
484
  let clear = false;
485
+ let carried;
442
486
  try {
443
487
  for (let group = 0;; group += 1) {
444
488
  clear = await deleteApplied(held);
445
489
  if (!clear || !pending || group === groups) break;
446
- const { logs, more } = await readLogs();
490
+ const { logs, more } = carried ?? await readLogs();
447
491
  if (logs.length === 0) {
448
492
  pending = false;
449
493
  break;
@@ -451,6 +495,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
451
495
  const applied = await applyGroup(held, logs);
452
496
  if (applied === void 0) break;
453
497
  [held, clear] = [applied.held, false];
498
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
499
+ carried = rest.length > 0 ? {
500
+ logs: rest,
501
+ more
502
+ } : void 0;
454
503
  pending = more || applied.count < logs.length;
455
504
  }
456
505
  } finally {
@@ -470,9 +519,10 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
470
519
  });
471
520
  let checking;
472
521
  /** Whether any log row waits; reads at once share one check. */
473
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
522
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
474
523
  index: "oldest",
475
- limit: 1
524
+ limit: 1,
525
+ ...past(shard)
476
526
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
477
527
  checking = void 0;
478
528
  });
@@ -24,6 +24,12 @@ const WINDOW_MS = 6e4;
24
24
  /** Log rows a compaction reads from each log table for one group. */
25
25
  const LOG_PAGE = 200;
26
26
  /**
27
+ * How old a log row this process can't apply must be before its reads step
28
+ * past it: older than any transaction still committing, between servers
29
+ * whose clocks agree this closely.
30
+ */
31
+ const SKIP_AFTER_MS = 3e5;
32
+ /**
27
33
  * Groups one compaction applies: after a commit, so the request that runs
28
34
  * it waits for one group; before a read; and on flush.
29
35
  */
@@ -154,23 +160,41 @@ const rewrite = (change, key, current) => {
154
160
  previous: current
155
161
  };
156
162
  };
163
+ /** A shard row's place in what `readCurrent` read. */
164
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
165
+ /** The shard key each change writes: shard 0, since one compaction runs at a time. */
166
+ const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
157
167
  /**
158
- * The write for each change on shard 0, since one compaction runs at a time:
159
- * a blind increment that creates the row for counters, and a guarded rewrite
160
- * for gauges and sketches, whose rows are read in one batch per table.
168
+ * The current rows of the changes that rewrite theirs (gauges and sketches),
169
+ * each once, in one batch per table.
161
170
  */
162
- const compile = async (adapter, changes) => {
163
- const keys = changes.map(({ key }) => [...key.slice(0, -1), 0]);
171
+ const readCurrent = async (adapter, changes) => {
172
+ const keys = keysOf(changes);
164
173
  const reads = /* @__PURE__ */ new Map();
165
174
  changes.forEach((change, at) => {
166
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
175
+ if (!rewrites(change)) return;
176
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
177
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
178
+ reads.set(change.model, wanted);
167
179
  });
168
180
  const current = /* @__PURE__ */ new Map();
169
- await Promise.all([...reads].map(async ([model, positions]) => {
170
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
171
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
181
+ await Promise.all([...reads].map(async ([model, wanted]) => {
182
+ const keys = [...wanted.values()];
183
+ const rows = await adapter.get(model.table, keys);
184
+ keys.forEach((key, at) => {
185
+ current.set(rowId(model, key), rows[at] ?? null);
186
+ });
172
187
  }));
173
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
188
+ return current;
189
+ };
190
+ /**
191
+ * The write for each change: a blind increment that creates the row for
192
+ * counters, and a guarded rewrite for gauges and sketches, over the rows
193
+ * `current` read.
194
+ */
195
+ const build = (changes, current) => {
196
+ const keys = keysOf(changes);
197
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
174
198
  };
175
199
  const isOp = (op) => op !== void 0;
176
200
  const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
@@ -252,6 +276,16 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
252
276
  let compacting;
253
277
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
254
278
  const known = /* @__PURE__ */ new Map();
279
+ /**
280
+ * Each log table's last row of a run at its head that this process can't
281
+ * apply (it names an aggregate or metric this schema lacks), whose reads
282
+ * start past it. The rows wait for a process that can apply them, and a
283
+ * restart reads them again.
284
+ */
285
+ const skipped = LOG_TABLES.map(() => void 0);
286
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
287
+ /** When a log row's transaction stamped its ID. */
288
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
255
289
  const idOf = (shard, id) => JSON.stringify([shard, id]);
256
290
  /** The lease row as stored once `set` is written over it. */
257
291
  const leaseOp = (held, set) => {
@@ -367,14 +401,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
367
401
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
368
402
  const page = await engine.reads.findMany(name, {
369
403
  index: "oldest",
370
- limit: LOG_PAGE
404
+ limit: LOG_PAGE,
405
+ ...past(shard)
371
406
  });
372
407
  more ||= page.next !== void 0;
373
- return (await Promise.all(page.rows.map(async (row) => ({
408
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
374
409
  shard,
375
410
  row,
376
411
  changes: await decode(String(row.changes))
377
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
412
+ })));
413
+ const settled = now() - SKIP_AFTER_MS;
414
+ for (const { row, changes } of decoded) {
415
+ const id = String(row.id);
416
+ if (changes !== void 0 || stampOf(id) >= settled) break;
417
+ skipped[shard] = id;
418
+ }
419
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
378
420
  ...entry,
379
421
  changes
380
422
  }]);
@@ -382,7 +424,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
382
424
  more
383
425
  };
384
426
  };
385
- const rowsFor = async (changes) => (await compile(adapter, changes)).filter(isOp);
386
427
  /**
387
428
  * Applies the oldest pending log rows whose merged changes fit in one
388
429
  * atomic write with the lease, which lists them as applied; the rows are
@@ -391,12 +432,14 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
391
432
  * log rows it applied whole, or undefined when a conflict stopped it.
392
433
  */
393
434
  const applyGroup = async (held, logs) => {
435
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
436
+ const rowsFor = (changes) => build(changes, current).filter(isOp);
394
437
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
395
438
  const batch = logs.slice(0, count);
396
439
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
397
440
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
398
441
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
399
- const ops = [...await rowsFor([...changes.values()]), lease.op];
442
+ const ops = [...rowsFor([...changes.values()]), lease.op];
400
443
  if (!adapter.fits(ops)) continue;
401
444
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
402
445
  return await commit(ops) ? {
@@ -418,7 +461,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
418
461
  };
419
462
  const lease = leaseOp(held, {});
420
463
  const ops = [
421
- ...await rowsFor(entries.slice(0, take)),
464
+ ...rowsFor(entries.slice(0, take)),
422
465
  kept,
423
466
  lease.op
424
467
  ];
@@ -439,11 +482,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
439
482
  if (held === void 0) return;
440
483
  let pending = true;
441
484
  let clear = false;
485
+ let carried;
442
486
  try {
443
487
  for (let group = 0;; group += 1) {
444
488
  clear = await deleteApplied(held);
445
489
  if (!clear || !pending || group === groups) break;
446
- const { logs, more } = await readLogs();
490
+ const { logs, more } = carried ?? await readLogs();
447
491
  if (logs.length === 0) {
448
492
  pending = false;
449
493
  break;
@@ -451,6 +495,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
451
495
  const applied = await applyGroup(held, logs);
452
496
  if (applied === void 0) break;
453
497
  [held, clear] = [applied.held, false];
498
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
499
+ carried = rest.length > 0 ? {
500
+ logs: rest,
501
+ more
502
+ } : void 0;
454
503
  pending = more || applied.count < logs.length;
455
504
  }
456
505
  } finally {
@@ -470,9 +519,10 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs
470
519
  });
471
520
  let checking;
472
521
  /** Whether any log row waits; reads at once share one check. */
473
- const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
522
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
474
523
  index: "oldest",
475
- limit: 1
524
+ limit: 1,
525
+ ...past(shard)
476
526
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
477
527
  checking = void 0;
478
528
  });
@@ -1,17 +1,47 @@
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");
4
6
  const require_settingsMigrator = require("./settingsMigrator.cjs");
5
7
  //#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({
8
+ /** Each table, and the index tables of its multi-valued indexes. */
9
+ const flatten = (shapes) => shapes.flatMap((shape) => [shape, ...flatten(shape.indexes.flatMap((index) => index.kind === "table" ? [index.table] : []))]);
10
+ /**
11
+ * MySQL declares a table's indexes in its CREATE TABLE, which a table an
12
+ * earlier release created skips, and has no CREATE INDEX IF NOT EXISTS: the
13
+ * indexes the tables lack, created one by one.
14
+ */
15
+ const missingMysqlIndexes = async (executor, schema, tablePrefix) => {
16
+ const quote = (name) => require_sqlSchema.quoteSql("mysql", name);
17
+ const { rows } = await executor.execute({
18
+ sql: "SELECT DISTINCT TABLE_NAME AS t, INDEX_NAME AS i FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE()",
19
+ params: []
20
+ });
21
+ const folded = (table, index) => JSON.stringify([String(table).toLowerCase(), String(index).toLowerCase()]);
22
+ const present = new Set(rows.map(({ t, i }) => folded(t, i)));
23
+ return flatten(require_sqlSchema.sqlTableShapes("mysql", [...schema.tables, require_fence.SETTINGS_TABLE], tablePrefix)).flatMap((shape) => shape.indexes.flatMap((index) => index.kind === "index" && !present.has(folded(shape.name, index.name)) ? [`CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quote(index.name)} ON ${quote(shape.name)} (${index.columns.map(quote).join(", ")})`] : []));
24
+ };
25
+ /**
26
+ * Runs the tables' statements, then the settings rows last, in one
27
+ * transaction where the dialect's DDL is transactional. On MySQL the indexes
28
+ * existing tables lack go between them, so the settings move only once
29
+ * every index exists.
30
+ */
31
+ const run = async (executor, tables, settings, schema, tablePrefix) => {
32
+ const each = async (connection, sqls) => {
33
+ for (const sql of sqls) await connection.execute({
10
34
  sql,
11
35
  params: []
12
36
  });
13
37
  };
14
- await (executor.dialect === "mysql" ? each(executor) : executor.transaction(each));
38
+ if (executor.dialect !== "mysql") {
39
+ await executor.transaction((connection) => each(connection, [...tables, ...settings]));
40
+ return;
41
+ }
42
+ await each(executor, tables);
43
+ await each(executor, await missingMysqlIndexes(executor, schema, tablePrefix));
44
+ await each(executor, settings);
15
45
  };
16
46
  /**
17
47
  * `hot-updater db migrate` and `db generate` for an SQL provider on the
@@ -28,6 +58,8 @@ const createEngineSqlMigrator = (options) => {
28
58
  require_settingsMigrator.refuseV0Database(options.adapterName, stored);
29
59
  if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return require_fixedMigratorShared.getEmptyMigrationResult();
30
60
  const statements = require_engineSql.generateEngineSql(options.executor.dialect, options.schema, options.settings, options);
61
+ const settingsSql = require_engineSql.settingsStatements(options.executor.dialect, options.settings, options.tablePrefix);
62
+ const tablesSql = statements.slice(0, -settingsSql.length || void 0);
31
63
  return {
32
64
  operations: [...options.schema.tables.map((table) => ({
33
65
  type: "create-table",
@@ -43,7 +75,7 @@ const createEngineSqlMigrator = (options) => {
43
75
  description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
44
76
  }]],
45
77
  getSQL: () => statements.map((statement) => `${statement};`).join("\n\n"),
46
- execute: () => run(options.executor, statements)
78
+ execute: () => run(options.executor, tablesSql, settingsSql, options.schema, options.tablePrefix)
47
79
  };
48
80
  };
49
81
  return {
@@ -1,17 +1,47 @@
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 { quoteSql, sqlTableShapes } from "../database/sql/sqlSchema.mjs";
5
+ import { generateEngineSql, settingsStatements } from "./engineSql.mjs";
4
6
  import { readStoredSettings, refuseV0Database, storedSchemaVersion } from "./settingsMigrator.mjs";
5
7
  //#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({
8
+ /** Each table, and the index tables of its multi-valued indexes. */
9
+ const flatten = (shapes) => shapes.flatMap((shape) => [shape, ...flatten(shape.indexes.flatMap((index) => index.kind === "table" ? [index.table] : []))]);
10
+ /**
11
+ * MySQL declares a table's indexes in its CREATE TABLE, which a table an
12
+ * earlier release created skips, and has no CREATE INDEX IF NOT EXISTS: the
13
+ * indexes the tables lack, created one by one.
14
+ */
15
+ const missingMysqlIndexes = async (executor, schema, tablePrefix) => {
16
+ const quote = (name) => quoteSql("mysql", name);
17
+ const { rows } = await executor.execute({
18
+ sql: "SELECT DISTINCT TABLE_NAME AS t, INDEX_NAME AS i FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE()",
19
+ params: []
20
+ });
21
+ const folded = (table, index) => JSON.stringify([String(table).toLowerCase(), String(index).toLowerCase()]);
22
+ const present = new Set(rows.map(({ t, i }) => folded(t, i)));
23
+ return flatten(sqlTableShapes("mysql", [...schema.tables, SETTINGS_TABLE], tablePrefix)).flatMap((shape) => shape.indexes.flatMap((index) => index.kind === "index" && !present.has(folded(shape.name, index.name)) ? [`CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quote(index.name)} ON ${quote(shape.name)} (${index.columns.map(quote).join(", ")})`] : []));
24
+ };
25
+ /**
26
+ * Runs the tables' statements, then the settings rows last, in one
27
+ * transaction where the dialect's DDL is transactional. On MySQL the indexes
28
+ * existing tables lack go between them, so the settings move only once
29
+ * every index exists.
30
+ */
31
+ const run = async (executor, tables, settings, schema, tablePrefix) => {
32
+ const each = async (connection, sqls) => {
33
+ for (const sql of sqls) await connection.execute({
10
34
  sql,
11
35
  params: []
12
36
  });
13
37
  };
14
- await (executor.dialect === "mysql" ? each(executor) : executor.transaction(each));
38
+ if (executor.dialect !== "mysql") {
39
+ await executor.transaction((connection) => each(connection, [...tables, ...settings]));
40
+ return;
41
+ }
42
+ await each(executor, tables);
43
+ await each(executor, await missingMysqlIndexes(executor, schema, tablePrefix));
44
+ await each(executor, settings);
15
45
  };
16
46
  /**
17
47
  * `hot-updater db migrate` and `db generate` for an SQL provider on the
@@ -28,6 +58,8 @@ const createEngineSqlMigrator = (options) => {
28
58
  refuseV0Database(options.adapterName, stored);
29
59
  if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
30
60
  const statements = generateEngineSql(options.executor.dialect, options.schema, options.settings, options);
61
+ const settingsSql = settingsStatements(options.executor.dialect, options.settings, options.tablePrefix);
62
+ const tablesSql = statements.slice(0, -settingsSql.length || void 0);
31
63
  return {
32
64
  operations: [...options.schema.tables.map((table) => ({
33
65
  type: "create-table",
@@ -43,7 +75,7 @@ const createEngineSqlMigrator = (options) => {
43
75
  description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
44
76
  }]],
45
77
  getSQL: () => statements.map((statement) => `${statement};`).join("\n\n"),
46
- execute: () => run(options.executor, statements)
78
+ execute: () => run(options.executor, tablesSql, settingsSql, options.schema, options.tablePrefix)
47
79
  };
48
80
  };
49
81
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hot-updater/plugin-core",
3
- "version": "1.2.0-rc.44",
3
+ "version": "1.2.0-rc.46",
4
4
  "type": "module",
5
5
  "description": "React Native OTA solution for self-hosted",
6
6
  "sideEffects": false,
@@ -45,7 +45,7 @@
45
45
  "es-toolkit": "^1.32.0",
46
46
  "mime": "^4.0.4",
47
47
  "verkit": "0.4.0",
48
- "@hot-updater/protocol": "1.2.0-rc.44"
48
+ "@hot-updater/protocol": "1.2.0-rc.46"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@electric-sql/pglite": "0.4.1",