@protobase/cli 0.130.0 → 0.131.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,17 +1,17 @@
1
1
  //#region src/build/pdfkit-fonts.ts
2
2
  const nodeBuild = /[\\/]pdfkit[\\/]js[\\/]pdfkit\.node\.mjs$/;
3
- const fontLoad = /\b[\w$]+\('#standard-fonts\/(\w+)'\)/g;
3
+ const fontLoad = /\b[\w$]+\('\.\/standard-fonts\/(\w+)\.cjs'\)/g;
4
4
  /**
5
5
  * Bundles pdfkit's standard fonts, which React PDF's renderer writes text in. pdfkit's Node build loads each with a
6
- * `require` of its own subpath import, `#standard-fonts/Helvetica`, made at run time, which a bundle cannot resolve
7
- * from its own folder; this turns each into an import of the font's module beside it.
6
+ * `require` of the font's CommonJS file beside it, `./standard-fonts/Helvetica.cjs`, made at run time, which a bundle
7
+ * cannot resolve from its own folder; this turns each into an import of the font's ES module beside it.
8
8
  */
9
9
  const pdfkitFonts = () => ({
10
10
  name: "protobase-pdfkit-fonts",
11
11
  transform(code, id) {
12
12
  if (!nodeBuild.test(id)) return;
13
13
  const fonts = new Set([...code.matchAll(fontLoad)].map(([, font]) => font));
14
- if (fonts.size === 0) this.error("pdfkit no longer loads its standard fonts as `require(\"#standard-fonts/<Font>\")`; update pdfkitFonts");
14
+ if (fonts.size === 0) this.error("pdfkit no longer loads its standard fonts as `require(\"./standard-fonts/<Font>.cjs\")`; update pdfkitFonts");
15
15
  return {
16
16
  code: [...fonts].map((font) => `import __pdfkitFont${font} from './standard-fonts/${font}.mjs'\n`).join("") + code.replace(fontLoad, (_, font) => `__pdfkitFont${font}`),
17
17
  map: null
@@ -2,6 +2,7 @@ import { moduleFile } from "../module-file.js";
2
2
  import { viteBundle } from "./vite-bundle.js";
3
3
  import { npmWs } from "./npm-ws.js";
4
4
  import { pdfkitFonts } from "./pdfkit-fonts.js";
5
+ import { unicodePropertiesTrie } from "./unicode-properties-trie.js";
5
6
  import { fileURLToPath } from "node:url";
6
7
  //#region src/build/serve-runtime.ts
7
8
  const cliRoot = fileURLToPath(new URL("../..", import.meta.url));
@@ -12,7 +13,11 @@ const buildServeRuntime = async ({ outFile, bun }) => {
12
13
  entry: serveMain,
13
14
  outFile,
14
15
  bun,
15
- plugins: [npmWs(), pdfkitFonts()]
16
+ plugins: [
17
+ npmWs(),
18
+ pdfkitFonts(),
19
+ unicodePropertiesTrie()
20
+ ]
16
21
  });
17
22
  };
18
23
  //#endregion
@@ -0,0 +1,18 @@
1
+ import path from "node:path";
2
+ //#region src/build/unicode-properties-trie.ts
3
+ const entry = /[\\/]unicode-properties[\\/]index\.js$/;
4
+ /**
5
+ * Bundles the Unicode data that React PDF's text layout reads through unicode-properties. Its Node build reads the
6
+ * file `data.trie` beside it at run time, which a bundle does not carry; this takes the build that embeds the same data
7
+ * as base64 instead.
8
+ */
9
+ const unicodePropertiesTrie = () => ({
10
+ name: "protobase-unicode-properties-trie",
11
+ enforce: "pre",
12
+ resolveId(id, importer) {
13
+ if (id !== "#binary-trie" || !importer || !entry.test(importer)) return;
14
+ return path.join(path.dirname(importer), "binaryTrie.browser.js");
15
+ }
16
+ });
17
+ //#endregion
18
+ export { unicodePropertiesTrie };
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.130.0";
2
+ var version = "0.131.0";
3
3
  //#endregion
4
4
  export { version };
@@ -1,18 +1,18 @@
1
- import { stepsOfVersions } from "@protobase/server/internal";
1
+ import { versionRecordRefusal, versionRecordTable } from "@protobase/server/internal";
2
2
  import postgres from "postgres";
3
3
  //#region src/migration/baseline/read-live-store.ts
4
4
  /**
5
5
  * The auth store at `url` as its schema has it, read once in a read-only transaction: every relation of the store's
6
- * schema with its kind and columns, and the parts of steps it recorded: in `auth_steps`, or for a store without it, by
7
- * version in `auth_migrations`. Refuses a store with neither, one made before 0.48, which `protobase auth migration`
8
- * adopts first.
6
+ * schema with its kind and columns, and the parts of steps it recorded in `auth_steps`. Refuses a store without it:
7
+ * one that records versions instead, which Protobase 0.130 moves to `auth_steps` first, or one made before 0.48, which
8
+ * `protobase auth migration` adopts first.
9
9
  */
10
10
  const readLiveStore = async (url, names) => {
11
11
  const sql = postgres(url, {
12
12
  max: 1,
13
13
  onnotice: () => {}
14
14
  });
15
- const record = names.names.table("auth_migrations");
15
+ const record = versionRecordTable(names);
16
16
  const steps = names.names.table("auth_steps");
17
17
  try {
18
18
  return await sql.begin("read only", async (tx) => {
@@ -35,12 +35,8 @@ const readLiveStore = async (url, names) => {
35
35
  relations
36
36
  };
37
37
  }
38
- if (!relations[record.name]) throw new Error(`The auth store has neither ${steps.name} nor ${record.name}, as a store made before 0.48: adopt it with \`protobase auth migration\` and apply that file first`);
39
- const versions = await tx.unsafe(`select ${String(record.columns.version)} as version from ${String(record)} order by 1`);
40
- return {
41
- applied: stepsOfVersions(versions.map(({ version }) => Number(version))),
42
- relations
43
- };
38
+ if (relations[record.name]) throw new Error(versionRecordRefusal(record.name));
39
+ throw new Error(`The auth store has no ${steps.name}, as a store made before 0.48: adopt it with \`protobase auth migration\` and apply that file first`);
44
40
  });
45
41
  } finally {
46
42
  await sql.end();
@@ -5,11 +5,10 @@ import { refuseInconsistent } from "../snapshot/consistency.js";
5
5
  import { writeMigrationFile } from "../snapshot/write-file.js";
6
6
  import { describedModules, readLiveModules } from "./read-live-modules.js";
7
7
  import { readLiveStore } from "./read-live-store.js";
8
- import { baselineStore, stepRecordMigration, storeModel, targetIds } from "@protobase/server/internal";
8
+ import { baselineStore, storeModel, targetIds } from "@protobase/server/internal";
9
9
  //#region src/migration/baseline/write-baseline.ts
10
10
  const intro = `-- Written by \`protobase migration baseline\` from the database: the auth store as the project's earlier migrations made it.
11
- -- It drops nothing, and changes nothing but the record of the store's steps, made from auth_migrations where the store
12
- -- has none; it starts ${snapshotFile}, and \`protobase migration\` writes what the store lacks from it.
11
+ -- It changes nothing; it starts ${snapshotFile}, and \`protobase migration\` writes what the store lacks from it.
13
12
  `;
14
13
  const modulesIntro = `-- Written by \`protobase migration baseline\` from the database: the schema modules the project's earlier migrations
15
14
  -- made, which ${snapshotFile} did not record. It changes nothing; \`protobase migration\` writes what they lack from it.
@@ -17,10 +16,10 @@ const modulesIntro = `-- Written by \`protobase migration baseline\` from the da
17
16
  /**
18
17
  * `protobase migration baseline`: describes, as the database has them, the auth store of a project without a snapshot
19
18
  * and each schema module the config needs that the snapshot lacks, such as one an earlier version's migration made,
20
- * in a numbered migration that only records itself, and the store's steps where it records them by version alone,
21
- * and the snapshot that ends at it, once. Each module of the store that is on is at the step `auth_migrations` records,
22
- * a module that is off but has tables is kept, organizations count as ever on when a table whose rows belong to one has
23
- * the column that names it, and a user table another system made is external. A schema module is at the step its
19
+ * in a numbered migration that only records itself, and the snapshot that ends at it, once. Each module of the store
20
+ * that is on is at the step `auth_steps` records, a module that is off but has tables is kept, organizations count as
21
+ * ever on when a table whose rows belong to one has the column that names it, and a user table another system made is
22
+ * external. A schema module is at the step its
24
23
  * catalogue shows (`SchemaModule.read`). Returns the file's path.
25
24
  */
26
25
  const writeBaseline = async ({ projectDir, dir, auth, modules, url, protobaseVersion, newId }) => {
@@ -50,7 +49,7 @@ const writeBaseline = async ({ projectDir, dir, auth, modules, url, protobaseVer
50
49
  if (!auth && !found) throw new Error("Sign-in is off in the project's config, and the database has none of the schema modules it needs: there is nothing to describe, and `protobase migration` writes them");
51
50
  const store = auth && baselineStore(auth.names, await readLiveStore(url, auth.names));
52
51
  const modulesText = found ? `${described}\n` : "";
53
- const body = !store ? `${modulesIntro}${modulesText}` : store.stepRecord ? `${intro}${modulesText}` : `${intro}${modulesText}\n${stepRecordMigration(auth.names)}\n`;
52
+ const body = store ? `${intro}${modulesText}` : `${modulesIntro}${modulesText}`;
54
53
  const decisions = {
55
54
  modules: {
56
55
  kept: store?.kept ?? [],
@@ -47,9 +47,10 @@ const columnChanges = (relation, before, after, keepsValues = tables.has(relatio
47
47
  });
48
48
  const requiredColumns = (relation, before, after) => after.filter((column) => !before.some((had) => had.name === column.name) && column.notNull && !column.hasDefault && !column.generated).map((column) => `adds the required column ${relation.name}.${column.name} without a default`);
49
49
  const newLimits = (relation, what, before, after) => after.filter((limit) => !before.some((had) => had.name === limit.name && had.definition === limit.definition)).map((limit) => `adds the ${what} ${limit.name} to ${relation.name}, which rows written by older code may break`);
50
- const relationChanges = (before, after, relation) => {
50
+ const relationChanges = (before, after, relation, dropped) => {
51
51
  const now = after.relations.find((found) => found.name === relation.name);
52
52
  const kind = kindNames[relation.kind];
53
+ if (!now && dropped.has(relation.oid)) return [];
53
54
  if (!now) return [`drops, renames or moves ${kind} ${relation.name}`];
54
55
  if (now.kind !== relation.kind) return [`makes ${kind} ${relation.name} a ${kindNames[now.kind]}`];
55
56
  const columns = [byRelation(before.columns, relation.oid), byRelation(after.columns, now.oid)];
@@ -76,9 +77,12 @@ const enumChanges = (before, after) => before.enums.flatMap((had) => {
76
77
  if (!now) return [`drops, renames or moves type ${had.name}`];
77
78
  return had.labels.filter((label) => !now.labels.includes(label)).map((label) => `removes the value ${label} of type ${had.name}`);
78
79
  });
79
- /** What the change from `before` to `after` takes from older code, one line each; none when it only adds. */
80
- const contractions = (before, after) => [
81
- ...before.relations.flatMap((relation) => relationChanges(before, after, relation)),
80
+ /**
81
+ * What the change from `before` to `after` takes from older code, one line each; none when it only adds. `dropped`: the
82
+ * oids of the tables a step of the auth store drops, which no older code reads (`Step.drops`), whose drop takes nothing.
83
+ */
84
+ const contractions = (before, after, dropped = /* @__PURE__ */ new Set()) => [
85
+ ...before.relations.flatMap((relation) => relationChanges(before, after, relation, dropped)),
82
86
  ...functionChanges(before, after),
83
87
  ...enumChanges(before, after)
84
88
  ];
@@ -9,10 +9,10 @@ const lockNotAvailable = "55P03";
9
9
  /**
10
10
  * Applies `sections` to the database at `url` in one transaction it rolls back, reading its schema before them and
11
11
  * after each, so nothing changes: what the whole file takes from older code, each line under the sections that take
12
- * it. Sections that take nothing are
13
- * left out.
12
+ * it. Sections that take nothing are left out, and so is the drop of a table of `dropped`, as SQL text, which a step
13
+ * of the auth store drops and no older code reads (`droppedTableIds`).
14
14
  */
15
- const trialContractions = async (url, sections) => {
15
+ const trialContractions = async (url, sections, dropped = []) => {
16
16
  const sql = postgres(url, {
17
17
  max: 1,
18
18
  onnotice: () => {}
@@ -23,14 +23,19 @@ const trialContractions = async (url, sections) => {
23
23
  await tx.unsafe(`set local lock_timeout = '${lockTimeout}'`);
24
24
  await tx.unsafe(`select set_config('${forceSetting}', 'true', true)`);
25
25
  const before = await readCatalog(tx);
26
+ const droppedOids = /* @__PURE__ */ new Set();
27
+ for (const table of dropped) {
28
+ const [found] = await tx`select to_regclass(${table})::oid::text as oid`;
29
+ if (found?.oid) droppedOids.add(found.oid);
30
+ }
26
31
  const own = [];
27
32
  const sinceStart = [];
28
33
  let previous = before;
29
34
  for (const section of sections) {
30
35
  await tx.unsafe(section.text);
31
36
  const now = await readCatalog(tx);
32
- own.push(contractions(previous, now));
33
- sinceStart.push(contractions(before, now));
37
+ own.push(contractions(previous, now, droppedOids));
38
+ sinceStart.push(contractions(before, now, droppedOids));
34
39
  previous = now;
35
40
  }
36
41
  const whole = sinceStart.at(-1) ?? [];
@@ -28,7 +28,7 @@ const registerMigration = (program) => {
28
28
  force: Boolean(opts.force)
29
29
  });
30
30
  });
31
- const migration = folderOptions(program.command("migration").description("Write what the config and this version of Protobase need beyond protobase.snapshot.json as the project's next numbered SQL migration, and rewrite the snapshot").option("--custom <name>", "write an empty numbered migration to fill by hand, and make the snapshot end at it").option("--record-config", "with --custom: record the config's auth store names in the snapshot, which the file makes the store match").option("--after", "with --custom: write an empty .after.sql beside it too, for statements that cannot run in a transaction, such as create index concurrently").option("--off <choice>", "what becomes of the tables of a sign-in module the config turns off, without asking: keep").option("--force", "write the migration that turns a kept sign-in module on again even while its tables hold rows")).action(async (opts) => {
31
+ const migration = folderOptions(program.command("migration").description("Write what the config and this version of Protobase need beyond protobase.snapshot.json as the project's next numbered SQL migration, and rewrite the snapshot").option("--custom <name>", "write an empty numbered migration to fill by hand, and make the snapshot end at it").option("--record-config", "with --custom: record the config's auth store names in the snapshot, which the file makes the store match").option("--after", "with --custom: write an empty .after.sql beside it too, for statements that cannot run in a transaction, such as create index concurrently").option("--off <choice>", "what becomes of the tables of a sign-in module the config turns off, without asking: keep, archive or delete").option("--force", "write the migration that turns a kept sign-in module on again even while its tables hold rows")).action(async (opts) => {
32
32
  if (opts.recordConfig && !opts.custom) throw new Error("--record-config goes with --custom <name>");
33
33
  if (opts.after && !opts.custom) throw new Error("--after goes with --custom <name>");
34
34
  const { config, auth } = await loadAuthTarget(opts);
@@ -67,7 +67,7 @@ const registerMigration = (program) => {
67
67
  const database = project && url ? {
68
68
  url,
69
69
  parts: migrationParts(project),
70
- contractions: (sections) => trialContractions(url, sections),
70
+ contractions: (sections, dropped) => trialContractions(url, sections, dropped),
71
71
  readModule: (id, input) => schemaModules[id].read(project.db, input)
72
72
  } : void 0;
73
73
  const modules = project ? project.modules : await configModules(config);
@@ -130,6 +130,29 @@ const registerMigration = (program) => {
130
130
  const { dropMigration } = await import("./snapshot/drop.js");
131
131
  out(`deleted ${await dropMigration(process.cwd(), path.resolve(opts.dir))} and took protobase.snapshot.json back\n`);
132
132
  });
133
+ migration.command("contract").description("Sign off the update that turned a sign-in module off with --off archive or delete: write the next migration, which archives what it retired once that update served long enough").option("--dir <dir>", "migrations folder", "db/migrations").option("--hours <hours>", "the hours the file that turned it off must have been applied for, before the migration applies", "24").action(async (opts) => {
134
+ const [{ writeContract }, { signOffHours }] = await Promise.all([import("./sign-off/contract.js"), import("./sign-off/signed-off-file.js")]);
135
+ const file = await writeContract({
136
+ projectDir: process.cwd(),
137
+ dir: path.resolve(opts.dir),
138
+ hours: signOffHours(opts.hours),
139
+ protobaseVersion,
140
+ newId: randomUUID
141
+ });
142
+ out(`wrote ${path.relative(process.cwd(), file)} and protobase.snapshot.json: apply it with the project's migrations once the update has served for ${opts.hours} hours\n`);
143
+ });
144
+ migration.command("delete").description("Write the next migration, which drops for good what `contract` archived of a sign-in module, once nothing wrote it for a period").argument("<module>", "the archived module, such as organizations").option("--dir <dir>", "migrations folder", "db/migrations").option("--hours <hours>", "the hours since the archive was applied, through which retired.writes must count no write of it", "168").action(async (module, opts) => {
145
+ const [{ writeDelete }, { signOffHours }] = await Promise.all([import("./sign-off/delete.js"), import("./sign-off/signed-off-file.js")]);
146
+ const file = await writeDelete({
147
+ projectDir: process.cwd(),
148
+ dir: path.resolve(opts.dir),
149
+ module,
150
+ hours: signOffHours(opts.hours),
151
+ protobaseVersion,
152
+ newId: randomUUID
153
+ });
154
+ out(`wrote ${path.relative(process.cwd(), file)} and protobase.snapshot.json: apply it with the project's migrations\n`);
155
+ });
133
156
  migration.command("up").description("Rewrite protobase.snapshot.json in this version's format").action(async () => {
134
157
  const { upgradeSnapshot } = await import("./snapshot/up.js");
135
158
  out(`${await upgradeSnapshot(process.cwd())}\n`);
@@ -0,0 +1,65 @@
1
+ import { readSnapshot, snapshotFile } from "../snapshot/snapshot-file.js";
2
+ import { readMigrationFiles } from "../snapshot/migration-files.js";
3
+ import { refuseInconsistent } from "../snapshot/consistency.js";
4
+ import { nextMigrationName } from "../../auth/migration-file.js";
5
+ import { writeMigrationFile } from "../snapshot/write-file.js";
6
+ import { signedOffFile } from "./signed-off-file.js";
7
+ import { readdir } from "node:fs/promises";
8
+ import { archiveSchema, archiveStatements, archivedModule, markedSql, revokeStatements, signOffGate } from "@protobase/server/internal";
9
+ //#region src/migration/sign-off/contract.ts
10
+ /** The line `protobase migration contract`'s files open with, under their header. */
11
+ const contractIntro = "-- Written by `protobase migration contract`: it signs off the update of each migration it names, and archives what that update retired.\n";
12
+ /**
13
+ * `protobase migration contract`: writes the next migration, which archives each sign-in module turned off with
14
+ * `--off archive` or `--off delete`, behind a check that refuses until the file that turned it off was applied `hours`
15
+ * ago and another after it; every statement names that file with `-- protobase:contract`. The snapshot moves the
16
+ * modules from `kept` to `archived`. Returns the file's path.
17
+ */
18
+ const writeContract = async ({ projectDir, dir, hours, protobaseVersion, newId }) => {
19
+ const snapshot = await readSnapshot(projectDir);
20
+ const files = await readMigrationFiles(dir);
21
+ refuseInconsistent(snapshot, files);
22
+ const deferred = (snapshot?.decisions.modules.kept ?? []).filter((kept) => kept.off !== void 0);
23
+ if (!snapshot?.model.auth || deferred.length === 0) throw new Error(`Nothing awaits a sign-off: ${snapshotFile} has no sign-in module turned off with \`--off archive\` or \`--off delete\``);
24
+ const store = snapshot.model.auth.schema;
25
+ const schema = archiveSchema(Number(nextMigrationName(await readdir(dir), "contract").split("_")[0]));
26
+ const signedOff = [...new Set(deferred.map(({ off }) => off.file))].map((id) => signedOffFile(files, id));
27
+ const id = newId();
28
+ const body = [
29
+ contractIntro,
30
+ ...signedOff.map((file) => `-- The sign-off of ${file.name}: it applies once that file was applied ${hours} hours ago, and a migration after it.\n${markedSql(file.id, [signOffGate(file, hours, "The sign-off", true)])}\n`),
31
+ ...deferred.map(({ off, ...kept }) => `-- ${kept.module} archived to ${schema}: its tables, with no foreign key to the tables still on, and each column it retired as <column>_archive, all still watched in retired.writes.\n${markedSql(off.file, archiveStatements(store, schema, {
32
+ ...kept,
33
+ off
34
+ }))}\n`),
35
+ `-- Nothing but a superuser uses ${schema}: the app's roles and the one applying this file are refused.\n${markedSql(deferred[0].off.file, revokeStatements(schema))}\n`
36
+ ].join("\n");
37
+ const decisions = {
38
+ ...snapshot.decisions,
39
+ modules: {
40
+ kept: snapshot.decisions.modules.kept.filter((kept) => kept.off === void 0),
41
+ archived: [...snapshot.decisions.modules.archived, ...deferred.map((kept) => archivedModule(store, schema, kept, id))]
42
+ }
43
+ };
44
+ const content = {
45
+ name: "contract",
46
+ body,
47
+ additive: false,
48
+ kind: {
49
+ custom: false,
50
+ additive: false,
51
+ breaksOlderCode: true
52
+ }
53
+ };
54
+ const draft = {
55
+ previous: snapshot,
56
+ auth: snapshot.model.auth,
57
+ modules: snapshot.model.modules,
58
+ organizations: { on: false },
59
+ protobaseVersion,
60
+ decisions
61
+ };
62
+ return writeMigrationFile(projectDir, dir, content, draft, id);
63
+ };
64
+ //#endregion
65
+ export { contractIntro, writeContract };
@@ -0,0 +1,50 @@
1
+ import { readSnapshot, snapshotFile } from "../snapshot/snapshot-file.js";
2
+ import { readMigrationFiles } from "../snapshot/migration-files.js";
3
+ import { refuseInconsistent } from "../snapshot/consistency.js";
4
+ import { writeMigrationFile } from "../snapshot/write-file.js";
5
+ import { signedOffFile } from "./signed-off-file.js";
6
+ import { deleteStatements, markedSql, signOffGate, stepRecordOf } from "@protobase/server/internal";
7
+ //#region src/migration/sign-off/delete.ts
8
+ /**
9
+ * `protobase migration delete <module>`: writes the next migration, which drops what the sign-off archived of
10
+ * `module`, its tables and its column archives, and while it is off its rows in `auth_steps`, behind checks that
11
+ * refuse until the archive was applied `hours` ago and while `retired.writes` counts a write of it within them, or does
12
+ * not watch it. The snapshot no longer lists it as archived. Returns the file's path.
13
+ */
14
+ const writeDelete = async ({ projectDir, dir, hours, protobaseVersion, newId, module }) => {
15
+ const snapshot = await readSnapshot(projectDir);
16
+ const files = await readMigrationFiles(dir);
17
+ refuseInconsistent(snapshot, files);
18
+ const archived = snapshot?.decisions.modules.archived ?? [];
19
+ const entry = archived.find((found) => found.module === module);
20
+ if (!snapshot?.model.auth || !entry) {
21
+ const listed = archived.length === 0 ? "none is" : `${archived.map((found) => found.module).join(", ")} ${archived.length === 1 ? "is" : "are"}`;
22
+ throw new Error(`${module} has no archive to delete: ${listed} archived in ${snapshotFile}. A module turned off is archived by \`protobase migration contract\` once turned off with \`--off archive\` or \`--off delete\``);
23
+ }
24
+ const archive = signedOffFile(files, entry.file);
25
+ const steps = snapshot.model.auth.modules[entry.module] !== void 0 || snapshot.decisions.modules.kept.some((kept) => kept.module === entry.module) ? void 0 : stepRecordOf(snapshot.model.auth);
26
+ const body = [`-- Written by \`protobase migration delete ${module}\`: it drops for good what ${archive.name} archived of ${module}.\n`, `-- It applies once ${archive.name} was applied ${hours} hours ago, and while retired.writes counts no write of what it drops within them.\n${markedSql(archive.id, [signOffGate(archive, hours, `Deleting ${module}`, false), ...deleteStatements(entry, hours, steps)])}\n`].join("\n");
27
+ const decisions = {
28
+ ...snapshot.decisions,
29
+ modules: {
30
+ ...snapshot.decisions.modules,
31
+ archived: archived.filter((found) => found !== entry)
32
+ }
33
+ };
34
+ const content = {
35
+ name: `delete_${module}`,
36
+ body,
37
+ additive: false
38
+ };
39
+ const draft = {
40
+ previous: snapshot,
41
+ auth: snapshot.model.auth,
42
+ modules: snapshot.model.modules,
43
+ organizations: { on: false },
44
+ protobaseVersion,
45
+ decisions
46
+ };
47
+ return writeMigrationFile(projectDir, dir, content, draft, newId());
48
+ };
49
+ //#endregion
50
+ export { writeDelete };
@@ -0,0 +1,19 @@
1
+ import { snapshotFile } from "../snapshot/snapshot-file.js";
2
+ //#region src/migration/sign-off/signed-off-file.ts
3
+ /** The migration with id `id` among `files`, by its id and its name as `migrations.history` records it. */
4
+ const signedOffFile = (files, id) => {
5
+ const found = files.find(({ header }) => header?.id === id);
6
+ if (!found) throw new Error(`The migration ${id} is not among the project's migrations: take back the file that has it, or ${snapshotFile} from before it`);
7
+ return {
8
+ id,
9
+ name: found.file.replace(/\.sql$/, "")
10
+ };
11
+ };
12
+ /** The hours a sign-off waits, from `--hours`: a whole number, at least 1. */
13
+ const signOffHours = (value) => {
14
+ const hours = Number(value);
15
+ if (!Number.isInteger(hours) || hours < 1) throw new Error(`--hours takes a whole number of hours, at least 1, not "${value}"`);
16
+ return hours;
17
+ };
18
+ //#endregion
19
+ export { signOffHours, signedOffFile };
@@ -1,6 +1,6 @@
1
1
  import { keptAfter, moduleChanges } from "./module-changes.js";
2
2
  import { modelHash as modelHash$1, snapshotFile } from "./snapshot-file.js";
3
- import { keepSql, latestSteps, nameChanges, offlineStepsMigration, resolveNames, revivalCheckSql, storeModel, unwatchSql } from "@protobase/server/internal";
3
+ import { forgetStepsSql, keepSql, latestSteps, nameChanges, offlineStepsMigration, resolveNames, restoredKeysSql, retiredNames, revivalCheckSql, stepRecordOf, storeModel, unwatchSql } from "@protobase/server/internal";
4
4
  //#region src/migration/snapshot/auth-difference.ts
5
5
  /** Each module's last step in a model. */
6
6
  const lastStepsOf = (model) => Object.fromEntries(Object.entries(model.modules).map(([module, entry]) => [module, entry.lastStep]));
@@ -84,36 +84,64 @@ const stepsAfter = (snapshot, target) => offlineStepsMigration(target.names, sna
84
84
  /** How to write what the steps cannot, once refused. */
85
85
  const customHint = "Write the change by hand with `protobase migration --custom <name> --record-config`.";
86
86
  /** The way through when a module turned off has no choice made for its tables. */
87
- const offHint = "Run `protobase migration` in a terminal to choose what becomes of its tables, or pass `--off keep`";
87
+ const offHint = "Run `protobase migration` in a terminal to choose what becomes of its tables, or pass `--off keep`, `--off archive` or `--off delete`";
88
+ const refuseArchivedAgain = (snapshot, off, choice) => {
89
+ if (choice === "keep") return;
90
+ const again = off.filter(({ module }) => snapshot?.decisions.modules.archived.some((archived) => archived.module === module));
91
+ if (again.length === 0) return;
92
+ throw new Error(`${again.map(({ module }) => module).join(", ")} has an archive from an earlier time it was off: delete it first with \`protobase migration delete <module>\`, or pass \`--off keep\``);
93
+ };
94
+ const freshAfterArchive = (snapshot, before, target) => (snapshot?.decisions.modules.archived ?? []).filter(({ module }) => target.names.names.modules.includes(module) && !before?.modules[module] && !snapshot.decisions.modules.kept.some((kept) => kept.module === module));
95
+ const turnedOn = (snapshot, before, target) => before ? target.names.names.modules.filter((module) => !before.modules[module] && !snapshot.decisions.modules.kept.some((kept) => kept.module === module)) : [];
96
+ const forgetArchived = (fresh, before) => {
97
+ const steps = before && stepRecordOf(before);
98
+ if (!steps) return [];
99
+ return fresh.map(({ module }) => `-- ${module} on again after its archive: it starts again from its first step, and the archive stays as it is until \`protobase migration delete ${module}\`.\n${forgetStepsSql(steps, module)}`);
100
+ };
88
101
  /**
89
102
  * The difference between the snapshot's auth store and the config's, from the snapshot alone: `migration`, what keeps
90
103
  * each module turned off (`off`, the choice made for them), the check that refuses to turn a kept one on again while
91
104
  * its tables hold rows, and the steps after each module's last one, undefined when there is none of these; the
92
- * store's model once it is applied; and the modules kept then.
105
+ * store's model once it is applied; and the modules kept then, those turned off with archive or delete awaiting the
106
+ * sign-off that archives them, with the migration `file` that turns them off.
93
107
  */
94
- const authDifference = (snapshot, target, off) => {
108
+ const authDifference = (snapshot, target, off, file = "") => {
95
109
  const refusals = authRefusals(snapshot, target);
96
110
  if (refusals.length > 0) throw new Error(`${refusals.join("; ")}. ${customHint}`);
97
111
  const unset = target ? organizationRefusals(snapshot, target) : [];
98
112
  if (unset.length > 0) throw new Error(unset.join("; "));
99
113
  const changes = moduleChanges(snapshot, target);
100
- const kept = keptAfter(snapshot?.decisions.modules.kept ?? [], changes);
101
114
  if (!target) return {
102
115
  model: void 0,
103
116
  migration: void 0,
104
117
  changes,
105
- kept
118
+ kept: keptAfter(snapshot?.decisions.modules.kept ?? [], changes)
106
119
  };
107
120
  if (changes.off.length > 0 && off === void 0) throw new Error(`${changes.off.map(({ module }) => module).join(", ")} is off in the config while ${snapshotFile} has its tables. ${offHint}.`);
108
- if (changes.off.length > 0 && off !== "keep") throw new Error(`--off ${off} is not available yet: a module turned off keeps its tables and rows (--off keep)`);
121
+ refuseArchivedAgain(snapshot, changes.off, off);
109
122
  const before = snapshot?.model.auth;
110
123
  const steps = stepsAfter(snapshot, target);
111
124
  const existing = Object.keys(before?.modules ?? {});
112
125
  const external = externalUser(snapshot, target) || target.names.users.keyTable !== void 0;
126
+ const deferred = off === "archive" || off === "delete" ? changes.off.map((module) => ({
127
+ ...module,
128
+ off: {
129
+ choice: off,
130
+ file,
131
+ columns: retiredNames(target.names, module.module, existing, external)
132
+ }
133
+ })) : changes.off;
134
+ const kept = keptAfter(snapshot?.decisions.modules.kept ?? [], {
135
+ ...changes,
136
+ off: deferred
137
+ });
138
+ const fresh = freshAfterArchive(snapshot, before, target);
113
139
  const parts = [
140
+ ...forgetArchived(fresh, before),
114
141
  ...changes.off.map(({ module }) => keepSql(target.names, module, existing, external)),
115
142
  ...changes.revived.flatMap(({ module, step }) => [revivalCheckSql(target.names, module, step), ...[unwatchSql(target.names, module, existing, external)].filter((text) => text !== void 0)]),
116
- ...steps ? [steps.sql] : []
143
+ ...steps ? [steps.sql] : [],
144
+ ...turnedOn(snapshot, before, target).flatMap((module) => [restoredKeysSql(target.names, module, existing)].filter((text) => text !== void 0))
117
145
  ];
118
146
  const model = storeModel(target.names, steps || !before ? latestSteps(target.names.names.modules) : snapshotStore(snapshot).lastSteps);
119
147
  if (parts.length === 0 && redescribed(before, model)) parts.push(redescribedSql);
@@ -4,7 +4,7 @@ import { protobaseFiles, readMigrationFiles } from "./migration-files.js";
4
4
  import { refuseInconsistent } from "./consistency.js";
5
5
  import path from "node:path";
6
6
  import { rm } from "node:fs/promises";
7
- import { storeNamesList } from "@protobase/server/internal";
7
+ import { contractMark, storeNamesList } from "@protobase/server/internal";
8
8
  //#region src/migration/snapshot/drop.ts
9
9
  const atSteps = (model, steps) => {
10
10
  if (!model || Object.keys(steps).length === 0) return;
@@ -31,6 +31,7 @@ const dropMigration = async (projectDir, dir) => {
31
31
  const written = protobaseFiles(files);
32
32
  const newest = written.at(-1);
33
33
  const previous = written.at(-2);
34
+ if (newest.text.includes(contractMark(""))) throw new Error(`${newest.file} signs off or deletes what an earlier migration retired, which changes ${snapshotFile}'s decisions: delete it by hand and take ${snapshotFile} from before it from version control`);
34
35
  const remove = async () => {
35
36
  await rm(path.join(dir, newest.file));
36
37
  await rm(path.join(dir, afterFileOf(newest.file)), { force: true });
@@ -3,12 +3,26 @@ const rowsNote = (module) => module === "personal_access_tokens" ? "\n Its toke
3
3
  const plural = (count, one, many) => `${count} ${count === 1 ? one : many}`;
4
4
  const darkNote = (module, facts) => module === "organizations" && facts ? `\n While organizations are off, the default organization stands in for all of them, and only its members can sign in. That locks out ${plural(facts.outside, "person", "people")} and stops ${plural(facts.otherTokens, "personal access token", "personal access tokens")} created outside it from working.` : "";
5
5
  /** The question that chooses what becomes of the tables of the modules turned off, saying what goes dark with organizations (`facts`). */
6
- const offQuestion = (modules, facts) => `${modules.map(({ module }) => module).join(", ")} is off in the config. What becomes of its tables and rows?\n keep: they stay as they are, and turning it on again goes on from them. Archive and delete are coming soon.${modules.map(({ module }) => rowsNote(module) + darkNote(module, facts)).join("")}\n [k]eep (k): `;
7
- /** Asks what becomes of the tables of the modules turned off: keep, the default and for now the only choice. */
6
+ const offQuestion = (modules, facts) => `${modules.map(({ module }) => module).join(", ")} is off in the config. What becomes of its tables and rows?
7
+ keep: they stay as they are, and turning it on again goes on from them.
8
+ archive: they stay as they are until \`protobase migration contract\` signs the update off, which moves them to an archive the app cannot use.
9
+ delete: as archive, and once it is archived, \`protobase migration delete\` removes it for good.${modules.map(({ module }) => rowsNote(module) + darkNote(module, facts)).join("")}
10
+ [k]eep, [a]rchive or [d]elete (k): `;
11
+ const answers = {
12
+ keep: [
13
+ "",
14
+ "k",
15
+ "keep"
16
+ ],
17
+ archive: ["a", "archive"],
18
+ delete: ["d", "delete"]
19
+ };
20
+ /** Asks what becomes of the tables of the modules turned off: keep, the default, archive or delete. */
8
21
  const chooseOff = (ask) => async (modules, facts) => {
9
22
  const answer = (await ask(offQuestion(modules, facts))).trim().toLowerCase();
10
- if (answer === "" || answer === "k" || answer === "keep") return "keep";
11
- throw new Error(`"${answer}" is not a choice: keep is the only one for now`);
23
+ const choice = Object.keys(answers).find((known) => answers[known].includes(answer));
24
+ if (!choice) throw new Error(`"${answer}" is not a choice: answer keep, archive or delete`);
25
+ return choice;
12
26
  };
13
27
  /** The refusal of a module turned on again while its kept tables hold rows, with the way through. */
14
28
  const revivalRefused = ({ module, found }) => `${module} is on again while its kept tables hold rows: ${found}. Delete them in a migration of the project's own first, or bring them back: pass --force to write the migration, and apply it with \`protobase migrate --force\``;
@@ -12,7 +12,7 @@ import { revivedRows } from "./revival-rows.js";
12
12
  import { breaksOlderCodeNote, olderCodeRefusal } from "../older-code/refusal.js";
13
13
  import { moduleSections } from "./module-sections.js";
14
14
  import { runPreconditions } from "./preconditions.js";
15
- import { schemaModules } from "@protobase/server/internal";
15
+ import { droppedTableIds, schemaModules } from "@protobase/server/internal";
16
16
  //#region src/migration/snapshot/run-migration.ts
17
17
  const checkRevivals = async (url, run, revived) => {
18
18
  if (revived.length === 0 || run.force) return;
@@ -48,7 +48,8 @@ const runMigration = async (run) => {
48
48
  if (!snapshot && auth && files.some(({ text }) => text.includes("The auth schema changes this version of Protobase needs"))) throw new Error(`The project has auth migrations from before ${snapshotFile}: start it with \`protobase migration baseline\`, run against the database with the project's migrations applied, then run \`protobase migration\` again`);
49
49
  const { off: turnedOff } = moduleChanges(snapshot, auth);
50
50
  const off = run.off ?? (turnedOff.length > 0 && run.chooseOff ? await run.chooseOff(turnedOff, await offFacts(run, turnedOff)) : void 0);
51
- const difference = authDifference(snapshot, auth, off);
51
+ const id = newId();
52
+ const difference = authDifference(snapshot, auth, off, id);
52
53
  if (database) await checkRevivals(database.url, run, difference.changes.revived);
53
54
  if (database && difference.migration && difference.migration.checks.length > 0) await runPreconditions(database.url, difference.migration.checks);
54
55
  const written = moduleSections(snapshot, modules);
@@ -74,7 +75,7 @@ const runMigration = async (run) => {
74
75
  ];
75
76
  if (sections.length === 0) return;
76
77
  const own = /* @__PURE__ */ new Set(["auth", ...written.sections.map(({ name }) => name)]);
77
- const found = database ? await database.contractions(sections) : [];
78
+ const found = database ? await database.contractions(sections, auth ? droppedTableIds(auth.names) : []) : [];
78
79
  const refused = found.filter(({ name }) => !own.has(name));
79
80
  if (refused.length > 0) throw new Error(olderCodeRefusal(refused));
80
81
  const label = (name) => name === "auth" ? "The sign-in modules' steps" : schemaModules[name].title;
@@ -111,7 +112,7 @@ const runMigration = async (run) => {
111
112
  protobaseVersion,
112
113
  ...decisions && { decisions }
113
114
  };
114
- return writeMigrationFile(projectDir, dir, content, draft, newId());
115
+ return writeMigrationFile(projectDir, dir, content, draft, id);
115
116
  };
116
117
  //#endregion
117
118
  export { intro, runMigration };
@@ -1,5 +1,5 @@
1
1
  import { tableKey } from "../db/model.js";
2
- import { storeRecordNames, storeTableNames } from "@protobase/server/auth-store";
2
+ import { storeRecordName, storeTableNames } from "@protobase/server/auth-store";
3
3
  import { definitionsSchema, userTablesSchema } from "@protobase/server/config-exports";
4
4
  //#region src/scaffold/protobase-tables.ts
5
5
  const storeCore = [
@@ -17,7 +17,7 @@ const authStore = (schema, tables) => {
17
17
  if (schema === "auth") return tables;
18
18
  const has = (name) => tables.some((table) => table.name === name);
19
19
  const user = userTableOf(schema, tables);
20
- if (!storeRecordNames.some(has) && !(storeCore.every(has) && user !== void 0)) return [];
20
+ if (!has(storeRecordName) && !(storeCore.every(has) && user !== void 0)) return [];
21
21
  if (schema !== "public") return tables;
22
22
  return tables.filter((table) => storeTableNames.includes(table.name) || table.name === user);
23
23
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.130.0",
3
+ "version": "0.131.0",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -43,13 +43,13 @@
43
43
  "dependencies": {
44
44
  "@better-auth/core": "^1.7.12",
45
45
  "@hono/node-server": "^2.1.3",
46
- "@protobase/config": "0.130.0",
47
- "@protobase/layout": "0.130.0",
48
- "@protobase/query": "0.130.0",
49
- "@protobase/schema": "0.130.0",
50
- "@protobase/server": "0.130.0",
51
- "@protobase/ui": "0.130.0",
52
- "@protobase/workflows": "0.130.0",
46
+ "@protobase/config": "0.131.0",
47
+ "@protobase/layout": "0.131.0",
48
+ "@protobase/query": "0.131.0",
49
+ "@protobase/schema": "0.131.0",
50
+ "@protobase/server": "0.131.0",
51
+ "@protobase/ui": "0.131.0",
52
+ "@protobase/workflows": "0.131.0",
53
53
  "@react-email/render": "^2.1.0",
54
54
  "@scalar/hono-api-reference": "^0.12.10",
55
55
  "@sentry/vite-plugin": "^11.10.0",
@@ -24,6 +24,7 @@ Develop, build and run an app, on servers, in containers and on phones.
24
24
  - [Migrations at update time](../guides/deploy.md#migrations): The bundle carries the project's migrations, and the runtime applies them before the new version serves, in batches of one transaction each, refusing a second run while one runs, with an `.after.sql` beside a file for statements such as `create index concurrently`, which a stopped run's next run finishes.
25
25
  - [Migration record](../guides/deploy.md#the-record-of-migrations): Every migration file Protobase writes ends by adding its own row to `migrations.history`, so any tool that applies the file also records it. At startup the server reads the record: it starts when the database matches its version or is ahead only by additive migrations, and when the database is behind, it refuses and says what is missing and how to fix it.
26
26
  - [Changes that break older code](../reference/cli.md#changes-that-break-older-code) (beta): `protobase migration` applies each new file to the database in a transaction it rolls back and names what the code still running would lose; Protobase's own parts keep what older code reads, a change only a hand-written file can make is refused with the way through, and a file that breaks older code makes the version before it refuse to start, saying rolling back is blocked. `protobase migration check` lints hand-written files with Postgres's own parser and warns of statements that lock reads.
27
+ - [Signing off an update](../reference/cli.md#signing-off-an-update) (beta): Sign off an update with `protobase migration contract` to archive what it retired, and remove it later with `protobase migration delete` once nothing writes it.
27
28
  - [Release steps](../reference/cli.md#release-steps): `protobase-serve migrate-release` brings a database up to a release's own built-in schema steps straight from a built bundle, with a dry-run plan, without writing files into the project.
28
29
  - [Single-file runtime](../reference/cli.md#build-serve): The runtime as one file, so a host needs only Bun and that file.
29
30
  - [Separate worker](../reference/cli.md#worker): Jobs and event delivery in their own process.
@@ -8,7 +8,7 @@ Sign-in methods, users, roles, organizations and tokens.
8
8
  - [Sign-in page](../reference/client.md#the-admin-app): The app signs people in at its own address, where the browser's Back returns to the step before, and signing in comes back to the page they were on.
9
9
  - [First admin](../reference/auth.md#first-run): No account can be made over the web while the app has no users. You create the first admin from the terminal, and the last active admin cannot be deleted, demoted or blocked.
10
10
  - [Users from a script](../reference/auth.md#first-run): A seed or another script of the project creates and lists users, and mints their tokens, on the app's own sign-in.
11
- - [Versioned sign-in tables](../reference/auth.md#migrations): The sign-in tables come from numbered steps that ship with Protobase, a chain for each module of sign-in, written as the project's own migrations and recorded in the database, so a deploy checks them without comparing tables. Every step only adds, and one that assumes something of the rows already there checks it first and names the rows to fix. A feature's tables exist only once the config turns it on, and turning it on is the next migration. Turning it off keeps its tables and rows, and the columns it adds to other tables, counting by hour the writes older code still makes to them, and turning it on again goes on from them, refusing while they hold rows unless `protobase migrate --force` brings them back. Archiving or deleting them is coming soon.
11
+ - [Versioned sign-in tables](../reference/auth.md#migrations): The sign-in tables come from numbered steps that ship with Protobase, a chain for each module of sign-in, written as the project's own migrations and recorded in the database, so a deploy checks them without comparing tables. Every step only adds, but the one that drops `auth_migrations`, the former record of versions no code reads since 0.130, and one that assumes something of the rows already there checks it first and names the rows to fix. A feature's tables exist only once the config turns it on, and turning it on is the next migration. Turning it off keeps its tables and rows, and the columns it adds to other tables, counting by hour the writes older code still makes to them, and turning it on again goes on from them, refusing while they hold rows unless `protobase migrate --force` brings them back. Archiving or deleting them is coming soon.
12
12
  - [Table and column names](../reference/auth.md#table-and-column-names): Every sign-in table can take another name or a prefix, and every column but `id` another name, from the config, and the migrations, sign-in and Protobase's own queries all use it.
13
13
  - [Existing users table](../reference/auth.md#an-existing-users-table): Sign-in can use the users table another system keeps in the same database.
14
14
  - [Users page](../reference/auth.md#users-page): Admins find people, set roles, block them, add accounts and invite people by email.
@@ -26,7 +26,7 @@ Users, sessions and signing keys stay apart from the application's tables, in a
26
26
 
27
27
  ### Migrations
28
28
 
29
- The store's tables come from steps that ship with Protobase, and are part of the project's migrations, committed in the repository like the application's own: the examples carry them as `db/migrations/*_auth.sql`, and their `db:migrate` applies both. Each module of sign-in has its own numbered chain of steps, the only source of its tables: `auth` (users, sessions, accounts, codes and signing keys), `two_factor`, `passkeys`, `sign_in_policy`, `staff_sign_in`, `organizations`, `mcp`, `personal_access_tokens`, `mail_senders` and `platform_devices`. A step is written against the store's [names](#table-and-column-names), so it makes the tables and columns under the names the app configures, and a step that adds columns to another module's table, such as `organizations` adding the organization of each user, session and personal access token, adds them only while that module is on. The store records each step it applied in its `auth_steps` table, one row per module, step and the module whose tables it changes, so the columns one module adds to another's tables are recorded apart from the step's own tables. A store an earlier Protobase made recorded versions instead, in `auth_migrations`, the numbers of the single chain the store had before its modules had chains of their own: the next file makes `auth_steps` from them, each version as the steps that shared it, such as version 13 as `auth` 4, `passkeys` 2, `staff_sign_in` 2 and `organizations` 2, and `auth_migrations` is read no more. When an upgrade of Protobase brings new steps, write them as the project's next migration:
29
+ The store's tables come from steps that ship with Protobase, and are part of the project's migrations, committed in the repository like the application's own: the examples carry them as `db/migrations/*_auth.sql`, and their `db:migrate` applies both. Each module of sign-in has its own numbered chain of steps, the only source of its tables: `auth` (users, sessions, accounts, codes and signing keys), `two_factor`, `passkeys`, `sign_in_policy`, `staff_sign_in`, `organizations`, `mcp`, `personal_access_tokens`, `mail_senders` and `platform_devices`. A step is written against the store's [names](#table-and-column-names), so it makes the tables and columns under the names the app configures, and a step that adds columns to another module's table, such as `organizations` adding the organization of each user, session and personal access token, adds them only while that module is on. The store records each step it applied in its `auth_steps` table, one row per module, step and the module whose tables it changes, so the columns one module adds to another's tables are recorded apart from the step's own tables. A store an earlier Protobase made recorded versions instead, in `auth_migrations`, the numbers of the single chain the store had before its modules had chains of their own: the migrations of Protobase 0.130 made `auth_steps` from them, and `auth` step 6 drops `auth_migrations`. A store that still has `auth_migrations` without `auth_steps` is refused: bring the project to Protobase 0.130 first, write and apply its migration there, then upgrade. When an upgrade of Protobase brings new steps, write them as the project's next migration:
30
30
 
31
31
  ```sh
32
32
  bun run db:migrate # the database at the project's current schema
@@ -40,7 +40,7 @@ A store has the tables of the modules the config turns on, and no table, column
40
40
 
41
41
  #### Turning a module off
42
42
 
43
- Taking a feature out of the config turns its module off, and the next [`protobase migration`](cli.md#migration) asks what becomes of its tables and rows; without a terminal, `--off keep` answers. The answer is recorded in `protobase.snapshot.json`, under `decisions.modules.kept`, with the step the module had and its tables' names. `keep`, the default, applies at once: the tables and rows stay as they are, the module stays at its step, and each column it adds to the tables of the modules still on loses `not null`, so the code that no longer writes it still inserts rows, and is watched for the code that still does, such as the version before once rolled back: a trigger on each counts the rows written with it set, by hour, in `retired.writes` (`table_name`, `column_name`, `hour`, `writes`), the schema `retired` made by the first file that retires a column. Turning the module on again stops the watch, and the column is in use again under its name with the values it kept. A personal access token's `organization_id` stays required, as tokens made while organizations are off are made in [the default organization](#the-default-organization). For personal access tokens the question says they stay valid unless deleted. <gap>A module turned off cannot have its tables archived or deleted because waiting for an update to count as successful, by its manual sign-off, is not implemented.</gap> `--off archive` and `--off delete` are refused, naming keep. `protobase auth migration` refuses a config that turns a module off or on again since the snapshot, and says to run `protobase migration`.
43
+ Taking a feature out of the config turns its module off, and the next [`protobase migration`](cli.md#migration) asks what becomes of its tables and rows, keep, archive or delete; without a terminal, `--off` answers. The answer is recorded in `protobase.snapshot.json`, under `decisions.modules.kept`, with the step the module had and its tables' names. `keep`, the default, applies at once: the tables and rows stay as they are, the module stays at its step, and each column it adds to the tables of the modules still on loses `not null`, so the code that no longer writes it still inserts rows, and is watched for the code that still does, such as the version before once rolled back: a trigger on each counts the rows written with it set, by hour, in `retired.writes` (`table_name`, `column_name`, `hour`, `writes`), the schema `retired` made by the first file that retires a column. Turning the module on again stops the watch, and the column is in use again under its name with the values it kept. A personal access token's `organization_id` stays required, as tokens made while organizations are off are made in [the default organization](#the-default-organization). For personal access tokens the question says they stay valid unless deleted. `archive` and `delete` keep it the same way, and record the choice, the file that turned it off and the columns it retired, until [`protobase migration contract`](cli.md#signing-off-an-update) signs the update off: that file moves the module's tables to the schema `protobase_archive_<n>`, which the app's roles cannot use, with no foreign key between them and the tables still on, and renames each column it retired to `<column>_archive`; the module moves to `decisions.modules.archived`. [`protobase migration delete <module>`](cli.md#signing-off-an-update) then removes the archive for good, once it was applied a stated period ago and nothing wrote it within it. A module turned on again after its archive starts afresh from its first step, and the archive stays until deleted. `protobase auth migration` refuses a config that turns a module off or on again since the snapshot, and says to run `protobase migration`.
44
44
 
45
45
  Turning a kept module on again writes the rest of its steps after the one it was kept at, and refuses a table or column name the config changed meanwhile, as for a module that stays on; and again what the modules on add to its tables, which their guard skips where the database has it. Its rows come back into use, such as personal access tokens, which act for their users again, so the file starts with a check that refuses while its tables hold rows, naming each table with its count, unless it is applied with [`protobase migrate --force`](cli.md#migrate). With `DATABASE_URL` set, `protobase migration` counts them first and refuses the same way, asking on a terminal whether to bring them back, or taking `--force`; with empty tables it neither asks nor refuses.
46
46
 
@@ -56,7 +56,7 @@ A store made before 0.48, when `protobase auth migration` compared the database
56
56
 
57
57
  Each module of the store declares its tables and columns once, under built-in names, snake_case like the app's (`sign_in_policy.platform_sign_in`, `session.user_id`); the code and the API keep Better Auth's camelCase names. The modules and their tables:
58
58
 
59
- - `auth`: `user`, `session`, `account`, `verification`, `jwks`, `auth_steps` and `auth_migrations`.
59
+ - `auth`: `user`, `session`, `account`, `verification`, `jwks` and `auth_steps`.
60
60
  - `two_factor`: `two_factor`, and the user's `two_factor_enabled`.
61
61
  - `passkeys`: `passkey`.
62
62
  - `sign_in_policy`: `sign_in_policy`.
@@ -51,7 +51,7 @@ protobase scaffold [connection string | --env VAR] [target] [options]
51
51
 
52
52
  Without a connection string or `--env`, the URL is `DATABASE_URL`, from the environment or the nearest `.env` at or above the current directory, as `dev` reads it. `target` is `all` (default), `schema`, `schema.table` or `schema.table.column`. Tables are introspected from `pg_catalog`; `config/<resource>/data.ts` is created or extended. A table that a written one points to with a foreign key is written too, outside the target or excluded, unless it has a resource already, since the app refuses a relation to a resource it does not have; a line names each.
53
53
 
54
- Protobase's own tables are left out, since they hold password hashes, OAuth tokens and signing keys: the auth store, which is the `auth` schema or another schema with the store's `auth_steps` or `auth_migrations` table, or with Better Auth's `session`, `account` and `verification` tables whose sessions point at a user table (in `public`, only the tables of the store's [migrations](auth.md#migrations) and that user table, whatever it is called), pg-boss's `jobs` schema, and the `migrations` schema whose `applied` table records the migrations applied. A line names each one skipped. The auth store is left out whatever the target names; a target naming the `jobs` or `migrations` schema scaffolds it anyway. A resource an earlier run made over one of them gets a warning to remove it, and `dev` and `serve` refuse to start with a resource over the auth store.
54
+ Protobase's own tables are left out, since they hold password hashes, OAuth tokens and signing keys: the auth store, which is the `auth` schema or another schema with the store's `auth_steps` table, or with Better Auth's `session`, `account` and `verification` tables whose sessions point at a user table (in `public`, only the tables of the store's [migrations](auth.md#migrations) and that user table, whatever it is called), pg-boss's `jobs` schema, and the `migrations` schema whose `applied` table records the migrations applied. A line names each one skipped. The auth store is left out whatever the target names; a target naming the `jobs` or `migrations` schema scaffolds it anyway. A resource an earlier run made over one of them gets a warning to remove it, and `dev` and `serve` refuse to start with a resource over the auth store.
55
55
 
56
56
  | Option | Effect |
57
57
  | --- | --- |
@@ -667,32 +667,40 @@ A project with auth migrations written before the snapshot starts it with `migra
667
667
  :::
668
668
 
669
669
  ```sh
670
- protobase migration [--dir db/migrations] [--extend <dir>] [--off keep] [--force]
670
+ protobase migration [--dir db/migrations] [--extend <dir>] [--off keep|archive|delete] [--force]
671
671
  protobase migration --custom <name> [--record-config] [--after]
672
672
  protobase migration check
673
673
  protobase migration baseline [--dir db/migrations] [--extend <dir>]
674
+ protobase migration contract [--hours 24]
675
+ protobase migration delete <module> [--hours 168]
674
676
  protobase migration drop
675
677
  protobase migration up
676
678
  ```
677
679
 
678
680
  Writes what the config and this version of Protobase need beyond the project's `protobase.snapshot.json` as the project's next migration in `--dir`: one numbered file each run, named after what it holds, such as `004_auth.sql` or `005_changes_webhooks.sql`, after the folder's highest number, and rewrites the snapshot to end at it, so both show in the pull request. The file starts with lines Protobase reads back: `-- protobase:id`, a random id of its own, then the version that wrote it, each sign-in module's last step, the schema modules' part of the model as JSON (`-- protobase:modules`), and the hash of the snapshot's model once it is applied. The file ends with the statement that records it in `migrations.history` with the snapshot's model, which the server reads at startup (see [The record of migrations](../guides/deploy.md#the-record-of-migrations)), with whether it is additive (see [Changes that break older code](#changes-that-break-older-code)). It writes nothing, the snapshot included, when nothing differs. Apply the file with the project's other migrations.
679
681
 
680
- A sign-in module the config turns off is [kept](auth.md#turning-a-module-off): on a terminal it asks what becomes of its tables, keep being the default and for now the only choice, and without one it needs `--off keep`. A kept module turned on again goes on from its step; with `DATABASE_URL` set and rows in its tables, it asks on a terminal whether to bring them back, and needs `--force` without one, and the file it writes then applies with `protobase migrate --force`.
682
+ A sign-in module the config turns off is [kept](auth.md#turning-a-module-off): on a terminal it asks what becomes of its tables, keep, archive or delete, keep being the default, and without one it needs `--off`. Archive and delete keep it as keep does until [`contract`](#signing-off-an-update) signs the update off. A kept module turned on again goes on from its step; with `DATABASE_URL` set and rows in its tables, it asks on a terminal whether to bring them back, and needs `--force` without one, and the file it writes then applies with `protobase migrate --force`.
681
683
 
682
- The snapshot describes the schema the project's migrations make: the sign-in store as the runtime reads it, each module that is on with its tables, columns and indexes under the names the config gives them, its last step, and whether every table whose rows belong to an organization has the column that names it, with `modelHash`, the SHA-256 of exactly that; what the migrations decided, the file it ends at with its id, its `format` and the version of Protobase that wrote it, the modules kept or archived, whether organizations were ever on and the default organization, and in `external` the store's relations Protobase did not make, such as the user view of [`users.keyTable`](auth.md#a-view-over-another-systems-users), which no step alters; and `physical`, every schema, table, column and index name the store has. Its `model.modules` holds each built-in schema, each a module with numbered steps, such as the [jobs schema](jobs.md#the-jobs-schema) (`jobs`), the [change capture](events.md#migrations-and-startup) (`changes`) and its [history](history.md#the-table) and [notices](live.md#the-table) tables (`history`, `notices`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks` (`webhooks`) and their delivery log with `deliveryLog` (`webhook_delivery_log`), the [workflows, versions and runs](workflows.md#turning-them-on) of `workflows` (`workflows`) with their storage configurations and custom steps while those are on (`workflow_storage`, `workflow_custom_steps`), the [devices and history tables](notifications.md#table-names) of `notifications` (`notification_devices`, `notification_history`), each unless a store of the app's own replaces it, the [comments table](comments.md#the-table) (`comments`), the table of the bounces and complaints of [`mailFeedback`](email.md#bounces-and-complaints) (`mail_feedback`), written before the change capture whose triggers capture its events, and the table of who unsubscribed from bulk mail of [`unsubscribe`](email.md#unsubscribe) (`unsubscribes`), and the [query role](assistant.md#the-built-in-backend) of the assistant's read-only queries (`query`), each at its last step and the version of the functions over it, with the names it takes from the config, such as the schema `events`, `webhooks.schema` or `workflows.schema` names, the notifications tables' names and columns and the users table they point at, and the triggers of each captured resource at a digest of their statements; it keeps one the config no longer needs as the migrations left it. That part of the file comes from the snapshot alone too, after the store's: the module's steps after its last one, then its functions where the snapshot has another version, then the triggers of each resource whose statements differ, such as one added or one whose field became sensitive; a file that replaces them with a version the code before does not run on says `-- protobase:breaks-older-code`. A name the config changes, such as `events.schema`, `webhooks.schema` or a notifications table's column, is refused, since Protobase does not write renames; so is turning sign-in on under notifications tables made without it, whose user column then points at no users table. With `DATABASE_URL` set, it refuses to write a module from its first step onto a database that has it already, as made by an earlier version's migration, and names `baseline`. The sign-in store's part of the file comes from the snapshot alone, without a database: the [steps](auth.md#migrations) after each module's last one, those a newer Protobase ships included, each followed by its row in `auth_steps`, and for a snapshot whose store has no `auth_steps` yet, that table first, made from `auth_migrations`. Each runs only while `auth_steps` lacks it, so a database that has it already, such as one [`migrate-release`](#release-steps) brought to a newer release, skips it. With `DATABASE_URL` set, the checks of those steps run first against the database's rows, in a read-only transaction, and refuse as the step would, such as on two accounts with one provider and account id. A name the store has that the config changes, such as a table renamed in [`auth.tables`](auth.md#table-and-column-names), is refused with what changed, since Protobase does not write renames: write it by hand with `--custom` and `--record-config`. A store a newer Protobase describes otherwise with no step to apply, such as personal access tokens now holding an organization's rows, gets a file that records it anew and changes nothing in the database. A step whose work cannot run in a transaction leaves it to the file's `.after.sql`, such as the batches that give each personal access token the [default organization](auth.md#the-default-organization) when organizations turn on, and the index it builds concurrently. With organizations on or ever on, the file needs `organizations.default` in the config, and turning them on the first time over a store that may hold users needs `organizations.existingUsersRole`; it refuses without them, as `migration check` reports.
684
+ The snapshot describes the schema the project's migrations make: the sign-in store as the runtime reads it, each module that is on with its tables, columns and indexes under the names the config gives them, its last step, and whether every table whose rows belong to an organization has the column that names it, with `modelHash`, the SHA-256 of exactly that; what the migrations decided, the file it ends at with its id, its `format` and the version of Protobase that wrote it, the modules kept or archived, whether organizations were ever on and the default organization, and in `external` the store's relations Protobase did not make, such as the user view of [`users.keyTable`](auth.md#a-view-over-another-systems-users), which no step alters; and `physical`, every schema, table, column and index name the store has. Its `model.modules` holds each built-in schema, each a module with numbered steps, such as the [jobs schema](jobs.md#the-jobs-schema) (`jobs`), the [change capture](events.md#migrations-and-startup) (`changes`) and its [history](history.md#the-table) and [notices](live.md#the-table) tables (`history`, `notices`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks` (`webhooks`) and their delivery log with `deliveryLog` (`webhook_delivery_log`), the [workflows, versions and runs](workflows.md#turning-them-on) of `workflows` (`workflows`) with their storage configurations and custom steps while those are on (`workflow_storage`, `workflow_custom_steps`), the [devices and history tables](notifications.md#table-names) of `notifications` (`notification_devices`, `notification_history`), each unless a store of the app's own replaces it, the [comments table](comments.md#the-table) (`comments`), the table of the bounces and complaints of [`mailFeedback`](email.md#bounces-and-complaints) (`mail_feedback`), written before the change capture whose triggers capture its events, and the table of who unsubscribed from bulk mail of [`unsubscribe`](email.md#unsubscribe) (`unsubscribes`), and the [query role](assistant.md#the-built-in-backend) of the assistant's read-only queries (`query`), each at its last step and the version of the functions over it, with the names it takes from the config, such as the schema `events`, `webhooks.schema` or `workflows.schema` names, the notifications tables' names and columns and the users table they point at, and the triggers of each captured resource at a digest of their statements; it keeps one the config no longer needs as the migrations left it. That part of the file comes from the snapshot alone too, after the store's: the module's steps after its last one, then its functions where the snapshot has another version, then the triggers of each resource whose statements differ, such as one added or one whose field became sensitive; a file that replaces them with a version the code before does not run on says `-- protobase:breaks-older-code`. A name the config changes, such as `events.schema`, `webhooks.schema` or a notifications table's column, is refused, since Protobase does not write renames; so is turning sign-in on under notifications tables made without it, whose user column then points at no users table. With `DATABASE_URL` set, it refuses to write a module from its first step onto a database that has it already, as made by an earlier version's migration, and names `baseline`. The sign-in store's part of the file comes from the snapshot alone, without a database: the [steps](auth.md#migrations) after each module's last one, those a newer Protobase ships included, each followed by its row in `auth_steps`; a snapshot whose store has no `auth_steps` yet, as a Protobase before 0.130 wrote it, is refused, naming 0.130 as the release to migrate through first. Each runs only while `auth_steps` lacks it, so a database that has it already, such as one [`migrate-release`](#release-steps) brought to a newer release, skips it. With `DATABASE_URL` set, the checks of those steps run first against the database's rows, in a read-only transaction, and refuse as the step would, such as on two accounts with one provider and account id. A name the store has that the config changes, such as a table renamed in [`auth.tables`](auth.md#table-and-column-names), is refused with what changed, since Protobase does not write renames: write it by hand with `--custom` and `--record-config`. A store a newer Protobase describes otherwise with no step to apply, such as personal access tokens now holding an organization's rows, gets a file that records it anew and changes nothing in the database. A step whose work cannot run in a transaction leaves it to the file's `.after.sql`, such as the batches that give each personal access token the [default organization](auth.md#the-default-organization) when organizations turn on, and the index it builds concurrently. With organizations on or ever on, the file needs `organizations.default` in the config, and turning them on the first time over a store that may hold users needs `organizations.existingUsersRole`; it refuses without them, as `migration check` reports.
683
685
 
684
686
  The rest of the file is what the config still needs of the database, compared with it, under its own comment and named in the file name as in brackets: with [`userTables`](user-tables.md#the-switch), the delete of the definitions of tables that resources in code [own now](user-tables.md#taking-a-table-over-as-code) (`owned_definitions`). It is compared only with `DATABASE_URL` set, against the database with the project's migrations applied, and the command says so without it. The jobs schema is written when the config has jobs, `webhooks`, `workflows`, `notifications` or `mailFeedback`, or uses the relay, or a resource has events, history, comments or an [AI field](ai.md) or is a [time rollup](data-config.md#keeping-it-up-to-date). The rollups and formulas module is written when a resource has [rollup or formula fields](data-config.md#rollups-and-formulas) or is a [time rollup](data-config.md#time-rollups) (`computed`): the `rollups` schema, then per field and rollup the columns, the functions and triggers that keep the rollups, and the tables, indexes and refresh functions of time rollups; a changed one is dropped and made again, and what sets a rollup's values or fills a time rollup goes in the file's `.after.sql`, which runs once its transaction commits. The `derived` schema is written when a resource has [derived values](derived.md), with each value declared and its fill enqueued, and a value no longer declared loses its state. The schemas of user tables (`user_tables`) are written with [`userTables`](user-tables.md#the-switch); the tables users add inside them are data, made while the app serves. The change capture is written when a resource has events, history, live updates or derived values, another's derived values or live updates read it, or `mailFeedback` is on; its history table with history, and its notices table with live updates. The webhooks, workflows, notifications, [status](status.md), [calls](calls.md), comments, mail feedback and unsubscribe modules, the `realtime_relay` schema of [`realtime: { processes: 'many' }`](supabase-realtime.md#several-processes) and the `channels` schema of [`realtime: { sqlSends: true }`](channels.md#from-sql) are written while the config turns their feature on, and none of them while it is off; turning a feature off later leaves its tables as they are. Calls write the notices table too, which rings reach open pages through. The [relay](realtime-relay.md#sessions) module, the trigger that ends a deleted session's sockets and `realtime.members` with the triggers that keep it from channel records that list their members, is written with `realtime.relay`, and for an app with sign-in and a live resource whose conversation page has `members`, after the auth store's steps, since its trigger is on the sessions table. The query module, the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as with the function they run through, is written last when the command finds the built-in assistant's key (`query`), with the role's grants on each resource's table but those of the auth store: a resource added writes only its grants, and one removed takes them back. It reads the config merged with those of `--extend` as `dev` merges them, and the `.env` nearest the current directory.
685
687
 
686
688
  #### Changes that break older code
687
689
 
688
- Every file is additive, so the code still running while it deploys, and the version before it once rolled back, still runs on the database, or it breaks older code, and that code refuses to start rather than fail on a request, when the file changes the model the record holds (see [The record of migrations](../guides/deploy.md#the-record-of-migrations)). With `DATABASE_URL` set, `protobase migration` applies the file to the database in a transaction it rolls back, reads the schema before and after, and names what older code loses: a table, column, sequence, function or enum value dropped, renamed or moved, a trigger dropped, disabled or firing on fewer events, a table or column made again with its rows or values lost, a column whose type changes or that becomes `not null`, a required column without a default or one losing its default, and a new constraint or unique index on a table there already, which rows older code writes may break. A view, function, trigger or generated column made again is not lost, and taking back a privilege, which only narrows access, is always allowed. What the sign-in modules' steps take, such as the organization every personal access token needs once organizations turn on, is Protobase's own path: the file then says `-- protobase:breaks-older-code` in its header, with what the steps take under it, and is recorded as not additive. What another part would take is refused before anything is written, naming it, with the way through: write the change by hand with `--custom` and mark the file `-- protobase:breaks-older-code`. Protobase's own parts keep what older code still reads, such as the triggers of a resource that no longer has events, history or live updates while another resource is still captured, so the dispatch job drains what they capture; they follow the resource's fields, so a field made sensitive is no longer copied. Once no resource is captured, the change capture drops them, in a file that says `-- protobase:breaks-older-code`; so does the function and trigger of a rollup field the config no longer has, which the next file drops. A rename or a move is always one file that breaks older code, with no view or trigger in between. A column Protobase adds is retired rather than dropped once the config no longer needs it: the column of a rollup or formula field the config no longer has stays as it is, and putting the field back finds it, with its values; the columns a [sign-in module turned off](auth.md#turning-a-module-off) adds to the tables still on stay under their names, watched for the writes older code still makes, and are in use again, with their values, once it is on again. A resource field's column is the project's own, as is its table: removing the field writes nothing, and dropping the column is a hand-written file marked `-- protobase:breaks-older-code`. <gap>`protobase migration` cannot write a statement that takes from older code under `-- protobase:contract <id>`, naming the migration that stopped older code from using it, because the sign-off and delete paths are not implemented.</gap> <gap>A sign-in step that takes from older code cannot carry `-- protobase:contract` because steps naming the migration that stopped older code from using what they take is not implemented.</gap> A [time rollup](data-config.md#time-rollups) that changes has its table made again and filled from its source, which loses no rows, as its comment marks it as Protobase's: only the columns older code reads that it no longer has are named.
690
+ Every file is additive, so the code still running while it deploys, and the version before it once rolled back, still runs on the database, or it breaks older code, and that code refuses to start rather than fail on a request, when the file changes the model the record holds (see [The record of migrations](../guides/deploy.md#the-record-of-migrations)). With `DATABASE_URL` set, `protobase migration` applies the file to the database in a transaction it rolls back, reads the schema before and after, and names what older code loses: a table, column, sequence, function or enum value dropped, renamed or moved, a trigger dropped, disabled or firing on fewer events, a table or column made again with its rows or values lost, a column whose type changes or that becomes `not null`, a required column without a default or one losing its default, and a new constraint or unique index on a table there already, which rows older code writes may break. A view, function, trigger or generated column made again is not lost, and taking back a privilege, which only narrows access, is always allowed. What the sign-in modules' steps take, such as the organization every personal access token needs once organizations turn on, is Protobase's own path: the file then says `-- protobase:breaks-older-code` in its header, with what the steps take under it, and is recorded as not additive. The drop of `auth_migrations`, the record of versions no code reads since 0.130, takes nothing, and leaves the file additive. What another part would take is refused before anything is written, naming it, with the way through: write the change by hand with `--custom` and mark the file `-- protobase:breaks-older-code`. Protobase's own parts keep what older code still reads, such as the triggers of a resource that no longer has events, history or live updates while another resource is still captured, so the dispatch job drains what they capture; they follow the resource's fields, so a field made sensitive is no longer copied. Once no resource is captured, the change capture drops them, in a file that says `-- protobase:breaks-older-code`; so does the function and trigger of a rollup field the config no longer has, which the next file drops. A rename or a move is always one file that breaks older code, with no view or trigger in between. A column Protobase adds is retired rather than dropped once the config no longer needs it: the column of a rollup or formula field the config no longer has stays as it is, and putting the field back finds it, with its values; the columns a [sign-in module turned off](auth.md#turning-a-module-off) adds to the tables still on stay under their names, watched for the writes older code still makes, and are in use again, with their values, once it is on again. A resource field's column is the project's own, as is its table: removing the field writes nothing, and dropping the column is a hand-written file marked `-- protobase:breaks-older-code`. [`contract` and `delete`](#signing-off-an-update) write their statements under `-- protobase:contract <id>`, naming the migration that stopped older code from using what they take. <gap>A sign-in step that takes from older code cannot carry `-- protobase:contract` because steps naming the migration that stopped older code from using what they take is not implemented.</gap> A [time rollup](data-config.md#time-rollups) that changes has its table made again and filled from its source, which loses no rows, as its comment marks it as Protobase's: only the columns older code reads that it no longer has are named.
689
691
 
690
692
  - `--custom <name>` writes an empty numbered file, `NNN_<name>.sql`, with Protobase's lines and `-- protobase:custom`, for statements you write by hand, and makes the snapshot end at it. Say what it is among its `-- protobase:` lines, which `check` requires: `-- protobase:additive` once it only adds, which `check` verifies with Postgres's own parser, statement by statement, passing only what adds, such as a new table (not `if not exists`, which may find one with rows), a nullable or defaulted column, a plain index, a constraint or unique index on a table the file makes, a new enum value, a trigger dropped and made again on its table, and `create or replace` of a view or function, which Postgres refuses when its columns, arguments or result change; a dropped default, a renamed enum value and a `delete` inside an `insert` or `update` count as taking from older code; or `-- protobase:breaks-older-code` when it takes from older code what it reads, such as a rename or a dropped column. Either way `migrate` records it as not additive unless it says `-- protobase:additive`. Write the statements above the statement that records it, which stays last; `migrate` fills in its hash and whether it is marked additive from the finished file. With `--record-config`, the snapshot takes the sign-in store's names as the config has them now, each module at the step it was: the file is where you make the store match, such as a rename, and it says `-- protobase:breaks-older-code`. With `--after`, it also writes an empty `NNN_<name>.after.sql` beside it, for statements that cannot run in a transaction, such as `create index concurrently if not exists`, which `migrate` runs once the file commits (see [The record of migrations](../guides/deploy.md#the-record-of-migrations)).
691
693
  - `check`, for CI, writes nothing and exits 1 with a line for each problem: a config or Protobase version that needs steps the migrations lack, of the sign-in store or a schema module, or a schema module the snapshot does not record at all, a name the config changed, two files that share a number when Protobase wrote one of them, a snapshot that does not end at the newest file Protobase wrote or whose model does not match its `modelHash`, a hand-written file that says neither `-- protobase:additive` nor `-- protobase:breaks-older-code`, says both, has a statement marked `-- protobase:contract`, which only Protobase writes, or is marked additive while a statement does not only add, and a `-- protobase:contract <id>` that names no file before its own. It also prints a `warning:` line, which leaves the exit code alone, for each statement the `squawk-cli` linter finds that holds a lock blocking reads while it scans or rewrites a table, such as `set not null` or a column type change, and for each statement of a file Protobase wrote that takes from older code without `-- protobase:contract`, such as a formula's column made again.
692
- - `baseline` describes, once, what the project's earlier migrations made that the snapshot does not record: each schema module the config needs, such as a jobs schema an earlier version's `protobase migration` wrote, read from its catalogue as the step pg-boss's version is at and the version Protobase's functions carry, and refused at a pg-boss version no step records, or a change capture, read as its first step once the outbox is there, `capture()` at its version when its body is the one this version writes, and each resource whose table has triggers calling it, which the next `protobase migration` writes again when they are not the ones the config makes, and refused for an outbox without its `database_role` column or a history table without its indexes, or the rollups and formulas, read as their first step once the `rollups` schema is there, and each rollup's column, formula's column, rollup's function and trigger, and time rollup's table and refresh function found, current when it is what this or, for a rollup or formula, an earlier version made of the config, else made again by the next `protobase migration`, as a time rollup an earlier version made is, and refused where the column or table is the project's own or a rollup's column is of another type, or the `derived` schema, read as its first step once its tables, sequence and indexes are there, with each value `derived.declared` marks, and refused without the sequence, the pending table or their indexes, or the schemas of user tables, read as their first step once every part is there, and refused for a definitions table made before organizations, or the tables of webhooks, workflows and notifications, each read as its first step once its tables are there with every index and, for a devices or history table of the app's own, each column under its configured name and the foreign key to the users, the webhooks' functions at the version their comments carry and the workflows' at version 28, the statuses table read as its first step once it has its columns and the foreign key to the users, the calls schema as its first step once its tables are there and its second once its guest tables are too, the `realtime_relay` and `channels` schemas as their first step once their tables are there, `channels.send()` too, the comments, mail feedback and opt-outs tables as their first step once each is there with every index, the query role as its first step once it and the `query` schema are there, with its function at version 1 when it is the one this version writes, owned by the role and not executable by everyone, each resource whose table it reads, and each table it reads that no resource has, which the next `protobase migration` takes back, and the relay's trigger and `realtime.members` functions at their versions with each listed channel whose triggers are the ones this version writes, enabled on its table and its partitions, else written again by the next `protobase migration`, and refused at an older version or shape no step records, such as webhooks without the indexes their version 2 added, a devices table without its session column, a feedback table whose recipient a complaint cannot leave out, or `realtime.members` functions before their version 3; in a project without a snapshot, the sign-in store too. It writes `NNN_baseline.sql`, which changes nothing and records itself, and the snapshot with them, after which `protobase migration` writes only what they lack. For the sign-in store, it starts the snapshot of a project whose store came from auth migrations written before it, such as an app's existing `db/migrations/*_auth.sql`, once: run it with `DATABASE_URL` pointing at the database with those migrations applied. In one read-only transaction it reads the steps the store records in `auth_steps`, or for a store an earlier Protobase made, the versions it records in `auth_migrations`, and the tables of the store's schema, and writes `NNN_baseline.sql`, which drops nothing, changes nothing but making `auth_steps` from `auth_migrations` where the store lacks it, and records itself in `migrations.history`, and `protobase.snapshot.json` describing the store as it is: each module the config has on at the step its recorded versions reach, so the former chain's versions 1 to 8 put each module at its first step; a module that is off but has tables as kept; organizations as ever on when a table whose rows belong to an organization, such as `member`, has the column that names it; and the user table as external when the config reads it through [`users.keyTable`](auth.md#a-view-over-another-systems-users), so no step writes to it; a user table the database has as a view needs `users.keyTable`, naming the table that holds the user ids, and is refused without it. `auth_migrations` stays as it is, read no more. Apply the file with the project's other migrations, then run `protobase migration`, which writes only the steps the store lacks, and nothing for a current store. It refuses a project whose snapshot records every schema module the database has, a store with neither record, one made before 0.48, which [`auth migration`](#auth-migration) adopts first, a version this Protobase does not ship, and a table a recorded step made that the schema lacks under the name the config gives it, such as one renamed since, naming each. <gap>`baseline` cannot refuse a column renamed since a step made it because recording which columns each step adds is not implemented.</gap> The first `protobase migration` after it keeps the organization of each personal access token that has one, and refuses one without, naming it, rather than give it the [default organization](auth.md#the-default-organization): no other column says where a token works.
693
- - `drop` deletes the newest file Protobase wrote and takes the snapshot back to the one before it, from that file's lines, or removes the snapshot with the first file. It refuses while two files share a number or the snapshot does not end at the newest file, so it never deletes another branch's file, and after a file that recorded a changed config, whose snapshot before it only version control has.
694
+ - `baseline` describes, once, what the project's earlier migrations made that the snapshot does not record: each schema module the config needs, such as a jobs schema an earlier version's `protobase migration` wrote, read from its catalogue as the step pg-boss's version is at and the version Protobase's functions carry, and refused at a pg-boss version no step records, or a change capture, read as its first step once the outbox is there, `capture()` at its version when its body is the one this version writes, and each resource whose table has triggers calling it, which the next `protobase migration` writes again when they are not the ones the config makes, and refused for an outbox without its `database_role` column or a history table without its indexes, or the rollups and formulas, read as their first step once the `rollups` schema is there, and each rollup's column, formula's column, rollup's function and trigger, and time rollup's table and refresh function found, current when it is what this or, for a rollup or formula, an earlier version made of the config, else made again by the next `protobase migration`, as a time rollup an earlier version made is, and refused where the column or table is the project's own or a rollup's column is of another type, or the `derived` schema, read as its first step once its tables, sequence and indexes are there, with each value `derived.declared` marks, and refused without the sequence, the pending table or their indexes, or the schemas of user tables, read as their first step once every part is there, and refused for a definitions table made before organizations, or the tables of webhooks, workflows and notifications, each read as its first step once its tables are there with every index and, for a devices or history table of the app's own, each column under its configured name and the foreign key to the users, the webhooks' functions at the version their comments carry and the workflows' at version 28, the statuses table read as its first step once it has its columns and the foreign key to the users, the calls schema as its first step once its tables are there and its second once its guest tables are too, the `realtime_relay` and `channels` schemas as their first step once their tables are there, `channels.send()` too, the comments, mail feedback and opt-outs tables as their first step once each is there with every index, the query role as its first step once it and the `query` schema are there, with its function at version 1 when it is the one this version writes, owned by the role and not executable by everyone, each resource whose table it reads, and each table it reads that no resource has, which the next `protobase migration` takes back, and the relay's trigger and `realtime.members` functions at their versions with each listed channel whose triggers are the ones this version writes, enabled on its table and its partitions, else written again by the next `protobase migration`, and refused at an older version or shape no step records, such as webhooks without the indexes their version 2 added, a devices table without its session column, a feedback table whose recipient a complaint cannot leave out, or `realtime.members` functions before their version 3; in a project without a snapshot, the sign-in store too. It writes `NNN_baseline.sql`, which changes nothing and records itself, and the snapshot with them, after which `protobase migration` writes only what they lack. For the sign-in store, it starts the snapshot of a project whose store came from auth migrations written before it, such as an app's existing `db/migrations/*_auth.sql`, once: run it with `DATABASE_URL` pointing at the database with those migrations applied. In one read-only transaction it reads the steps the store records in `auth_steps` and the tables of the store's schema, and writes `NNN_baseline.sql`, which changes nothing and records itself in `migrations.history`, and `protobase.snapshot.json` describing the store as it is: each module the config has on at the step it records; a module that is off but has tables as kept; organizations as ever on when a table whose rows belong to an organization, such as `member`, has the column that names it; and the user table as external when the config reads it through [`users.keyTable`](auth.md#a-view-over-another-systems-users), so no step writes to it; a user table the database has as a view needs `users.keyTable`, naming the table that holds the user ids, and is refused without it. `auth_migrations` stays as it is, read no more. Apply the file with the project's other migrations, then run `protobase migration`, which writes only the steps the store lacks, and nothing for a current store. It refuses a project whose snapshot records every schema module the database has, a store that records versions in `auth_migrations` without `auth_steps`, which Protobase 0.130 moves to `auth_steps` first, a store without either record, one made before 0.48, which [`auth migration`](#auth-migration) adopts first, a version this Protobase does not ship, and a table a recorded step made that the schema lacks under the name the config gives it, such as one renamed since, naming each. <gap>`baseline` cannot refuse a column renamed since a step made it because recording which columns each step adds is not implemented.</gap> The first `protobase migration` after it keeps the organization of each personal access token that has one, and refuses one without, naming it, rather than give it the [default organization](auth.md#the-default-organization): no other column says where a token works.
695
+ - `drop` deletes the newest file Protobase wrote and takes the snapshot back to the one before it, from that file's lines, or removes the snapshot with the first file. It refuses while two files share a number or the snapshot does not end at the newest file, so it never deletes another branch's file, and after a file that recorded a changed config, or one `contract` or `delete` wrote, whose snapshot before it only version control has.
694
696
  - `up` rewrites the snapshot in this version's format. Every other command refuses a snapshot of an older format, and one of a newer format, which only a newer Protobase reads.
695
697
 
698
+ #### Signing off an update
699
+
700
+ An update that turned a sign-in module off with `--off archive` or `--off delete` keeps its tables, as keep does, until you sign it off: once the update counts as successful, `protobase migration contract` writes the next numbered file, `NNN_contract.sql`, which archives each such module. Every statement in it carries `-- protobase:contract <id>`, naming the file that turned the module off, and the file says `-- protobase:breaks-older-code`. Its first statement refuses, so `migrate` applies none of it, until `migrations.history` has that file's row, a migration applied after it, as the next update applies one, and `--hours` (24 by default) since it was applied. The archive moves the module's tables, with their rows, to the schema `protobase_archive_<n>`, `<n>` being the file's number, after dropping every foreign key between them and the tables still on, in either direction; renames each column the module added to the tables still on to `<column>_archive`; watches both in `retired.writes`, a table's writes under the column `*`; and takes every privilege on that schema and its tables and sequences from each role that owns or holds one, from everyone, and from the role applying the file, so the app's roles get `permission denied`. The snapshot moves the module from `decisions.modules.kept` to `decisions.modules.archived`, with the schema, its tables and the archived columns. A module turned on again after its archive starts from its first step under the live names, with its rows in `auth_steps` reset, as fresh empty tables, except a column it leaves in use while off, such as a personal access token's `organization_id`, which keeps its values and its steps and gets back the foreign key the archive took, not checked against rows whose organization the archive holds, which no longer work; the archive stays as it is, still refused, until it is deleted, and there is no restore from it. Turning it off again with archive or delete is refused while that archive is there.
701
+
702
+ `protobase migration delete <module>` writes the file that removes an archived module for good, never written on its own: its statements, each under `-- protobase:contract` naming the sign-off's file, refuse until that file was applied `--hours` ago (168 by default), and while `retired.writes` counts a write of an archived table or column within those hours, or does not watch one. It then drops the archived tables, the schema once nothing else is in it, and each `<column>_archive`, and, while the module is still off, its rows in `auth_steps`; the snapshot no longer lists it as archived. Archive and delete differ only in the choice the snapshot records: what removes the tables is always `delete`. Dropping what a module retired takes three applications of the migrations, each in an update of its own: the one that turns the module off stops every reader and writer; the sign-off comes in a later one, once another migration was applied after the off file and `--hours` passed since it; and the delete in one after that, `--hours` after the sign-off.
703
+
696
704
  When two branches each write a migration, both rewrite the snapshot, so merging the second reports a conflict in `protobase.snapshot.json`, and the commands refuse until it is resolved. On the second branch, delete its own new file, take the other branch's snapshot, and run `protobase migration` again: it writes the second branch's changes as one file after the other's.
697
705
 
698
706
  ```sh
@@ -724,7 +732,7 @@ Prints the app's entry for the apps file of [Realtime](realtime-relay.md), as JS
724
732
  protobase auth migration [--dir db/migrations] [--name auth]
725
733
  ```
726
734
 
727
- Run inside a project, against its database with the project's migrations applied. It reads the steps the store applied from its `auth_steps` table, or for a store an earlier Protobase made, the versions it applied from `auth_migrations`, which the file then records by step in `auth_steps`, and writes the steps of the modules the config has on that it has not, each followed by its row there, as the next migration in `--dir`: `009_auth.sql` after `008_...`, with the store's schema, user table, columns and id type as the config's `auth` names them. Nothing is written when the store is current and the project has a snapshot, nor with sign-in off, when it says so and exits 0. The file only adds, never drops; apply it with the project's other migrations. It starts with Protobase's lines, ends with the statement that records it in `migrations.history`, and starts the project's `protobase.snapshot.json`, or moves it on, with the store at every step, so [`migration`](#migration) goes on from it. A project without a snapshot whose store is current, such as one whose auth migrations an earlier Protobase wrote, gets a file without statements that starts it, and one whose store is current but not in `migrations.history`, such as one migrated before that record, a file that only records it. For a store made before 0.48, with neither record, it writes the step that adopts it once, and refuses one that matches no version, naming what differs. See [migrations](auth.md#migrations).
735
+ Run inside a project, against its database with the project's migrations applied. It reads the steps the store applied from its `auth_steps` table, refusing a store that records versions in `auth_migrations` without it, which Protobase 0.130 moves there first, and writes the steps of the modules the config has on that it has not, each followed by its row there, as the next migration in `--dir`: `009_auth.sql` after `008_...`, with the store's schema, user table, columns and id type as the config's `auth` names them. Nothing is written when the store is current and the project has a snapshot, nor with sign-in off, when it says so and exits 0. The file only adds, and drops nothing but `auth_migrations`, the record of versions `auth_steps` replaced; apply it with the project's other migrations. It starts with Protobase's lines, ends with the statement that records it in `migrations.history`, and starts the project's `protobase.snapshot.json`, or moves it on, with the store at every step, so [`migration`](#migration) goes on from it. A project without a snapshot whose store is current, such as one whose auth migrations an earlier Protobase wrote, gets a file without statements that starts it, and one whose store is current but not in `migrations.history`, such as one migrated before that record, a file that only records it. For a store made before 0.48, with neither record, it writes the step that adopts it once, and refuses one that matches no version, naming what differs. See [migrations](auth.md#migrations).
728
736
 
729
737
  ## `import supabase`
730
738