@broberg/db-sdk 0.3.0 → 0.4.0

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.
@@ -1,3 +1,9 @@
1
+ import {
2
+ PG_OPTIONS,
3
+ toResult,
4
+ toResult2
5
+ } from "../chunk-ONXYOFVT.js";
6
+
1
7
  // src/switchable/switchable.ts
2
8
  var UNSUPPORTED = "@broberg/db-sdk/switchable: this postgres.js version does not have the Query internals the switch routes .raw by (3.4.x) \u2014 refusing rather than running on the wrong database";
3
9
  var isQuery = (x) => {
@@ -297,12 +303,22 @@ async function tables(db) {
297
303
  from pg_index i join pg_attribute a on a.attrelid = i.indrelid and a.attnum = any(i.indkey)
298
304
  where i.indrelid = c.oid and i.indisprimary) as pk,
299
305
  (select array_agg(a.attname::text order by a.attnum) from pg_attribute a
300
- where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped) as cols
306
+ where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped) as cols,
307
+ (select array_agg(a.attname::text order by a.attnum) from pg_attribute a
308
+ where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped and a.attgenerated <> '') as gen,
309
+ (select array_agg(a.attname::text order by a.attnum) from pg_attribute a
310
+ where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped and a.attidentity = 'a') as ida
301
311
  from pg_class c
302
312
  where c.relnamespace = current_schema()::regnamespace and c.relkind = 'r'
