@protobase/cli 0.130.0 → 0.130.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/package.js +1 -1
- package/dist/migration/register.js +24 -1
- package/dist/migration/sign-off/contract.js +65 -0
- package/dist/migration/sign-off/delete.js +50 -0
- package/dist/migration/sign-off/signed-off-file.js +19 -0
- package/dist/migration/snapshot/auth-difference.js +36 -8
- package/dist/migration/snapshot/drop.js +2 -1
- package/dist/migration/snapshot/module-prompts.js +18 -4
- package/dist/migration/snapshot/run-migration.js +3 -2
- package/package.json +8 -8
- package/skills/protobase/references/features/build-and-run.md +1 -0
- package/skills/protobase/references/reference/auth.md +1 -1
- package/skills/protobase/references/reference/cli.md +12 -4
package/dist/cli/package.js
CHANGED
|
@@ -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);
|
|
@@ -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
|
-
|
|
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
|
|
7
|
-
|
|
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
|
-
|
|
11
|
-
throw new Error(`"${answer}" is not a choice: keep
|
|
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\``;
|
|
@@ -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
|
|
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);
|
|
@@ -111,7 +112,7 @@ const runMigration = async (run) => {
|
|
|
111
112
|
protobaseVersion,
|
|
112
113
|
...decisions && { decisions }
|
|
113
114
|
};
|
|
114
|
-
return writeMigrationFile(projectDir, dir, content, draft,
|
|
115
|
+
return writeMigrationFile(projectDir, dir, content, draft, id);
|
|
115
116
|
};
|
|
116
117
|
//#endregion
|
|
117
118
|
export { intro, runMigration };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.130.
|
|
3
|
+
"version": "0.130.1",
|
|
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.
|
|
47
|
-
"@protobase/layout": "0.130.
|
|
48
|
-
"@protobase/query": "0.130.
|
|
49
|
-
"@protobase/schema": "0.130.
|
|
50
|
-
"@protobase/server": "0.130.
|
|
51
|
-
"@protobase/ui": "0.130.
|
|
52
|
-
"@protobase/workflows": "0.130.
|
|
46
|
+
"@protobase/config": "0.130.1",
|
|
47
|
+
"@protobase/layout": "0.130.1",
|
|
48
|
+
"@protobase/query": "0.130.1",
|
|
49
|
+
"@protobase/schema": "0.130.1",
|
|
50
|
+
"@protobase/server": "0.130.1",
|
|
51
|
+
"@protobase/ui": "0.130.1",
|
|
52
|
+
"@protobase/workflows": "0.130.1",
|
|
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.
|
|
@@ -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
|
|
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
|
|
|
@@ -667,17 +667,19 @@ 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
|
|
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
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`, 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.
|
|
683
685
|
|
|
@@ -685,14 +687,20 @@ The rest of the file is what the config still needs of the database, compared wi
|
|
|
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`.
|
|
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. 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
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`, 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.
|
|
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
|