@protobase/cli 0.128.0 → 0.129.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/auth/migration-file.js +3 -1
- package/dist/auth/write-migration.js +15 -5
- package/dist/cli/package.js +1 -1
- package/dist/dev/entry.js +5 -4
- package/dist/migration/apply-migrations.js +96 -25
- package/dist/migration/baseline/read-live-store.js +36 -0
- package/dist/migration/baseline/write-baseline.js +47 -0
- package/dist/migration/plan-migrations.js +26 -24
- package/dist/migration/record/after-file.js +22 -0
- package/dist/migration/record/fill-row.js +25 -0
- package/dist/migration/record/migration-dir.js +34 -0
- package/dist/migration/record/pending.js +36 -0
- package/dist/migration/record/record-block.js +38 -0
- package/dist/migration/record/run-after.js +23 -0
- package/dist/migration/register.js +20 -2
- package/dist/migration/release/apply-release-steps.js +6 -5
- package/dist/migration/release/release-record.js +30 -0
- package/dist/migration/snapshot/auth-difference.js +9 -2
- package/dist/migration/snapshot/check.js +3 -5
- package/dist/migration/snapshot/custom.js +15 -5
- package/dist/migration/snapshot/drop.js +9 -4
- package/dist/migration/snapshot/migration-files.js +3 -2
- package/dist/migration/snapshot/next-snapshot.js +18 -8
- package/dist/migration/snapshot/run-migration.js +4 -3
- package/dist/migration/snapshot/snapshot-file.js +4 -3
- package/dist/migration/snapshot/write-file.js +20 -4
- package/dist/serve/create-admin.js +3 -2
- package/dist/serve/migrate-release.js +14 -7
- package/dist/serve/startup-checks.js +6 -4
- package/dist/users/set-disabled.js +3 -2
- package/package.json +8 -8
- package/skills/protobase/references/features/build-and-run.md +4 -3
- package/skills/protobase/references/guides/deploy.md +15 -1
- package/skills/protobase/references/reference/auth.md +1 -1
- package/skills/protobase/references/reference/cli.md +10 -8
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { recordBlock } from "../record/record-block.js";
|
|
2
|
+
import { modelHash, recordsRuntimeModel, runtimeModel, storeNamesList } from "@protobase/server/internal";
|
|
3
|
+
//#region src/migration/release/release-record.ts
|
|
4
|
+
/**
|
|
5
|
+
* The row that records a release in the record of migrations once its steps are applied, as a file's record block
|
|
6
|
+
* does: the model this release reads with `auth`, additive when only the auth store's steps, which only add, apply.
|
|
7
|
+
* `undefined` when the record has the model already and no step applies.
|
|
8
|
+
*/
|
|
9
|
+
const releaseRecord = async (auth, steps, protobaseVersion, id) => {
|
|
10
|
+
if (steps.length === 0 && await recordsRuntimeModel(auth)) return;
|
|
11
|
+
const model = runtimeModel(auth);
|
|
12
|
+
const row = {
|
|
13
|
+
id,
|
|
14
|
+
number: null,
|
|
15
|
+
name: `release ${protobaseVersion}`,
|
|
16
|
+
protobaseVersion,
|
|
17
|
+
model,
|
|
18
|
+
modelHash: modelHash(model),
|
|
19
|
+
physical: { auth: storeNamesList(model.auth) },
|
|
20
|
+
additive: steps.every(({ name }) => name === "auth"),
|
|
21
|
+
completed: true
|
|
22
|
+
};
|
|
23
|
+
return {
|
|
24
|
+
name: "record",
|
|
25
|
+
title: "The row that records this release in the record of migrations",
|
|
26
|
+
sql: recordBlock(row, null)
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
//#endregion
|
|
30
|
+
export { releaseRecord };
|
|
@@ -13,6 +13,13 @@ const authRefusals = (snapshot, target) => {
|
|
|
13
13
|
if (!target) return [`sign-in is off while ${snapshotFile} has the auth store, and turning it off is not supported yet`];
|
|
14
14
|
return nameChanges(before, storeModel(target.names, lastStepsOf(before))).map((change) => `the auth store's ${change}`);
|
|
15
15
|
};
|
|
16
|
+
/** The steps the store lacks after the snapshot's, which leave alone a user table the snapshot records as external. */
|
|
17
|
+
const stepsAfter = (snapshot, target) => {
|
|
18
|
+
const before = snapshot?.model.auth;
|
|
19
|
+
const user = target.names.names.table("user");
|
|
20
|
+
const userName = target.names.schema === void 0 ? user.name : `${target.names.schema}.${user.name}`;
|
|
21
|
+
return offlineStepsMigration(target.names, before && lastStepsOf(before), snapshot?.decisions.external?.includes(userName) ?? false);
|
|
22
|
+
};
|
|
16
23
|
/** How to write what the steps cannot, once refused. */
|
|
17
24
|
const customHint = "Write the change by hand with `protobase migration --custom <name> --record-config`.";
|
|
18
25
|
/**
|
|
@@ -27,11 +34,11 @@ const authDifference = (snapshot, target) => {
|
|
|
27
34
|
migration: void 0
|
|
28
35
|
};
|
|
29
36
|
const before = snapshot?.model.auth;
|
|
30
|
-
const migration =
|
|
37
|
+
const migration = stepsAfter(snapshot, target);
|
|
31
38
|
return {
|
|
32
39
|
migration,
|
|
33
40
|
model: storeModel(target.names, migration || !before ? latestSteps(target.names.names.modules) : lastStepsOf(before))
|
|
34
41
|
};
|
|
35
42
|
};
|
|
36
43
|
//#endregion
|
|
37
|
-
export { authDifference, authRefusals, customHint, lastStepsOf };
|
|
44
|
+
export { authDifference, authRefusals, customHint, lastStepsOf, stepsAfter };
|
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { readSnapshot, snapshotFile } from "./snapshot-file.js";
|
|
2
|
+
import { authRefusals, stepsAfter } from "./auth-difference.js";
|
|
2
3
|
import { readMigrationFiles } from "./migration-files.js";
|
|
3
4
|
import { inconsistencies } from "./consistency.js";
|
|
4
5
|
import "../../auth/migration-file.js";
|
|
5
|
-
import { authRefusals, lastStepsOf } from "./auth-difference.js";
|
|
6
6
|
import { lintCustomFiles } from "./lint-custom.js";
|
|
7
|
-
import { offlineStepsMigration } from "@protobase/server/internal";
|
|
8
7
|
//#region src/migration/snapshot/check.ts
|
|
9
8
|
/**
|
|
10
9
|
* `protobase migration check`, for CI: what keeps the migrations from matching the config, one line each, from the
|
|
@@ -15,11 +14,10 @@ const checkMigrations = async (projectDir, dir, auth) => {
|
|
|
15
14
|
const snapshot = await readSnapshot(projectDir);
|
|
16
15
|
const files = await readMigrationFiles(dir);
|
|
17
16
|
const found = inconsistencies(snapshot, files);
|
|
18
|
-
const before = snapshot?.model.auth;
|
|
19
17
|
const refusals = authRefusals(snapshot, auth);
|
|
20
|
-
if (!snapshot && auth && files.some(({ text }) => text.includes("The auth schema changes this version of Protobase needs"))) found.push(`the project has auth migrations from before ${snapshotFile}: start it with \`protobase
|
|
18
|
+
if (!snapshot && auth && files.some(({ text }) => text.includes("The auth schema changes this version of Protobase needs"))) found.push(`the project has auth migrations from before ${snapshotFile}: start it with \`protobase migration baseline\`, against the database with the project's migrations applied`);
|
|
21
19
|
else if (refusals.length > 0) found.push(...refusals);
|
|
22
|
-
else if (auth &&
|
|
20
|
+
else if (auth && stepsAfter(snapshot, auth)) found.push("the config and this version of Protobase need auth store steps the migrations lack: run `protobase migration`");
|
|
23
21
|
return [...found, ...lintCustomFiles(files)];
|
|
24
22
|
};
|
|
25
23
|
//#endregion
|
|
@@ -1,22 +1,29 @@
|
|
|
1
1
|
import { readSnapshot, snapshotFile } from "./snapshot-file.js";
|
|
2
|
+
import { lastStepsOf } from "./auth-difference.js";
|
|
2
3
|
import { readMigrationFiles } from "./migration-files.js";
|
|
3
4
|
import { refuseInconsistent } from "./consistency.js";
|
|
4
|
-
import { lastStepsOf } from "./auth-difference.js";
|
|
5
5
|
import { writeMigrationFile } from "./write-file.js";
|
|
6
6
|
import { storeModel } from "@protobase/server/internal";
|
|
7
7
|
//#region src/migration/snapshot/custom.ts
|
|
8
8
|
const body = (recordConfig) => [
|
|
9
9
|
`-- Written by hand; \`protobase migration --custom\` numbered it and made ${snapshotFile} end at it.`,
|
|
10
10
|
"-- It counts as not additive. Once it only adds, put a line `-- protobase:additive` among the lines above, and `protobase migration check` lints it.",
|
|
11
|
+
"-- Write its statements here, above the row that records it, which stays the last statement.",
|
|
11
12
|
...recordConfig ? [`-- ${snapshotFile} records the auth store as the config names it now: make the store match it here, such as renaming what the config renamed.`] : [],
|
|
12
13
|
""
|
|
13
14
|
].join("\n");
|
|
15
|
+
const afterBody = [
|
|
16
|
+
"-- Run by `protobase migrate` after the migration beside it commits, one statement at a time and outside a transaction,",
|
|
17
|
+
"-- such as `create index concurrently if not exists ...`; each statement ends with a semicolon at the end of a line.",
|
|
18
|
+
"-- The migration is complete once every statement here has run. An index left invalid by a run that stopped is dropped and built again.",
|
|
19
|
+
""
|
|
20
|
+
].join("\n");
|
|
14
21
|
/**
|
|
15
22
|
* `protobase migration --custom <name>`: writes an empty numbered migration for the developer to fill, and makes the
|
|
16
23
|
* snapshot end at it. With `recordConfig`, the snapshot takes the config's auth store names, each module at the step
|
|
17
24
|
* it was. Returns the file's path.
|
|
18
25
|
*/
|
|
19
|
-
const writeCustomMigration = async ({ projectDir, dir, name, recordConfig, auth, protobaseVersion, newId }) => {
|
|
26
|
+
const writeCustomMigration = async ({ projectDir, dir, name, recordConfig, after, auth, protobaseVersion, newId }) => {
|
|
20
27
|
const snapshot = await readSnapshot(projectDir);
|
|
21
28
|
refuseInconsistent(snapshot, await readMigrationFiles(dir));
|
|
22
29
|
const before = snapshot?.model.auth;
|
|
@@ -26,14 +33,17 @@ const writeCustomMigration = async ({ projectDir, dir, name, recordConfig, auth,
|
|
|
26
33
|
organizationsOn: auth?.organizationsOn ?? false,
|
|
27
34
|
protobaseVersion
|
|
28
35
|
};
|
|
29
|
-
|
|
36
|
+
const content = {
|
|
30
37
|
name,
|
|
31
38
|
body: body(recordConfig),
|
|
32
39
|
kind: {
|
|
33
40
|
custom: true,
|
|
34
41
|
additive: false
|
|
35
|
-
}
|
|
36
|
-
|
|
42
|
+
},
|
|
43
|
+
additive: false,
|
|
44
|
+
...after && { after: afterBody }
|
|
45
|
+
};
|
|
46
|
+
return writeMigrationFile(projectDir, dir, content, draft, newId());
|
|
37
47
|
};
|
|
38
48
|
//#endregion
|
|
39
49
|
export { writeCustomMigration };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { modelHash, readSnapshot, removeSnapshot, snapshotFile, writeSnapshot } from "./snapshot-file.js";
|
|
1
|
+
import { modelHash as modelHash$1, readSnapshot, removeSnapshot, snapshotFile, writeSnapshot } from "./snapshot-file.js";
|
|
2
|
+
import { afterFileOf } from "../record/after-file.js";
|
|
2
3
|
import { protobaseFiles, readMigrationFiles } from "./migration-files.js";
|
|
3
4
|
import { refuseInconsistent } from "./consistency.js";
|
|
4
5
|
import path from "node:path";
|
|
@@ -30,14 +31,18 @@ const dropMigration = async (projectDir, dir) => {
|
|
|
30
31
|
const written = protobaseFiles(files);
|
|
31
32
|
const newest = written.at(-1);
|
|
32
33
|
const previous = written.at(-2);
|
|
33
|
-
|
|
34
|
+
const remove = async () => {
|
|
34
35
|
await rm(path.join(dir, newest.file));
|
|
36
|
+
await rm(path.join(dir, afterFileOf(newest.file)), { force: true });
|
|
37
|
+
};
|
|
38
|
+
if (!previous) {
|
|
39
|
+
await remove();
|
|
35
40
|
await removeSnapshot(projectDir);
|
|
36
41
|
return newest.file;
|
|
37
42
|
}
|
|
38
43
|
const auth = atSteps(snapshot.model.auth, previous.header.steps);
|
|
39
44
|
const model = auth ? { auth } : {};
|
|
40
|
-
if (modelHash(model) !== previous.header.model) throw new Error(`${newest.file} changed more than the steps, so the snapshot before it cannot be rebuilt: delete it by hand and take ${snapshotFile} from before it from version control`);
|
|
45
|
+
if (modelHash$1(model) !== previous.header.model) throw new Error(`${newest.file} changed more than the steps, so the snapshot before it cannot be rebuilt: delete it by hand and take ${snapshotFile} from before it from version control`);
|
|
41
46
|
const rebuilt = {
|
|
42
47
|
...snapshot,
|
|
43
48
|
protobaseVersion: previous.header.version,
|
|
@@ -56,7 +61,7 @@ const dropMigration = async (projectDir, dir) => {
|
|
|
56
61
|
},
|
|
57
62
|
physical: auth ? { auth: storeNamesList(auth) } : {}
|
|
58
63
|
};
|
|
59
|
-
await
|
|
64
|
+
await remove();
|
|
60
65
|
await writeSnapshot(projectDir, rebuilt);
|
|
61
66
|
return newest.file;
|
|
62
67
|
};
|
|
@@ -1,13 +1,14 @@
|
|
|
1
|
+
import { isAfterFile } from "../record/after-file.js";
|
|
1
2
|
import { parseHeader } from "./header.js";
|
|
2
3
|
import { existsSync } from "node:fs";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { readFile, readdir } from "node:fs/promises";
|
|
5
6
|
//#region src/migration/snapshot/migration-files.ts
|
|
6
7
|
const numbered = /^(\d+)_.*\.sql$/;
|
|
7
|
-
/** The numbered migrations of `dir`, by number then name; none when it does not exist. */
|
|
8
|
+
/** The numbered migrations of `dir`, by number then name, their `.after.sql` aside; none when it does not exist. */
|
|
8
9
|
const readMigrationFiles = async (dir) => {
|
|
9
10
|
if (!existsSync(dir)) return [];
|
|
10
|
-
const names = (await readdir(dir)).filter((file) => numbered.test(file)).sort();
|
|
11
|
+
const names = (await readdir(dir)).filter((file) => numbered.test(file) && !isAfterFile(file)).sort();
|
|
11
12
|
return (await Promise.all(names.map(async (file) => {
|
|
12
13
|
const text = await readFile(path.join(dir, file), "utf8");
|
|
13
14
|
const header = parseHeader(text);
|
|
@@ -1,25 +1,35 @@
|
|
|
1
|
-
import { modelHash } from "./snapshot-file.js";
|
|
1
|
+
import { modelHash as modelHash$1 } from "./snapshot-file.js";
|
|
2
2
|
import { lastStepsOf } from "./auth-difference.js";
|
|
3
3
|
import { storeNamesList } from "@protobase/server/internal";
|
|
4
4
|
//#region src/migration/snapshot/next-snapshot.ts
|
|
5
|
-
|
|
6
|
-
const
|
|
5
|
+
const externalUser = (auth) => {
|
|
6
|
+
const user = auth?.modules.auth?.tables.user;
|
|
7
|
+
if (!auth?.userKeyTable || !user) return [];
|
|
8
|
+
return [auth.schema === null ? user.name : `${auth.schema}.${user.name}`];
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* The snapshot once the migration `endsAt` is applied: `auth`, the store's model then, and whether organizations are
|
|
12
|
+
* on now. It goes on from `before`, the decisions of the snapshot before it, which a baseline reads from the database.
|
|
13
|
+
*/
|
|
14
|
+
const nextSnapshot = (before, auth, organizationsOn, endsAt, protobaseVersion) => {
|
|
7
15
|
const model = auth ? { auth } : {};
|
|
16
|
+
const external = [.../* @__PURE__ */ new Set([...before?.external ?? [], ...externalUser(auth)])].sort();
|
|
8
17
|
return {
|
|
9
18
|
format: 1,
|
|
10
19
|
protobaseVersion,
|
|
11
20
|
endsAt,
|
|
12
|
-
modelHash: modelHash(model),
|
|
21
|
+
modelHash: modelHash$1(model),
|
|
13
22
|
model,
|
|
14
23
|
decisions: {
|
|
15
|
-
modules:
|
|
24
|
+
modules: before?.modules ?? {
|
|
16
25
|
kept: [],
|
|
17
26
|
archived: []
|
|
18
27
|
},
|
|
19
28
|
organizations: {
|
|
20
|
-
everOn: (
|
|
21
|
-
defaultOrganization:
|
|
22
|
-
}
|
|
29
|
+
everOn: (before?.organizations.everOn ?? false) || organizationsOn,
|
|
30
|
+
defaultOrganization: before?.organizations.defaultOrganization ?? null
|
|
31
|
+
},
|
|
32
|
+
...external.length > 0 && { external }
|
|
23
33
|
},
|
|
24
34
|
physical: auth ? { auth: storeNamesList(auth) } : {}
|
|
25
35
|
};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { readSnapshot, snapshotFile } from "./snapshot-file.js";
|
|
2
|
+
import { authDifference } from "./auth-difference.js";
|
|
2
3
|
import { readMigrationFiles } from "./migration-files.js";
|
|
3
4
|
import { refuseInconsistent } from "./consistency.js";
|
|
4
5
|
import { authMigrationTitle } from "../../auth/migration-file.js";
|
|
5
|
-
import { authDifference } from "./auth-difference.js";
|
|
6
6
|
import { writeMigrationFile } from "./write-file.js";
|
|
7
7
|
import { runPreconditions } from "./preconditions.js";
|
|
8
8
|
//#region src/migration/snapshot/run-migration.ts
|
|
@@ -19,7 +19,7 @@ const runMigration = async ({ projectDir, dir, auth, database, protobaseVersion,
|
|
|
19
19
|
const snapshot = await readSnapshot(projectDir);
|
|
20
20
|
const files = await readMigrationFiles(dir);
|
|
21
21
|
refuseInconsistent(snapshot, files);
|
|
22
|
-
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
|
|
22
|
+
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`);
|
|
23
23
|
const difference = authDifference(snapshot, auth);
|
|
24
24
|
if (database && difference.migration && difference.migration.checks.length > 0) await runPreconditions(database.url, difference.migration.checks);
|
|
25
25
|
const compared = [];
|
|
@@ -37,7 +37,8 @@ const runMigration = async ({ projectDir, dir, auth, database, protobaseVersion,
|
|
|
37
37
|
if (sections.length === 0) return;
|
|
38
38
|
const content = {
|
|
39
39
|
name: sections.map(({ name }) => name).join("_"),
|
|
40
|
-
body: [intro, ...sections.map(({ text }) => text)].join("\n")
|
|
40
|
+
body: [intro, ...sections.map(({ text }) => text)].join("\n"),
|
|
41
|
+
additive: sections.every(({ name }) => name === "auth")
|
|
41
42
|
};
|
|
42
43
|
return writeMigrationFile(projectDir, dir, content, {
|
|
43
44
|
previous: snapshot,
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { createHash } from "node:crypto";
|
|
4
3
|
import { readFile, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { modelHash } from "@protobase/server/internal";
|
|
5
5
|
//#region src/migration/snapshot/snapshot-file.ts
|
|
6
6
|
const snapshotFile = "protobase.snapshot.json";
|
|
7
|
-
|
|
7
|
+
/** The model's hash, as the record of migrations and the server's startup compare it. */
|
|
8
|
+
const modelHash$1 = (model) => modelHash(model);
|
|
8
9
|
/** The file's text: two-space JSON and a final newline, so the same snapshot is the same bytes. */
|
|
9
10
|
const snapshotText = (snapshot) => `${JSON.stringify(snapshot, null, 2)}\n`;
|
|
10
11
|
/** The snapshot's JSON as it stands, of any format; `undefined` when the project has none. */
|
|
@@ -30,4 +31,4 @@ const readSnapshot = async (projectDir) => {
|
|
|
30
31
|
const writeSnapshot = (projectDir, snapshot) => writeFile(path.join(projectDir, snapshotFile), snapshotText(snapshot));
|
|
31
32
|
const removeSnapshot = (projectDir) => rm(path.join(projectDir, snapshotFile));
|
|
32
33
|
//#endregion
|
|
33
|
-
export { checkFormat, modelHash, readSnapshot, readSnapshotJson, removeSnapshot, snapshotFile, snapshotText, writeSnapshot };
|
|
34
|
+
export { checkFormat, modelHash$1 as modelHash, readSnapshot, readSnapshotJson, removeSnapshot, snapshotFile, snapshotText, writeSnapshot };
|
|
@@ -1,22 +1,38 @@
|
|
|
1
1
|
import { writeSnapshot } from "./snapshot-file.js";
|
|
2
|
+
import { afterFileOf } from "../record/after-file.js";
|
|
2
3
|
import { headerText } from "./header.js";
|
|
3
4
|
import { nextMigrationName } from "../../auth/migration-file.js";
|
|
5
|
+
import { recordBlock, sqlHash } from "../record/record-block.js";
|
|
4
6
|
import { nextSnapshot, snapshotHeader } from "./next-snapshot.js";
|
|
5
7
|
import path from "node:path";
|
|
6
8
|
import { mkdir, readdir, writeFile } from "node:fs/promises";
|
|
7
9
|
//#region src/migration/snapshot/write-file.ts
|
|
8
10
|
/**
|
|
9
|
-
* Writes `content` as the next numbered migration of `dir`, starting with its header and `id
|
|
10
|
-
* project's snapshot to end at it. Returns the file's path.
|
|
11
|
+
* Writes `content` as the next numbered migration of `dir`, starting with its header and `id` and ending with the row
|
|
12
|
+
* that records it (`recordBlock`), then rewrites the project's snapshot to end at it. Returns the file's path.
|
|
11
13
|
*/
|
|
12
14
|
const writeMigrationFile = async (projectDir, dir, content, draft, id) => {
|
|
13
15
|
await mkdir(dir, { recursive: true });
|
|
14
16
|
const file = nextMigrationName(await readdir(dir), content.name);
|
|
15
|
-
const snapshot = nextSnapshot(draft.previous, draft.auth, draft.organizationsOn, {
|
|
17
|
+
const snapshot = nextSnapshot(draft.decisions ?? draft.previous?.decisions, draft.auth, draft.organizationsOn, {
|
|
16
18
|
file,
|
|
17
19
|
id
|
|
18
20
|
}, draft.protobaseVersion);
|
|
19
|
-
|
|
21
|
+
const text = `${headerText(snapshotHeader(snapshot, content.kind))}\n${content.body}\n`;
|
|
22
|
+
const custom = content.kind?.custom ?? false;
|
|
23
|
+
const row = {
|
|
24
|
+
id,
|
|
25
|
+
number: Number(file.split("_")[0]),
|
|
26
|
+
name: file.replace(/\.sql$/, ""),
|
|
27
|
+
protobaseVersion: snapshot.protobaseVersion,
|
|
28
|
+
model: snapshot.model,
|
|
29
|
+
modelHash: snapshot.modelHash,
|
|
30
|
+
physical: snapshot.physical,
|
|
31
|
+
additive: custom ? null : content.additive,
|
|
32
|
+
completed: content.after === void 0
|
|
33
|
+
};
|
|
34
|
+
await writeFile(path.join(dir, file), `${text}${recordBlock(row, custom ? null : sqlHash(text))}`, { flag: "wx" });
|
|
35
|
+
if (content.after !== void 0) await writeFile(path.join(dir, afterFileOf(file)), content.after, { flag: "wx" });
|
|
20
36
|
await writeSnapshot(projectDir, snapshot);
|
|
21
37
|
return path.join(dir, file);
|
|
22
38
|
};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { protobaseVersion } from "../version/version.js";
|
|
1
2
|
import { projectAuth } from "../config/build-project.js";
|
|
2
3
|
import { openAppDatabase } from "../project/pg-db.js";
|
|
3
4
|
import { readHidden } from "../users/password.js";
|
|
@@ -7,7 +8,7 @@ import { checkBundleManifest } from "./bundle-manifest.js";
|
|
|
7
8
|
import { loadBundle } from "./load-bundle.js";
|
|
8
9
|
import { bundleConfigFile } from "../worker/start-worker.js";
|
|
9
10
|
import pg from "pg";
|
|
10
|
-
import {
|
|
11
|
+
import { checkMigrationRecord } from "@protobase/server";
|
|
11
12
|
//#region src/serve/create-admin.ts
|
|
12
13
|
const createAdminInBundle = async (bundle, email, options, out) => {
|
|
13
14
|
const file = await bundleConfigFile(bundle);
|
|
@@ -16,7 +17,7 @@ const createAdminInBundle = async (bundle, email, options, out) => {
|
|
|
16
17
|
if (!config.auth) throw new Error("Sign-in is off in the bundle's config (`auth: false`), so the app has no users to manage");
|
|
17
18
|
if (!process.env.DATABASE_URL) throw new Error("No database: set DATABASE_URL");
|
|
18
19
|
const auth = await projectAuth(config, openAppDatabase(pg, process.env.DATABASE_URL));
|
|
19
|
-
await
|
|
20
|
+
await checkMigrationRecord(auth, protobaseVersion);
|
|
20
21
|
await createUserCommand(usersApi(auth), {
|
|
21
22
|
email,
|
|
22
23
|
role: "admin",
|
|
@@ -1,19 +1,24 @@
|
|
|
1
|
+
import { protobaseVersion } from "../version/version.js";
|
|
1
2
|
import { readManifest } from "../bundle/manifest.js";
|
|
2
3
|
import { checkBundleManifest } from "./bundle-manifest.js";
|
|
3
4
|
import { loadBundle } from "./load-bundle.js";
|
|
4
5
|
import { bundleConfigFile } from "../worker/start-worker.js";
|
|
6
|
+
import { readMigrationDir } from "../migration/record/migration-dir.js";
|
|
7
|
+
import { pendingIn } from "../migration/record/pending.js";
|
|
5
8
|
import { migrationProject } from "../migration/migration-project.js";
|
|
6
|
-
import { pendingIn } from "../migration/plan-migrations.js";
|
|
7
9
|
import { applyReleaseSteps, planReleaseSteps } from "../migration/release/apply-release-steps.js";
|
|
10
|
+
import { releaseRecord } from "../migration/release/release-record.js";
|
|
8
11
|
import { releaseSteps } from "../migration/release/release-steps.js";
|
|
9
12
|
import path from "node:path";
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
10
14
|
import postgres from "postgres";
|
|
11
15
|
//#region src/serve/migrate-release.ts
|
|
12
16
|
/**
|
|
13
17
|
* The runtime's `migrate-release`: brings DATABASE_URL to this release's own schema steps for every feature the
|
|
14
|
-
* bundle's config turns on (see releaseSteps),
|
|
15
|
-
* not at all. It writes no file: the steps come from the
|
|
16
|
-
* first, since the steps are compared with the database they
|
|
18
|
+
* bundle's config turns on (see releaseSteps), then the row that records the release (`releaseRecord`), applied in
|
|
19
|
+
* one transaction, or with `plan` printed as SQL and applied not at all. It writes no file: the steps come from the
|
|
20
|
+
* database and this release. The bundle's own migrations go first, since the steps are compared with the database they
|
|
21
|
+
* made. On a failure the error ends the process.
|
|
17
22
|
*/
|
|
18
23
|
const migrateRelease = async (bundle, env, out, plan) => {
|
|
19
24
|
const file = await bundleConfigFile(bundle);
|
|
@@ -27,9 +32,11 @@ const migrateRelease = async (bundle, env, out, plan) => {
|
|
|
27
32
|
const { migrations } = await readManifest(dir);
|
|
28
33
|
const project = await migrationProject(await loadBundle(file), env.DATABASE_URL);
|
|
29
34
|
const find = async (tx) => {
|
|
30
|
-
const pending = migrations ? await pendingIn(tx, path.join(dir, migrations)) : [];
|
|
31
|
-
if (pending.length > 0) throw new Error(`The database lacks the bundle's migrations ${pending.join(", ")}: apply them first with \`protobase-serve migrate\``);
|
|
32
|
-
|
|
35
|
+
const pending = migrations ? await pendingIn(tx, await readMigrationDir(path.join(dir, migrations))) : [];
|
|
36
|
+
if (pending.length > 0) throw new Error(`The database lacks the bundle's migrations ${pending.map(({ file }) => file).join(", ")}: apply them first with \`protobase-serve migrate\``);
|
|
37
|
+
const steps = await releaseSteps(project);
|
|
38
|
+
const record = project.auth && await releaseRecord(project.auth, steps, protobaseVersion, randomUUID());
|
|
39
|
+
return record ? [...steps, record] : steps;
|
|
33
40
|
};
|
|
34
41
|
await (plan ? planReleaseSteps(sql, find, out) : applyReleaseSteps(sql, find, out));
|
|
35
42
|
await project.close();
|
|
@@ -1,16 +1,18 @@
|
|
|
1
|
+
import { protobaseVersion } from "../version/version.js";
|
|
1
2
|
import { checkProjectRelay } from "./relay-check.js";
|
|
2
|
-
import { assistantSettings, authStoreTables,
|
|
3
|
+
import { assistantSettings, authStoreTables, checkCalls, checkChanges, checkChannelSends, checkComments, checkComputed, checkDerived, checkMailFeedbackSchema, checkMigrationRecord, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkStatusSchema, checkUnsubscribesSchema, checkUserTablesSchema, checkWebhooksSchema, checkWorkflowsSchema, configExports, mailFeedbackResource, relayed, sqlSends } from "@protobase/server";
|
|
3
4
|
//#region src/serve/startup-checks.ts
|
|
4
5
|
/**
|
|
5
|
-
* The server's startup checks of the database:
|
|
6
|
-
*
|
|
6
|
+
* The server's startup checks of the database: the record of its migrations (`checkMigrationRecord`), then each
|
|
7
|
+
* feature whose schema the record's model does not hold yet; each throws, with what to write as a migration, while a
|
|
8
|
+
* schema the project's features need is missing or behind. They only read. `serve` runs them before it builds the admin, and
|
|
7
9
|
* `protobase doctor` runs them too, so a change that would not start fails wherever doctor runs.
|
|
8
10
|
*/
|
|
9
11
|
const checkStartup = async (project, db) => {
|
|
10
12
|
const exported = configExports(project.config);
|
|
11
13
|
const models = exported.resources.map((resource) => resource.toModel());
|
|
12
14
|
const captured = project.mailFeedback ? [...models, mailFeedbackResource.toModel()] : models;
|
|
13
|
-
|
|
15
|
+
await checkMigrationRecord(project.auth, protobaseVersion);
|
|
14
16
|
if (project.auth) await checkResourcesOutsideAuthStore(db, models, project.auth);
|
|
15
17
|
if (project.mailFeedback) await checkMailFeedbackSchema(db);
|
|
16
18
|
await checkChanges(db, captured, project.events);
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import { protobaseVersion } from "../version/version.js";
|
|
1
2
|
import { usersApi } from "./users-api.js";
|
|
2
3
|
import { setDisabledCommand } from "./manage.js";
|
|
3
|
-
import {
|
|
4
|
+
import { checkMigrationRecord } from "@protobase/server";
|
|
4
5
|
//#region src/users/set-disabled.ts
|
|
5
6
|
const setDisabledInProject = async (auth, options, out) => {
|
|
6
|
-
await
|
|
7
|
+
await checkMigrationRecord(auth, protobaseVersion);
|
|
7
8
|
await setDisabledCommand(usersApi(auth), options, out);
|
|
8
9
|
};
|
|
9
10
|
//#endregion
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.129.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.
|
|
47
|
-
"@protobase/layout": "0.
|
|
48
|
-
"@protobase/query": "0.
|
|
49
|
-
"@protobase/schema": "0.
|
|
50
|
-
"@protobase/server": "0.
|
|
51
|
-
"@protobase/ui": "0.
|
|
52
|
-
"@protobase/workflows": "0.
|
|
46
|
+
"@protobase/config": "0.129.1",
|
|
47
|
+
"@protobase/layout": "0.129.1",
|
|
48
|
+
"@protobase/query": "0.129.1",
|
|
49
|
+
"@protobase/schema": "0.129.1",
|
|
50
|
+
"@protobase/server": "0.129.1",
|
|
51
|
+
"@protobase/ui": "0.129.1",
|
|
52
|
+
"@protobase/workflows": "0.129.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",
|
|
@@ -10,9 +10,9 @@ Develop, build and run an app, on servers, in containers and on phones.
|
|
|
10
10
|
- [UI-only dev server](../reference/cli.md#ui-only) (beta): `protobase dev --api <url>` serves the app's UI from the project with the API of an app already running, such as its staging deploy, with no database.
|
|
11
11
|
- [Editor types](../reference/cli.md#types): `protobase types` gives the editor and `tsc` the types of the CLI that builds the app, with nothing installed.
|
|
12
12
|
- [Project scripts](../reference/cli.md#run): `protobase run` runs a seed or a migration script on the CLI's packages.
|
|
13
|
-
- [Migrate command](../reference/cli.md#migrate): `protobase migrate` applies the project's SQL migrations
|
|
13
|
+
- [Migrate command](../reference/cli.md#migrate): `protobase migrate` applies the project's SQL migrations, with nothing installed, and `--plan` prints the SQL it would apply.
|
|
14
14
|
- [Migrations from config](../reference/cli.md#migration): Writes the SQL migrations for what the config turns on, as files of the project.
|
|
15
|
-
- [Schema snapshot](../reference/cli.md#migration) (beta): `protobase.snapshot.json` in the project describes the schema its migrations make, so each new migration is the next numbered file and the change shows in review. The sign-in tables are worked out from it without a database, `protobase migration check` fails CI when the config has a change the migrations lack,
|
|
15
|
+
- [Schema snapshot](../reference/cli.md#migration) (beta): `protobase.snapshot.json` in the project describes the schema its migrations make, so each new migration is the next numbered file and the change shows in review. The sign-in tables are worked out from it without a database, `protobase migration check` fails CI when the config has a change the migrations lack, `drop` takes the newest file back, and `protobase migration baseline` starts the snapshot of an existing app from its database, once, without changing or dropping anything.
|
|
16
16
|
- [User and organization commands](../reference/cli.md#users): Create users, set roles and manage organizations from the terminal.
|
|
17
17
|
- [Encryption commands](../reference/cli.md#encryption-status): Report and fix plaintext or old-key values of encrypted fields.
|
|
18
18
|
- [One bundle](../reference/cli.md#build): `protobase build` writes one folder with everything the app needs, without a database or secrets. It fails on a view that filters, sorts or searches by a field its resource does not allow.
|
|
@@ -21,7 +21,8 @@ Develop, build and run an app, on servers, in containers and on phones.
|
|
|
21
21
|
- [Native packages](../reference/cli.md#native-packages): npm packages with native add-ons are bundled for Linux.
|
|
22
22
|
- [Serve runtime](../reference/cli.md#serve): Runs a bundle, set by environment variables, with a health check, startup checks, jobs and a clean shutdown. `PROTOBASE_HOST=127.0.0.1` keeps it to this computer.
|
|
23
23
|
- [Host module list](../reference/cli.md#the-config-module): Each release of `@protobase/cli` carries the modules its runtime supplies to a bundle as `@protobase/cli/host-modules.json`, for a host to check a bundle's imports against the version that serves it.
|
|
24
|
-
- [Migrations at update time](../guides/deploy.md#migrations): The bundle carries the project's migrations, and the runtime applies them in one transaction
|
|
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
|
+
- [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.
|
|
25
26
|
- [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.
|
|
26
27
|
- [Single-file runtime](../reference/cli.md#build-serve): The runtime as one file, so a host needs only Bun and that file.
|
|
27
28
|
- [Separate worker](../reference/cli.md#worker): Jobs and event delivery in their own process.
|
|
@@ -32,7 +32,21 @@ The host serves `public/` itself and sends only the manifest's `api` paths to th
|
|
|
32
32
|
|
|
33
33
|
## Migrations
|
|
34
34
|
|
|
35
|
-
Serving never changes the database: the bundle carries the project's `db/migrations` as `migrations/`, and the runtime's `migrate <bundle>` applies the pending ones, the app's and the auth schema's, before a new version serves, with no other writes while it runs. It applies them
|
|
35
|
+
Serving never changes the database: the bundle carries the project's `db/migrations` as `migrations/`, and the runtime's `migrate <bundle>` applies the pending ones, the app's and the auth schema's, before a new version serves, with no other writes while it runs. It applies them behind a lock, recorded in `migrations.applied` as the presets' `db:migrate` does, so a database either script migrated is current for the other, and a second run while one runs stops at once instead of waiting. The files apply in batches, each in one transaction, cut after a file with an `.after.sql` (see [The record of migrations](#the-record-of-migrations)). A database an earlier version migrated keeps its record in `public.schema_migrations`, which `migrate` copies over the first time; a `public.schema_migrations` of another migration tool, without Protobase's `name` and `applied_at` columns, is never read or written. A file that would end its transaction (`BEGIN`, `COMMIT`, `ROLLBACK`) or cannot run in one (`create index concurrently`) is refused, and a refused or failing file leaves the database as its batch found it. The runtime reads the database's record of migrations once at startup, without comparing its tables, and refuses to start on a database behind it (see [The record of migrations](#the-record-of-migrations)). [`protobase migration`](../reference/cli.md#migration) writes the files the config's features need, such as the auth and jobs schemas, as the project's own migrations, and [a self-hosted image](#a-self-hosted-image) runs `migrate` as a step of its own before the app starts. A host that serves a bundle on a newer release's runtime brings the database to that release's own schema steps with the runtime's [`migrate-release <bundle>`](../reference/cli.md#release-steps), after `migrate` and before the bundle serves there.
|
|
36
|
+
|
|
37
|
+
### The record of migrations
|
|
38
|
+
|
|
39
|
+
Every migration Protobase writes ends with the statement that records it in `migrations.history`, so the file records itself whichever runner applies it, `protobase migrate`, the runtime's `migrate` or a project's own `db:migrate`. The row holds the file's id, from its first line, its number and name, the version of Protobase that wrote it, the model of what the runtime reads once it is applied with that model's hash, every name it makes, whether it is additive, so older code still runs on the database, the hash of its text without that last statement and with LF line endings, and when it was applied and completed. A file written by hand with [`migration --custom`](../reference/cli.md#migration) leaves its hash and whether it is additive to `migrate`, which fills them from the finished text; a project's own runner leaves them empty, and an empty additive counts as not additive. `migrate` finds the files to apply by their id as well as their name, so a renamed file is not applied twice.
|
|
40
|
+
|
|
41
|
+
A file may have an `.after.sql` beside it, such as `007_indexes.after.sql` beside `007_indexes.sql`, for statements that cannot run in a transaction, such as `create index concurrently if not exists`. `migrate` runs it once the file's batch commits, one statement at a time, each ending with a semicolon at the end of a line, then marks the file complete. A run that stops before then, killed or failing, leaves the file applied but not complete, and the next `migrate` finishes it first; an index it left invalid is dropped and built again. A project's own runner skips `.after.sql` files.
|
|
42
|
+
|
|
43
|
+
The server reads the newest row once at startup, with the model it builds from the config and its code, and starts when the hashes are equal, or when the database is ahead of it only by additive migrations, as when a deploy is rolled back to the version before. It refuses when the database lacks something it reads or has it at an older step, naming the sign-in module and step, the version the database matches and its own, and the two ways out: `protobase migrate --plan` and `protobase migrate`, or running the version the database matches:
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
The database is behind Protobase 0.128.0, so the server will not start: the auth store's passkeys module is at step 1 (passkeys), and this version needs step 2 (rp_id_index). To bring the database up to 0.128.0, run `protobase migrate --plan` to see the migrations it will apply, then `protobase migrate`. Or run Protobase 0.127.5, the version the database matches.
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
It refuses as well on a database ahead of it by a migration that is not additive, while a unique index of an `.after.sql` is still building, and on a database with sign-in that records no migration, such as one migrated before this record: `protobase auth migration` then writes the file that records the store. An unfinished plain index does not keep it from starting. The server never migrates the database itself, and never turns a feature off because its tables are missing. <gap>The record's model cannot hold the jobs, change capture, rollup and other feature schemas because recording their models is not implemented, so the server still checks those schemas at startup one by one.</gap>
|
|
36
50
|
|
|
37
51
|
## Images
|
|
38
52
|
|
|
@@ -40,7 +40,7 @@ Every store has the tables of every module, whether the app turns the feature on
|
|
|
40
40
|
|
|
41
41
|
The names the app configures, the store's schema ([`auth.schema`](config/sign-in.md#authschema)), its [tables and columns](#table-and-column-names), and uuid ids (`generateUserId: 'uuid'`), are the ones in effect when the file is written. Changing one later is a migration of the project's own, such as a rename. <gap>`protobase auth migration` cannot rename a table or column the store has already because writing a rename from a changed name is not implemented.</gap>
|
|
42
42
|
|
|
43
|
-
The server never changes the schema, and never compares it with what Better Auth needs. `protobase serve` and `protobase dev` read `
|
|
43
|
+
The server never changes the schema, and never compares it with what Better Auth needs. `protobase serve` and `protobase dev` read the database's [record of migrations](../guides/deploy.md#the-record-of-migrations), `migrations.history`, at startup and refuse to start while it lacks a step of this Protobase, naming the module and step, or while the database is ahead of this Protobase by a migration that is not additive. Each migration records itself there; `auth_migrations` stays the steps' own record, which each step's file reads to skip a step the database has. The examples' `db:migrate` applies all pending files in one transaction, so a migration that fails leaves the database as the running version expects it. The host must guarantee the rest: nothing but the migrations writes while they run, and the new version serves only after they succeeded. Only [`protobase dev`](cli.md#dev), on the developer's machine, compares the store's tables with what the app's Better Auth needs, and warns at startup about each table, column or index that drifted, such as one changed by hand.
|
|
44
44
|
|
|
45
45
|
No resource may be over a table of the store, which holds password hashes, sessions, tokens and signing keys: `protobase serve` and `protobase dev` refuse to start with one, naming it, whatever the table is called, and [`protobase scaffold`](cli.md#scaffold) never writes one. The API, the Supabase-compatible endpoints, live updates and MCP read the app's resources only, so none of them reads the store.
|
|
46
46
|
|