303
313
  order by 1`
304
314
  );
305
- return rows.map((r) => ({ name: String(r.name), pk: r.pk ?? [], cols: r.cols }));
315
+ return rows.map((r) => ({
316
+ name: String(r.name),
317
+ pk: r.pk ?? [],
318
+ cols: r.cols,
319
+ generated: r.gen ?? [],
320
+ identityAlways: r.ida ?? []
321
+ }));
306
322
  }
307
323
  async function fingerprints(db, tabs) {
308
324
  const out = /* @__PURE__ */ new Map();
@@ -327,8 +343,10 @@ async function fingerprints(db, tabs) {
327
343
  return out;
328
344
  }
329
345
  async function captureBaseline(reserve, o) {
346
+ return writeBaseline(reserve, await fingerprints(reserve, await tables(reserve)), o);
347
+ }
348
+ async function writeBaseline(reserve, rows, o) {
330
349
  const { schema } = { ...RECONCILE_DEFAULTS, ...o };
331
- const rows = await fingerprints(reserve, await tables(reserve));
332
350
  const keys = [...rows.keys()];
333
351
  const table = baselineTable(o);
334
352
  await reserve.batch([
@@ -350,10 +368,60 @@ async function baselineAt(reserve, o) {
350
368
  const at = rows[0]?.at;
351
369
  return at ? Number(at) : null;
352
370
  }
353
- async function readBaseline(reserve, o) {
354
- const { rows } = await reserve.execute(`select "key", "h" from ${baselineTable(o)}`);
371
+ async function readBaseline(reserve, o, only) {
372
+ const { rows } = only ? await reserve.execute({ sql: `select "key", "h" from ${baselineTable(o)} where "key" = any($1::text[])`, args: [only] }) : await reserve.execute(`select "key", "h" from ${baselineTable(o)}`);
355
373
  return new Map(rows.map((r) => [String(r.key), String(r.h)]));
356
374
  }
375
+ async function reserveHorizon(reserve) {
376
+ const { rows } = await reserve.execute(
377
+ `select (pg_snapshot_xmin(pg_current_snapshot())::text::bigint % 4294967296)::text as x,
378
+ (pg_current_xact_id()::text::bigint % 4294967296)::text as c`
379
+ );
380
+ return { xmin: String(rows[0].x), at: String(rows[0].c) };
381
+ }
382
+ var keyExpr = (t) => `jsonb_build_array(${t.pk.map((c) => `x.${q2(c)}`).join(", ")})::text`;
383
+ async function deltaFingerprints(reserve, primary, tabs, since) {
384
+ const R = /* @__PURE__ */ new Map();
385
+ const P = /* @__PURE__ */ new Map();
386
+ if (tabs.length === 0) return { R, P };
387
+ const [, ...res] = await reserve.batch([
388
+ UTC,
389
+ ...tabs.flatMap((t) => [
390
+ { sql: `select ${keyExpr(t)} as k, md5(to_jsonb(x)::text) as h from ${q2(t.name)} x where x.xmin::text::bigint >= $1::bigint`, args: [since.xmin] },
391
+ `select count(*)::bigint as n from ${q2(t.name)}`
392
+ ])
393
+ ]);
394
+ const changed = tabs.map((_, i) => res[i * 2].rows.map((r) => [String(r.k), String(r.h)]));
395
+ const countR = tabs.map((_, i) => Number(res[i * 2 + 1].rows[0].n));
396
+ const [, ...pres] = await primary.batch([
397
+ UTC,
398
+ ...tabs.flatMap((t, i) => [
399
+ { sql: `select ${keyExpr(t)} as k, md5(to_jsonb(x)::text) as h from ${q2(t.name)} x where ${keyExpr(t)} = any($1::text[])`, args: [changed[i].map(([k]) => k)] },
400
+ `select count(*)::bigint as n from ${q2(t.name)}`
401
+ ])
402
+ ]);
403
+ const needKeys = [];
404
+ tabs.forEach((t, i) => {
405
+ const onP = new Map(pres[i * 2].rows.map((r) => [String(r.k), String(r.h)]));
406
+ for (const [k, h] of changed[i]) R.set(`${t.name}${SEP}${k}`, h);
407
+ for (const [k, h] of onP) P.set(`${t.name}${SEP}${k}`, h);
408
+ const inserted = changed[i].filter(([k]) => !onP.has(k)).length;
409
+ if (Number(pres[i * 2 + 1].rows[0].n) + inserted !== countR[i]) needKeys.push(i);
410
+ });
411
+ for (const i of needKeys) {
412
+ const t = tabs[i];
413
+ const [rk, pk] = await Promise.all([
414
+ reserve.execute(`select ${keyExpr(t)} as k from ${q2(t.name)} x`),
415
+ primary.batch([UTC, `select ${keyExpr(t)} as k, md5(to_jsonb(x)::text) as h from ${q2(t.name)} x`]).then((r) => r[1])
416
+ ]);
417
+ const onR = new Set(rk.rows.map((r) => String(r.k)));
418
+ for (const r of pk.rows) {
419
+ const k = String(r.k);
420
+ if (!onR.has(k)) P.set(`${t.name}${SEP}${k}`, String(r.h));
421
+ }
422
+ }
423
+ return { R, P };
424
+ }
357
425
  async function reconcile(reserve, primary, opts2) {
358
426
  const { bypass } = { ...RECONCILE_DEFAULTS, ...opts2 };
359
427
  const [rt, pt] = await Promise.all([tables(reserve), tables(primary)]);
@@ -364,7 +432,24 @@ async function reconcile(reserve, primary, opts2) {
364
432
  ...pt.filter((t) => !rt.some((r) => r.name === t.name)).map((t) => t.name)
365
433
  ];
366
434
  if (schemaMismatch.length) return { upserts: 0, deletes: 0, conflicts: [], schemaMismatch, written: 0 };
367
- const [R, P, B] = await Promise.all([fingerprints(reserve, rt), fingerprints(primary, pt), readBaseline(reserve, opts2)]);
435
+ let R;
436
+ let P;
437
+ let B;
438
+ const since = opts2.since && Number(opts2.since.at) >= Number(opts2.since.xmin) ? opts2.since : void 0;
439
+ if (since && await reserveHorizon(reserve).then((h) => Number(h.at) >= Number(since.xmin))) {
440
+ const keyed = rt.filter((t) => t.pk.length);
441
+ const whole = rt.filter((t) => !t.pk.length);
442
+ const [d, wr, wp] = await Promise.all([
443
+ deltaFingerprints(reserve, primary, keyed, since),
444
+ fingerprints(reserve, whole),
445
+ fingerprints(primary, pt.filter((t) => !t.pk.length))
446
+ ]);
447
+ R = new Map([...d.R, ...wr]);
448
+ P = new Map([...d.P, ...wp]);
449
+ B = await readBaseline(reserve, opts2, [.../* @__PURE__ */ new Set([...R.keys(), ...P.keys()])]);
450
+ } else {
451
+ [R, P, B] = await Promise.all([fingerprints(reserve, rt), fingerprints(primary, pt), readBaseline(reserve, opts2)]);
452
+ }
368
453
  const conflicts = [];
369
454
  const copies = [];
370
455
  for (const k of /* @__PURE__ */ new Set([...R.keys(), ...P.keys()])) {
@@ -417,13 +502,15 @@ async function reconcile(reserve, primary, opts2) {
417
502
  }
418
503
  for (const table2 of order) {
419
504
  const t = byName.get(table2);
420
- const set = t.cols.filter((col) => !t.pk.includes(col));
505
+ const insertable = t.cols.filter((col) => !t.generated.includes(col));
506
+ const set = insertable.filter((col) => !t.pk.includes(col) && !t.identityAlways.includes(col));
507
+ const colList = insertable.map(q2).join(", ");
421
508
  const onConflict = t.pk.length ? `on conflict (${t.pk.map(q2).join(", ")}) do ${set.length ? `update set ${set.map((col) => `${q2(col)} = excluded.${q2(col)}`).join(", ")}` : "nothing"}` : "";
422
509
  for (const x of upserts.get(table2) ?? []) {
423
510
  const j = rowsByH.get(`${table2}${SEP}${x.h}`);
424
511
  if (j === void 0) continue;
425
512
  writes.push({
426
- sql: `insert into ${q2(table2)} select * from jsonb_populate_record(null::${q2(table2)}, $1::text::jsonb) ${onConflict}`,
513
+ sql: `insert into ${q2(table2)} (${colList}) overriding system value select ${colList} from jsonb_populate_record(null::${q2(table2)}, $1::text::jsonb) ${onConflict}`,
427
514
  args: [j]
428
515
  });
429
516
  meaning.push({ key: `${table2}${SEP}${x.key}`, h: x.h, counted: "always" });
@@ -446,6 +533,96 @@ async function reconcile(reserve, primary, opts2) {
446
533
  ]);
447
534
  return { ...plan, written: written.length };
448
535
  }
536
+ async function syncSequences(db) {
537
+ const { rows } = await db.execute(
538
+ `select c.relname as t, a.attname as col, pg_get_serial_sequence(format('%I.%I', n.nspname, c.relname), a.attname) as seq
539
+ from pg_class c join pg_namespace n on n.oid = c.relnamespace join pg_attribute a on a.attrelid = c.oid
540
+ where c.relnamespace = current_schema()::regnamespace and c.relkind = 'r' and a.attnum > 0 and not a.attisdropped
541
+ and pg_get_serial_sequence(format('%I.%I', n.nspname, c.relname), a.attname) is not null
542
+ order by 1, 2`
543
+ );
544
+ if (rows.length === 0) return [];
545
+ await db.batch(
546
+ rows.map((r) => ({
547
+ sql: `select setval($1::regclass, x.m) from (select max(${q2(String(r.col))}) as m from ${q2(String(r.t))}) x
548
+ where x.m is not null and x.m > (select case when is_called then last_value else last_value - 1 end from ${String(r.seq)})`,
549
+ args: [String(r.seq)]
550
+ }))
551
+ );
552
+ return rows.map((r) => `${String(r.t)}.${String(r.col)}`);
553
+ }
554
+ async function freezeBaseline(reserve, o) {
555
+ await reserve.execute(`drop table if exists ${baselineTable(o)}`);
556
+ const s = await openSession(reserve.raw);
557
+ try {
558
+ await s.execute("begin isolation level repeatable read read only");
559
+ await s.execute("select 1");
560
+ } catch (e) {
561
+ s.release();
562
+ throw e;
563
+ }
564
+ let settled = false;
565
+ return {
566
+ async finish() {
567
+ if (settled) throw new Error("freezeBaseline: already finished or cancelled");
568
+ settled = true;
569
+ let rows;
570
+ try {
571
+ rows = await fingerprints(s, await tables(s));
572
+ await s.execute("commit");
573
+ } catch (e) {
574
+ await s.execute("rollback").catch((rb) => {
575
+ e.rollbackError = rb;
576
+ });
577
+ throw e;
578
+ } finally {
579
+ s.release();
580
+ }
581
+ return writeBaseline(reserve, rows, o);
582
+ },
583
+ async cancel() {
584
+ if (settled) return;
585
+ settled = true;
586
+ try {
587
+ await s.execute("rollback");
588
+ } finally {
589
+ s.release();
590
+ }
591
+ }
592
+ };
593
+ }
594
+ async function openSession(raw) {
595
+ let exec;
596
+ let release;
597
+ if (raw && typeof raw.reserve === "function") {
598
+ const max = raw.options?.max;
599
+ if (typeof max === "number" && max < 2) throw new Error(`freezeBaseline needs a pool of at least 2 connections (this one has ${max})`);
600
+ const c = await raw.reserve();
601
+ exec = async (stmt) => {
602
+ const [text, args] = typeof stmt === "string" ? [stmt, []] : [stmt.sql, [...stmt.args ?? []]];
603
+ return toResult2(await c.unsafe(text, args, PG_OPTIONS));
604
+ };
605
+ release = () => c.release();
606
+ } else if (raw && typeof raw.connect === "function") {
607
+ const c = await raw.connect();
608
+ exec = async (stmt) => {
609
+ const [text, args] = typeof stmt === "string" ? [stmt, []] : [stmt.sql, [...stmt.args ?? []]];
610
+ return toResult(await c.query(text, args));
611
+ };
612
+ release = () => c.release();
613
+ } else {
614
+ throw new Error("freezeBaseline needs a postgres.js or pg client (its raw driver gives the dedicated connection)");
615
+ }
616
+ return {
617
+ execute: exec,
618
+ async batch(stmts) {
619
+ const out = [];
620
+ for (const st of stmts) out.push(await exec(st));
621
+ return out;
622
+ },
623
+ release
624
+ };
625
+ }
449
626
  function group(xs) {
450
627
  const m = /* @__PURE__ */ new Map();
451
628
  for (const x of xs) m.set(x.table, [...m.get(x.table) ?? [], x]);
@@ -641,9 +818,11 @@ async function orchestrateSwitch(o) {
641
818
  }
642
819
  let targetOpened = false;
643
820
  let subscriptionOff = false;
821
+ let frozen = null;
644
822
  const restored = [];
645
823
  const abort = async (reason) => {
646
824
  log(`ABORTING: ${reason} \u2014 releasing everyone on the old side`);
825
+ if (frozen) await frozen.cancel().catch((e) => log(`WARNING: the frozen baseline could not be released: ${e}`));
647
826
  log(`aborted: ${JSON.stringify(await all(o.machines, (m) => m.call("/db/abort", {})))}`);
648
827
  if (targetOpened) {
649
828
  try {
@@ -690,10 +869,12 @@ async function orchestrateSwitch(o) {
690
869
  log("TEST: subscription disabled before the hold");
691
870
  }
692
871
  }
872
+ let horizon;
693
873
  if (copyHome) {
694
874
  if (await baselineAt(o.reserve, o.reconcile) === null) {
695
875
  return { outcome: "refused", reason: "no baseline from the switch to the reserve \u2014 the only way back is discardReserveWrites" };
696
876
  }
877
+ horizon = await reserveHorizon(o.reserve);
697
878
  const stop = planStopper(await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, ...o.reconcile }), Boolean(o.skipConflicts), log);
698
879
  if (stop) return { outcome: "refused", reason: stop };
699
880
  }
@@ -720,20 +901,27 @@ async function orchestrateSwitch(o) {
720
901
  }
721
902
  log("subscription disabled");
722
903
  try {
723
- log(`baseline: ${await captureBaseline(o.reserve, o.reconcile)} rows`);
904
+ frozen = await freezeBaseline(o.reserve, o.reconcile);
905
+ log("baseline frozen (read after release)");
724
906
  } catch (e) {
725
- if (!emergency) return abort(`the baseline could not be taken: ${e}`);
907
+ if (!emergency) return abort(`the baseline could not be frozen: ${e}`);
726
908
  log(`WARNING: no baseline (${e}) \u2014 the way back will be discardReserveWrites`);
727
909
  }
728
910
  }
729
911
  if (copyHome) {
730
912
  try {
731
- const stop = planStopper(await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, ...o.reconcile }), Boolean(o.skipConflicts), log);
913
+ const stop = planStopper(await reconcile(o.reserve, o.primary, { apply: true, skipConflicts: o.skipConflicts, since: horizon, ...o.reconcile }), Boolean(o.skipConflicts), log);
732
914
  if (stop) return abort(stop);
733
915
  } catch (e) {
734
916
  return abort(`copying home failed: ${e}`);
735
917
  }
736
918
  }
919
+ try {
920
+ const seqs = await syncSequences(target);
921
+ if (seqs.length) log(`sequences on ${targetLabel}: ${seqs.length} checked`);
922
+ } catch (e) {
923
+ return abort(`the sequences on ${targetLabel} could not be moved up: ${e}`);
924
+ }
737
925
  try {
738
926
  await setFence(target, "open", o.fence);
739
927
  targetOpened = true;
@@ -762,6 +950,15 @@ async function orchestrateSwitch(o) {
762
950
  } catch (e) {
763
951
  log(`WARNING: ${oldLabel} is NOT fenced (${e}) \u2014 fence it when it answers`);
764
952
  }
953
+ if (frozen) {
954
+ const f = frozen;
955
+ frozen = null;
956
+ try {
957
+ log(`baseline: ${await f.finish()} rows (read after release)`);
958
+ } catch (e) {
959
+ log(`WARNING: the baseline could not be read (${e}) \u2014 the way home will refuse; only discardReserveWrites can bring the app back`);
960
+ }
961
+ }
765
962
  if (release.some((r) => !ready(r))) {
766
963
  return { outcome: "unconfirmed", reason: "a machine did not confirm release on the new side \u2014 its safety net sends it back; run status NOW", label: newLabel };
767
964
  }
@@ -947,6 +1144,7 @@ export {
947
1144
  createSwitchable,
948
1145
  emergencyGate,
949
1146
  fenceState,
1147
+ freezeBaseline,
950
1148
  httpMachine,
951
1149
  installFence,
952
1150
  judgeReserve,
@@ -956,9 +1154,11 @@ export {
956
1154
  readReserveSlot,
957
1155
  reconcile,
958
1156
  reserveHealth,
1157
+ reserveHorizon,
959
1158
  runGuard,
960
1159
  setFence,
961
1160
  switchToken,
1161
+ syncSequences,
962
1162
  unfencedTables,
963
1163
  watchReserve
964
1164
  };