@protobase/cli 0.128.0 → 0.129.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/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 +4 -2
- package/dist/migration/release/apply-release-steps.js +6 -5
- package/dist/migration/release/release-record.js +30 -0
- package/dist/migration/snapshot/check.js +1 -1
- 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 +2 -2
- package/dist/migration/snapshot/run-migration.js +3 -2
- package/dist/migration/snapshot/snapshot-file.js +4 -3
- package/dist/migration/snapshot/write-file.js +19 -3
- 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 +3 -2
- 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 +7 -7
|
@@ -18,5 +18,7 @@ const authMigrationTitle = "The auth schema changes this version of Protobase ne
|
|
|
18
18
|
const migrationText = (sql, writer = "protobase auth migration") => `-- ${authMigrationTitle}, written by \`${writer}\`.\n-- Applied with the project's other migrations; edit or remove statements the project handles differently.\n\n${sql}\n`;
|
|
19
19
|
/** The text of the file that starts the snapshot of a project whose store is current already: no statements. */
|
|
20
20
|
const currentStoreText = (writer = "protobase auth migration") => `-- ${authMigrationTitle}, written by \`${writer}\`: none, the store has every step of this version already.\n-- It starts protobase.snapshot.json from the project's earlier migrations.\n`;
|
|
21
|
+
/** The text of the file that only records a store that is current already in the database's record of migrations. */
|
|
22
|
+
const recordOnlyText = (writer = "protobase auth migration") => `-- ${authMigrationTitle}, written by \`${writer}\`: none, the store has every step of this version already.\n-- It records the store in the database's record of migrations, which the server reads at startup.\n`;
|
|
21
23
|
//#endregion
|
|
22
|
-
export { authMigrationTitle, currentStoreText, migrationText, nextMigrationName };
|
|
24
|
+
export { authMigrationTitle, currentStoreText, migrationText, nextMigrationName, recordOnlyText };
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { protobaseVersion } from "../version/version.js";
|
|
2
2
|
import { readSnapshot } from "../migration/snapshot/snapshot-file.js";
|
|
3
|
+
import { authRefusals, customHint } from "../migration/snapshot/auth-difference.js";
|
|
3
4
|
import { readMigrationFiles } from "../migration/snapshot/migration-files.js";
|
|
4
5
|
import { refuseInconsistent } from "../migration/snapshot/consistency.js";
|
|
5
|
-
import { currentStoreText, migrationText } from "./migration-file.js";
|
|
6
|
+
import { currentStoreText, migrationText, recordOnlyText } from "./migration-file.js";
|
|
6
7
|
import { writeMigrationFile } from "../migration/snapshot/write-file.js";
|
|
7
8
|
import { randomUUID } from "node:crypto";
|
|
8
9
|
import { authSchemaMigration } from "@protobase/server";
|
|
9
|
-
import { latestSteps, storeModel, storeNames } from "@protobase/server/internal";
|
|
10
|
+
import { latestSteps, recordsRuntimeModel, storeModel, storeNames } from "@protobase/server/internal";
|
|
10
11
|
//#region src/auth/write-migration.ts
|
|
11
12
|
/**
|
|
12
13
|
* Writes the auth schema changes the database still needs as the next migration in `dir`, and returns its path;
|
|
@@ -14,23 +15,32 @@ import { latestSteps, storeModel, storeNames } from "@protobase/server/internal"
|
|
|
14
15
|
* needs, so the project's earlier migrations must be applied to it first. The file brings the store to every step of
|
|
15
16
|
* this version, so the project's snapshot, started here when it has none, ends at it with the store there, and
|
|
16
17
|
* `protobase migration` goes on from it. A project without a snapshot whose store is current, such as one whose auth
|
|
17
|
-
* migrations came before the snapshot, gets a file without statements that starts it
|
|
18
|
+
* migrations came before the snapshot, gets a file without statements that starts it; one whose store is current but
|
|
19
|
+
* not in the database's record of migrations, as before the record, a file that only records it.
|
|
18
20
|
*/
|
|
19
21
|
const writeAuthMigration = async ({ auth, projectDir, dir, name, writer }) => {
|
|
20
22
|
const snapshot = await readSnapshot(projectDir);
|
|
21
23
|
refuseInconsistent(snapshot, await readMigrationFiles(dir));
|
|
22
24
|
const sql = await authSchemaMigration(auth);
|
|
23
|
-
|
|
25
|
+
const unrecorded = sql === void 0 && !await recordsRuntimeModel(auth);
|
|
26
|
+
if (sql === void 0 && snapshot && !unrecorded) return;
|
|
24
27
|
const names = storeNames(auth);
|
|
28
|
+
const refusals = authRefusals(snapshot, {
|
|
29
|
+
names,
|
|
30
|
+
organizationsOn: Boolean(auth.organizations)
|
|
31
|
+
});
|
|
32
|
+
if (refusals.length > 0) throw new Error(`${refusals.join("; ")}. ${customHint}`);
|
|
25
33
|
const draft = {
|
|
26
34
|
previous: snapshot,
|
|
27
35
|
auth: storeModel(names, latestSteps(names.names.modules)),
|
|
28
36
|
organizationsOn: Boolean(auth.organizations),
|
|
29
37
|
protobaseVersion
|
|
30
38
|
};
|
|
39
|
+
const body = sql !== void 0 ? migrationText(sql, writer) : snapshot ? recordOnlyText(writer) : currentStoreText(writer);
|
|
31
40
|
return writeMigrationFile(projectDir, dir, {
|
|
32
41
|
name,
|
|
33
|
-
body
|
|
42
|
+
body,
|
|
43
|
+
additive: true
|
|
34
44
|
}, draft, randomUUID());
|
|
35
45
|
};
|
|
36
46
|
//#endregion
|
package/dist/cli/package.js
CHANGED
package/dist/dev/entry.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { protobaseVersion } from "../version/version.js";
|
|
1
2
|
import { projectResources } from "../config/project-parts.js";
|
|
2
3
|
import { buildProject } from "../config/build-project.js";
|
|
3
4
|
import { projectIcons } from "../build/app-icons.js";
|
|
@@ -10,7 +11,7 @@ import { devRealtimePrune } from "./dev-prune.js";
|
|
|
10
11
|
import { devDatabase, loadDevConfig } from "./project.js";
|
|
11
12
|
import { withDevServiceWorker } from "./service-worker-route.js";
|
|
12
13
|
import { setMissing, supabaseEnv } from "./supabase-env.js";
|
|
13
|
-
import { apiKeySettings, assistantSettings, authSchemaDrift, authStoreTables, checkAi,
|
|
14
|
+
import { apiKeySettings, assistantSettings, authSchemaDrift, authStoreTables, checkAi, checkCalls, checkChanges, checkChannelSends, checkComments, checkComputed, checkDerived, checkMigrationRecord, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkStatusSchema, checkUserTablesSchema, checkWebhooksSchema, checkWorkflowsSchema, configExports, hasUsers, relayed, sqlSends } from "@protobase/server";
|
|
14
15
|
import { upgradeWebSocket } from "@hono/node-server";
|
|
15
16
|
import { Hono } from "hono";
|
|
16
17
|
//#region src/dev/entry.ts
|
|
@@ -27,9 +28,9 @@ const { db } = database;
|
|
|
27
28
|
const project = await buildProject(config, database);
|
|
28
29
|
const { resources, views } = configExports(project.config);
|
|
29
30
|
const store = globalThis;
|
|
30
|
-
if (
|
|
31
|
-
await
|
|
32
|
-
store.
|
|
31
|
+
if (!store.__protobaseRecordChecked) {
|
|
32
|
+
await checkMigrationRecord(project.auth, protobaseVersion);
|
|
33
|
+
store.__protobaseRecordChecked = true;
|
|
33
34
|
}
|
|
34
35
|
if (project.auth) await checkResourcesOutsideAuthStore(db, resources.map((resource) => resource.toModel()), project.auth);
|
|
35
36
|
await checkChanges(db, resources.map((resource) => resource.toModel()), project.events);
|
|
@@ -1,34 +1,105 @@
|
|
|
1
1
|
import { adoptPublicRecord } from "./adopt-public-record.js";
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
2
|
+
import { fillRow } from "./record/fill-row.js";
|
|
3
|
+
import { readMigrationDir } from "./record/migration-dir.js";
|
|
4
|
+
import { pendingIn, unfinishedIds } from "./record/pending.js";
|
|
5
|
+
import { runAfter } from "./record/run-after.js";
|
|
4
6
|
//#region src/migration/apply-migrations.ts
|
|
5
7
|
const lockKey = 7311946202;
|
|
6
8
|
const executeFile = "do $migration$ begin execute current_setting('migrations.file'); end $migration$";
|
|
9
|
+
/** What refuses a second run: waiting on the lock instead would deadlock with an index the first builds concurrently. */
|
|
10
|
+
const lockTaken = "Another run of `migrate` is applying migrations to this database: run it again once that one has ended";
|
|
11
|
+
/** The pending migrations in batches, each ending at one with an `.after.sql`, which runs once its batch commits. */
|
|
12
|
+
const batches = (pending) => {
|
|
13
|
+
const all = [[]];
|
|
14
|
+
for (const migration of pending) {
|
|
15
|
+
all.at(-1).push(migration);
|
|
16
|
+
if (migration.after) all.push([]);
|
|
17
|
+
}
|
|
18
|
+
return all.filter((batch) => batch.length > 0);
|
|
19
|
+
};
|
|
20
|
+
const connectionLostCodes = [
|
|
21
|
+
"57P01",
|
|
22
|
+
"57P02",
|
|
23
|
+
"57P03",
|
|
24
|
+
"CONNECTION_CLOSED",
|
|
25
|
+
"CONNECTION_DESTROYED",
|
|
26
|
+
"CONNECTION_ENDED",
|
|
27
|
+
"ECONNRESET",
|
|
28
|
+
"EPIPE"
|
|
29
|
+
];
|
|
30
|
+
const connectionLost = (error) => connectionLostCodes.includes(error.code ?? "");
|
|
31
|
+
const transaction = async (sql, run) => {
|
|
32
|
+
await sql`begin`;
|
|
33
|
+
const result = await run().catch(async (error) => {
|
|
34
|
+
if (!connectionLost(error)) await sql`rollback`;
|
|
35
|
+
throw error;
|
|
36
|
+
});
|
|
37
|
+
await sql`commit`;
|
|
38
|
+
return result;
|
|
39
|
+
};
|
|
40
|
+
const applyBatch = (tx, batch, out) => transaction(tx, async () => {
|
|
41
|
+
for (const migration of batch) {
|
|
42
|
+
out(`applying ${migration.file}\n`);
|
|
43
|
+
await tx`select set_config('migrations.file', ${migration.text}, true)`;
|
|
44
|
+
await tx.unsafe(executeFile);
|
|
45
|
+
await tx`insert into migrations.applied (name) values (${migration.file}) on conflict (name) do nothing`;
|
|
46
|
+
await fillRow(tx, migration);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
const finishUnfinished = async (sql, ids, migrations, out) => {
|
|
50
|
+
for (const id of ids) {
|
|
51
|
+
const migration = migrations.find((candidate) => candidate.id === id);
|
|
52
|
+
if (!migration?.after) throw new Error(`The record of migrations has ${id} unfinished, and no migration of the folder with that id has an .after.sql to finish it`);
|
|
53
|
+
out(`finishing ${migration.after.file}\n`);
|
|
54
|
+
await runAfter(sql, id, migration.after.text);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const apply = async (session, migrations, out) => {
|
|
58
|
+
const { pending, unfinished } = await transaction(session, async () => {
|
|
59
|
+
const [record] = await session`select to_regclass('migrations.applied') is null as fresh`;
|
|
60
|
+
await session`create schema if not exists migrations`;
|
|
61
|
+
await session`create table if not exists migrations.applied (name text primary key, applied_at timestamptz not null default now())`;
|
|
62
|
+
if (record.fresh) await adoptPublicRecord(session);
|
|
63
|
+
return {
|
|
64
|
+
pending: await pendingIn(session, migrations),
|
|
65
|
+
unfinished: await unfinishedIds(session)
|
|
66
|
+
};
|
|
67
|
+
});
|
|
68
|
+
await finishUnfinished(session, unfinished, migrations, out);
|
|
69
|
+
for (const batch of batches(pending)) {
|
|
70
|
+
await applyBatch(session, batch, out);
|
|
71
|
+
const last = batch.at(-1);
|
|
72
|
+
if (!last.after) continue;
|
|
73
|
+
out(`running ${last.after.file}\n`);
|
|
74
|
+
await runAfter(session, last.id, last.after.text);
|
|
75
|
+
}
|
|
76
|
+
out(pending.length > 0 ? `applied ${pending.length} migrations\n` : "the database is up to date\n");
|
|
77
|
+
return pending.map(({ file }) => file);
|
|
78
|
+
};
|
|
7
79
|
/**
|
|
8
|
-
* Applies the `*.sql` files of `dir`
|
|
9
|
-
*
|
|
10
|
-
*
|
|
80
|
+
* Applies the `*.sql` files of `dir` the database has not applied (`pendingIn`), in file name order, behind an
|
|
81
|
+
* advisory lock it only tries, refusing while another run holds it. They apply in batches, one transaction each, so
|
|
82
|
+
* when a file fails none of its batch is applied: a batch ends at a file with an `.after.sql`, whose statements then
|
|
83
|
+
* run outside a transaction before the next batch, and set its row's `completed_at`. A migration a stopped run left
|
|
84
|
+
* unfinished is finished first. The lock is released at the end, or with the connection when that is lost. Run it
|
|
85
|
+
* before a new version serves, while nothing else writes. Returns the names it applied.
|
|
11
86
|
*/
|
|
12
87
|
const applyMigrations = async (sql, dir, out) => {
|
|
13
|
-
const
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
const [
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
return pending;
|
|
29
|
-
});
|
|
30
|
-
out(applied.length > 0 ? `applied ${applied.length} migrations\n` : "the database is up to date\n");
|
|
31
|
-
return applied;
|
|
88
|
+
const migrations = await readMigrationDir(dir);
|
|
89
|
+
const session = await sql.reserve();
|
|
90
|
+
try {
|
|
91
|
+
const [lock] = await session`select pg_try_advisory_lock(${lockKey}) as locked`;
|
|
92
|
+
if (!lock.locked) throw new Error(lockTaken);
|
|
93
|
+
const unlock = () => session`select pg_advisory_unlock(${lockKey})`;
|
|
94
|
+
const applied = await apply(session, migrations, out).catch(async (error) => {
|
|
95
|
+
if (!connectionLost(error)) await unlock();
|
|
96
|
+
throw error;
|
|
97
|
+
});
|
|
98
|
+
await unlock();
|
|
99
|
+
return applied;
|
|
100
|
+
} finally {
|
|
101
|
+
session.release();
|
|
102
|
+
}
|
|
32
103
|
};
|
|
33
104
|
//#endregion
|
|
34
|
-
export { applyMigrations, executeFile, lockKey };
|
|
105
|
+
export { applyMigrations, executeFile, lockKey, lockTaken };
|
|
@@ -1,31 +1,33 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
1
|
+
import { readMigrationDir } from "./record/migration-dir.js";
|
|
2
|
+
import { pendingIn, unfinishedIds } from "./record/pending.js";
|
|
3
3
|
//#region src/migration/plan-migrations.ts
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
4
|
+
/** The migrations of `dir` the database has not applied, and the ids of those whose `.after.sql` has not finished, read-only. */
|
|
5
|
+
const pendingMigrations = async (sql, dir) => {
|
|
6
|
+
const migrations = await readMigrationDir(dir);
|
|
7
|
+
return sql.begin("read only", async (tx) => ({
|
|
8
|
+
migrations,
|
|
9
|
+
pending: await pendingIn(tx, migrations),
|
|
10
|
+
unfinished: await unfinishedIds(tx)
|
|
11
|
+
}));
|
|
11
12
|
};
|
|
12
|
-
/** The `*.sql` files of `dir` the database has not recorded as applied, in their order, read in the transaction `tx`. */
|
|
13
|
-
const pendingIn = async (tx, dir) => {
|
|
14
|
-
const files = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
|
|
15
|
-
const done = new Set(await appliedNames(tx));
|
|
16
|
-
return files.filter((file) => !done.has(file));
|
|
17
|
-
};
|
|
18
|
-
/** `pendingIn`, from a read-only transaction of its own. */
|
|
19
|
-
const pendingMigrations = (sql, dir) => sql.begin("read only", (tx) => pendingIn(tx, dir));
|
|
20
13
|
/**
|
|
21
|
-
* `protobase migrate --plan`: prints each
|
|
22
|
-
* name, with its SQL
|
|
14
|
+
* `protobase migrate --plan`: prints each `.after.sql` a stopped run left unfinished, then each migration of `dir` that
|
|
15
|
+
* `migrate` would apply, in its order, under its name, with its SQL and its `.after.sql`: it applies and records
|
|
16
|
+
* nothing. Returns the names it would apply.
|
|
23
17
|
*/
|
|
24
18
|
const planMigrations = async (sql, dir, out) => {
|
|
25
|
-
const pending = await pendingMigrations(sql, dir);
|
|
26
|
-
for (const
|
|
27
|
-
|
|
28
|
-
|
|
19
|
+
const { migrations, pending, unfinished } = await pendingMigrations(sql, dir);
|
|
20
|
+
for (const id of unfinished) {
|
|
21
|
+
const after = migrations.find((migration) => migration.id === id)?.after;
|
|
22
|
+
out(after ? `-- ${after.file}, to finish\n${after.text.trimEnd()}\n\n` : `-- ${id} is unfinished, and no migration of the folder finishes it\n\n`);
|
|
23
|
+
}
|
|
24
|
+
for (const { file, text, after } of pending) {
|
|
25
|
+
out(`-- ${file}\n${text.trimEnd()}\n\n`);
|
|
26
|
+
if (after) out(`-- ${after.file}, outside a transaction once ${file} commits\n${after.text.trimEnd()}\n\n`);
|
|
27
|
+
}
|
|
28
|
+
const finishing = unfinished.length > 0 ? `${unfinished.length} to finish; ` : "";
|
|
29
|
+
out(pending.length > 0 || unfinished.length > 0 ? `${finishing}${pending.length} migrations to apply; nothing was applied\n` : "the database is up to date\n");
|
|
30
|
+
return pending.map(({ file }) => file);
|
|
29
31
|
};
|
|
30
32
|
//#endregion
|
|
31
|
-
export {
|
|
33
|
+
export { planMigrations };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//#region src/migration/record/after-file.ts
|
|
2
|
+
/** The `.after.sql` beside the migration `file`. */
|
|
3
|
+
const afterFileOf = (file) => file.replace(/\.sql$/, ".after.sql");
|
|
4
|
+
const isAfterFile = (file) => file.endsWith(".after.sql");
|
|
5
|
+
/** Its statements: each ends with a semicolon at the end of a line. Comment lines between them are dropped. */
|
|
6
|
+
const afterStatements = (text) => text.replaceAll("\r\n", "\n").split(/;[ \t]*(?:\n|$)/).map((statement) => statement.split("\n").filter((line) => !/^\s*--/.test(line)).join("\n").trim()).filter((statement) => statement !== "");
|
|
7
|
+
const identifier = "(?:\"(?:[^\"]|\"\")+\"|[A-Za-z_][\\w$]*)";
|
|
8
|
+
const createIndex = new RegExp(`^create\\s+(unique\\s+)?index\\s+concurrently\\s+(?:if\\s+not\\s+exists\\s+)?(${identifier})\\s+on\\s+(?:only\\s+)?(${identifier}(?:\\.${identifier})?)`, "i");
|
|
9
|
+
/** The index a statement builds concurrently, as Postgres names it; `undefined` for any other statement. */
|
|
10
|
+
const builtIndex = (statement) => {
|
|
11
|
+
const found = createIndex.exec(statement);
|
|
12
|
+
if (!found) return;
|
|
13
|
+
const name = found[2];
|
|
14
|
+
return {
|
|
15
|
+
index: name.startsWith("\"") ? name.slice(1, -1).replaceAll("\"\"", "\"") : name.toLowerCase(),
|
|
16
|
+
unique: Boolean(found[1])
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
/** The table a statement builds an index on concurrently, as the statement names it; `undefined` for any other statement. */
|
|
20
|
+
const indexedTable = (statement) => createIndex.exec(statement)?.[3];
|
|
21
|
+
//#endregion
|
|
22
|
+
export { afterFileOf, afterStatements, builtIndex, indexedTable, isAfterFile };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { afterStatements, builtIndex } from "./after-file.js";
|
|
2
|
+
import { parseHeader } from "../snapshot/header.js";
|
|
3
|
+
import { sqlHash } from "./record-block.js";
|
|
4
|
+
import { recordTable } from "@protobase/server/internal";
|
|
5
|
+
//#region src/migration/record/fill-row.ts
|
|
6
|
+
/**
|
|
7
|
+
* Fills what the row a migration just inserted left unknown from its finished text, in the transaction that applied
|
|
8
|
+
* it: the hash and whether it is additive (its header's `-- protobase:additive`), as for a file filled by hand. With an
|
|
9
|
+
* `.after.sql`, the indexes that builds, and the row is not complete until it has run.
|
|
10
|
+
*/
|
|
11
|
+
const fillRow = async (tx, { id, text, after }) => {
|
|
12
|
+
if (!id) return;
|
|
13
|
+
const indexes = after && afterStatements(after.text).map(builtIndex).filter((index) => index !== void 0);
|
|
14
|
+
await tx.unsafe(`update ${recordTable} set sql_hash = coalesce(sql_hash, $2), additive = coalesce(additive, $3),
|
|
15
|
+
physical = case when $4::text::jsonb is null then physical else jsonb_set(physical, '{after}', $4::text::jsonb) end,
|
|
16
|
+
completed_at = case when $4::text::jsonb is null then completed_at end
|
|
17
|
+
where id = $1`, [
|
|
18
|
+
id,
|
|
19
|
+
sqlHash(text),
|
|
20
|
+
parseHeader(text)?.additive ?? false,
|
|
21
|
+
indexes ? JSON.stringify(indexes) : null
|
|
22
|
+
]);
|
|
23
|
+
};
|
|
24
|
+
//#endregion
|
|
25
|
+
export { fillRow };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { afterFileOf, isAfterFile } from "./after-file.js";
|
|
2
|
+
import { recordId } from "./record-block.js";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
6
|
+
//#region src/migration/record/migration-dir.ts
|
|
7
|
+
/**
|
|
8
|
+
* The `*.sql` migrations of `dir` in file name order, each with its `.after.sql`. Refuses an `.after.sql` beside no
|
|
9
|
+
* migration, or beside one without a record block, which has no row to mark complete.
|
|
10
|
+
*/
|
|
11
|
+
const readMigrationDir = async (dir) => {
|
|
12
|
+
const names = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
|
|
13
|
+
const migrations = await Promise.all(names.filter((file) => !isAfterFile(file)).map(async (file) => {
|
|
14
|
+
const text = await readFile(path.join(dir, file), "utf8");
|
|
15
|
+
const afterFile = afterFileOf(file);
|
|
16
|
+
const after = existsSync(path.join(dir, afterFile)) ? {
|
|
17
|
+
file: afterFile,
|
|
18
|
+
text: await readFile(path.join(dir, afterFile), "utf8")
|
|
19
|
+
} : void 0;
|
|
20
|
+
return {
|
|
21
|
+
file,
|
|
22
|
+
text,
|
|
23
|
+
id: recordId(text),
|
|
24
|
+
after
|
|
25
|
+
};
|
|
26
|
+
}));
|
|
27
|
+
const orphan = names.filter(isAfterFile).find((file) => !migrations.some(({ after }) => after?.file === file));
|
|
28
|
+
if (orphan) throw new Error(`${orphan} is beside no migration of the same name`);
|
|
29
|
+
const unrecorded = migrations.find(({ after, id }) => after && !id);
|
|
30
|
+
if (unrecorded) throw new Error(`${unrecorded.after.file} is beside ${unrecorded.file}, which has no record block to mark complete: write it with \`protobase migration --custom <name> --after\``);
|
|
31
|
+
return migrations;
|
|
32
|
+
};
|
|
33
|
+
//#endregion
|
|
34
|
+
export { readMigrationDir };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { recordTable } from "@protobase/server/internal";
|
|
2
|
+
//#region src/migration/record/pending.ts
|
|
3
|
+
const appliedNames = async (tx) => {
|
|
4
|
+
const [record] = await tx`
|
|
5
|
+
select to_regclass('migrations.applied') is not null as applied,
|
|
6
|
+
(select count(*) = 2 from information_schema.columns where table_schema = 'public' and table_name = 'schema_migrations' and column_name in ('name', 'applied_at')) as earlier`;
|
|
7
|
+
if (record.applied) return (await tx`select name from migrations.applied`).map((row) => row.name);
|
|
8
|
+
if (record.earlier) return (await tx`select name from public.schema_migrations`).map((row) => row.name);
|
|
9
|
+
return [];
|
|
10
|
+
};
|
|
11
|
+
/** The ids the record of migrations holds: those its files inserted, whichever runner applied them. */
|
|
12
|
+
const recordedIds = async (tx) => {
|
|
13
|
+
const [found] = await tx`select to_regclass(${recordTable}) is not null as found`;
|
|
14
|
+
if (!found.found) return /* @__PURE__ */ new Set();
|
|
15
|
+
const [row] = await tx.unsafe(`select json_agg(id) as names from ${recordTable}`);
|
|
16
|
+
return new Set(row.names ?? []);
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* The migrations the database has not applied, in their order, read in the transaction `tx`: neither recorded by name
|
|
20
|
+
* in `migrations.applied` nor, by the id of its record block, in the record of migrations, so a file another runner
|
|
21
|
+
* applied, or one renamed since, is not applied twice.
|
|
22
|
+
*/
|
|
23
|
+
const pendingIn = async (tx, migrations) => {
|
|
24
|
+
const names = new Set(await appliedNames(tx));
|
|
25
|
+
const ids = await recordedIds(tx);
|
|
26
|
+
return migrations.filter(({ file, id }) => !names.has(file) && !(id && ids.has(id)));
|
|
27
|
+
};
|
|
28
|
+
/** The rows of the record whose `.after.sql` has not finished, by id, in the order they were applied. */
|
|
29
|
+
const unfinishedIds = async (tx) => {
|
|
30
|
+
const [found] = await tx`select to_regclass(${recordTable}) is not null as found`;
|
|
31
|
+
if (!found.found) return [];
|
|
32
|
+
const [row] = await tx.unsafe(`select json_agg(id order by applied_at) as names from ${recordTable} where completed_at is null`);
|
|
33
|
+
return row.names ?? [];
|
|
34
|
+
};
|
|
35
|
+
//#endregion
|
|
36
|
+
export { pendingIn, recordedIds, unfinishedIds };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { recordTable, recordTableSql } from "@protobase/server/internal";
|
|
3
|
+
//#region src/migration/record/record-block.ts
|
|
4
|
+
/** The line the record block starts with, followed by the file's id. */
|
|
5
|
+
const recordMarker = "-- protobase:record";
|
|
6
|
+
const literal = (value) => {
|
|
7
|
+
if (value === null) return "null";
|
|
8
|
+
if (typeof value !== "string") return String(value);
|
|
9
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
10
|
+
};
|
|
11
|
+
/** The text before the file's record block, which its hash covers. */
|
|
12
|
+
const textBeforeRecord = (text) => {
|
|
13
|
+
const at = text.search(new RegExp(`^${recordMarker} `, "m"));
|
|
14
|
+
return at === -1 ? text : text.slice(0, at);
|
|
15
|
+
};
|
|
16
|
+
/** The SHA-256 of a file's text without its record block, with CRLF line endings read as LF. */
|
|
17
|
+
const sqlHash = (text) => createHash("sha256").update(textBeforeRecord(text).replaceAll("\r\n", "\n")).digest("hex");
|
|
18
|
+
/** The id in a file's record block; `undefined` when it has none. */
|
|
19
|
+
const recordId = (text) => new RegExp(`^${recordMarker} (\\S+)$`, "m").exec(text)?.[1];
|
|
20
|
+
/** The record block of the file whose text before it hashes to `hash`; `null` when that text is still to be written by hand. */
|
|
21
|
+
const recordBlock = (row, hash) => {
|
|
22
|
+
const columns = "id, number, name, protobase_version, model, model_hash, physical, additive, sql_hash, completed_at";
|
|
23
|
+
const values = [
|
|
24
|
+
literal(row.id),
|
|
25
|
+
literal(row.number),
|
|
26
|
+
literal(row.name),
|
|
27
|
+
literal(row.protobaseVersion),
|
|
28
|
+
`${literal(JSON.stringify(row.model))}::jsonb`,
|
|
29
|
+
literal(row.modelHash),
|
|
30
|
+
`${literal(JSON.stringify(row.physical))}::jsonb`,
|
|
31
|
+
literal(row.additive),
|
|
32
|
+
literal(hash),
|
|
33
|
+
row.completed ? "clock_timestamp()" : "null"
|
|
34
|
+
].join(", ");
|
|
35
|
+
return `${recordMarker} ${row.id}\n-- The row that records this migration as applied, which the server reads at startup.\n${recordTableSql}\ninsert into ${recordTable} (${columns}) values (${values});\n`;
|
|
36
|
+
};
|
|
37
|
+
//#endregion
|
|
38
|
+
export { recordBlock, recordId, recordMarker, sqlHash, textBeforeRecord };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { afterStatements, builtIndex, indexedTable } from "./after-file.js";
|
|
2
|
+
import { recordTable } from "@protobase/server/internal";
|
|
3
|
+
//#region src/migration/record/run-after.ts
|
|
4
|
+
/**
|
|
5
|
+
* Runs a migration's `.after.sql` on `sql`'s connection, outside a transaction, one statement at a time, then marks
|
|
6
|
+
* its row in the record complete. An index a statement builds that an earlier run left invalid on the statement's
|
|
7
|
+
* table, as when it was stopped, is dropped first, so it is built again rather than kept half made.
|
|
8
|
+
*/
|
|
9
|
+
const runAfter = async (sql, id, text) => {
|
|
10
|
+
for (const statement of afterStatements(text)) {
|
|
11
|
+
const index = builtIndex(statement);
|
|
12
|
+
if (index) {
|
|
13
|
+
const invalid = await sql`
|
|
14
|
+
select n.nspname as schema from pg_index i join pg_class c on c.oid = i.indexrelid join pg_namespace n on n.oid = c.relnamespace
|
|
15
|
+
where c.relname = ${index.index} and not i.indisvalid and i.indrelid = to_regclass(${indexedTable(statement)})`;
|
|
16
|
+
for (const { schema } of invalid) await sql`drop index concurrently ${sql(schema)}.${sql(index.index)}`;
|
|
17
|
+
}
|
|
18
|
+
await sql.unsafe(statement);
|
|
19
|
+
}
|
|
20
|
+
await sql.unsafe(`update ${recordTable} set completed_at = clock_timestamp() where id = $1`, [id]);
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
export { runAfter };
|
|
@@ -25,8 +25,9 @@ const registerMigration = (program) => {
|
|
|
25
25
|
const { migrateProject } = await import("./migrate-project.js");
|
|
26
26
|
await migrateProject(process.cwd(), () => resolveConnectionUrl(connection, opts.env), out, Boolean(opts.plan));
|
|
27
27
|
});
|
|
28
|
-
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")).action(async (opts) => {
|
|
28
|
+
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")).action(async (opts) => {
|
|
29
29
|
if (opts.recordConfig && !opts.custom) throw new Error("--record-config goes with --custom <name>");
|
|
30
|
+
if (opts.after && !opts.custom) throw new Error("--after goes with --custom <name>");
|
|
30
31
|
const { config, auth } = await loadAuthTarget(opts);
|
|
31
32
|
const dir = path.resolve(opts.dir);
|
|
32
33
|
if (opts.custom) {
|
|
@@ -36,11 +37,12 @@ const registerMigration = (program) => {
|
|
|
36
37
|
dir,
|
|
37
38
|
name: opts.custom,
|
|
38
39
|
recordConfig: Boolean(opts.recordConfig),
|
|
40
|
+
after: Boolean(opts.after),
|
|
39
41
|
auth,
|
|
40
42
|
protobaseVersion,
|
|
41
43
|
newId: randomUUID
|
|
42
44
|
});
|
|
43
|
-
out(`wrote ${path.relative(process.cwd(), file)} and protobase.snapshot.json: write its statements\n`);
|
|
45
|
+
out(`wrote ${path.relative(process.cwd(), file)}${opts.after ? ", its .after.sql" : ""} and protobase.snapshot.json: write its statements\n`);
|
|
44
46
|
return;
|
|
45
47
|
}
|
|
46
48
|
const [{ migrationProject }, { migrationParts }, { runMigration }, { migrationSummary }] = await Promise.all([
|
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { executeFile, lockKey } from "../apply-migrations.js";
|
|
1
|
+
import { executeFile, lockKey, lockTaken } from "../apply-migrations.js";
|
|
2
2
|
//#region src/migration/release/apply-release-steps.ts
|
|
3
3
|
/**
|
|
4
|
-
* Applies the steps `find` gives in one transaction, behind the lock `migrate` takes,
|
|
5
|
-
* none commits early: when one fails, such as a check that refuses the rows
|
|
6
|
-
* once the lock is held, so
|
|
4
|
+
* Applies the steps `find` gives in one transaction, behind the lock `migrate` takes, refusing while another run holds
|
|
5
|
+
* it, each as `migrate` runs a file, so none commits early: when one fails, such as a check that refuses the rows
|
|
6
|
+
* already there, none is applied. `find` runs once the lock is held, so it finds the steps from what is committed.
|
|
7
7
|
*/
|
|
8
8
|
const applyReleaseSteps = async (sql, find, out) => {
|
|
9
9
|
const applied = await sql.begin(async (tx) => {
|
|
10
|
-
await tx`select
|
|
10
|
+
const [lock] = await tx`select pg_try_advisory_xact_lock(${lockKey}) as locked`;
|
|
11
|
+
if (!lock.locked) throw new Error(lockTaken);
|
|
11
12
|
const steps = await find(tx);
|
|
12
13
|
for (const step of steps) {
|
|
13
14
|
out(`applying ${step.name}\n`);
|
|
@@ -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 };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { readSnapshot, snapshotFile } from "./snapshot-file.js";
|
|
2
|
+
import { authRefusals, lastStepsOf } 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
7
|
import { offlineStepsMigration } from "@protobase/server/internal";
|
|
8
8
|
//#region src/migration/snapshot/check.ts
|
|
@@ -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,4 +1,4 @@
|
|
|
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
|
|
@@ -9,7 +9,7 @@ const nextSnapshot = (previous, auth, organizationsOn, endsAt, protobaseVersion)
|
|
|
9
9
|
format: 1,
|
|
10
10
|
protobaseVersion,
|
|
11
11
|
endsAt,
|
|
12
|
-
modelHash: modelHash(model),
|
|
12
|
+
modelHash: modelHash$1(model),
|
|
13
13
|
model,
|
|
14
14
|
decisions: {
|
|
15
15
|
modules: previous?.decisions.modules ?? {
|
|
@@ -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
|
|
@@ -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,13 +1,15 @@
|
|
|
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 });
|
|
@@ -16,7 +18,21 @@ const writeMigrationFile = async (projectDir, dir, content, draft, id) => {
|
|
|
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.0",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -43,13 +43,13 @@
|
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@better-auth/core": "^1.7.12",
|
|
45
45
|
"@hono/node-server": "^2.1.3",
|
|
46
|
-
"@protobase/config": "0.
|
|
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.0",
|
|
47
|
+
"@protobase/layout": "0.129.0",
|
|
48
|
+
"@protobase/query": "0.129.0",
|
|
49
|
+
"@protobase/schema": "0.129.0",
|
|
50
|
+
"@protobase/server": "0.129.0",
|
|
51
|
+
"@protobase/ui": "0.129.0",
|
|
52
|
+
"@protobase/workflows": "0.129.0",
|
|
53
53
|
"@react-email/render": "^2.1.0",
|
|
54
54
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
55
55
|
"@sentry/vite-plugin": "^11.10.0",
|
|
@@ -10,7 +10,7 @@ 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
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, and `drop` takes the newest file back.
|
|
16
16
|
- [User and organization commands](../reference/cli.md#users): Create users, set roles and manage organizations from the terminal.
|
|
@@ -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
|
|
|
@@ -460,7 +460,7 @@ bun --no-install protobase-serve.js migrate-release <bundle> --plan # print wh
|
|
|
460
460
|
bun --no-install protobase-serve.js migrate-release <bundle> # apply it
|
|
461
461
|
```
|
|
462
462
|
|
|
463
|
-
It loads the bundle's config with the app's settings, as `create-admin` does, and compares every feature the config turns on with the database itself, as [`migration`](#migration) does with `DATABASE_URL` set: the sign-in tables by the versions their `auth_migrations` table records, the jobs, change capture, workflows, notifications and the other built-in schemas by what the database has. It applies what differs in one transaction, behind the lock `migrate` takes, prints each part it applies, such as `applying auth`, or that the database is up to date, so a second run applies nothing. A step whose check refuses the rows already there, such as two From addresses one person entered with different case, stops it with the step's message and exit code 1, and nothing is applied. It refuses a database that lacks any of the bundle's own migrations, since the steps are compared with what they made.
|
|
463
|
+
It loads the bundle's config with the app's settings, as `create-admin` does, and compares every feature the config turns on with the database itself, as [`migration`](#migration) does with `DATABASE_URL` set: the sign-in tables by the versions their `auth_migrations` table records, the jobs, change capture, workflows, notifications and the other built-in schemas by what the database has. It applies what differs in one transaction, then the row that records the release in `migrations.history`, which the server reads at startup, behind the lock `migrate` takes, stopping at once while another run holds it, prints each part it applies, such as `applying auth`, or that the database is up to date, so a second run applies nothing. A step whose check refuses the rows already there, such as two From addresses one person entered with different case, stops it with the step's message and exit code 1, and nothing is applied. It refuses a database that lacks any of the bundle's own migrations, since the steps are compared with what they made.
|
|
464
464
|
|
|
465
465
|
`--plan` applies nothing and prints the same statements as one SQL script, each part under a comment, ending with `-- N steps to apply; nothing was applied`. The script records the sign-in versions it applies itself, so a host can run it in a transaction of its own, such as one it rolls back to try it first, or one it commits while nothing else writes.
|
|
466
466
|
|
|
@@ -652,7 +652,7 @@ For a project with [organizations](auth.md#organizations); `<organization>` is a
|
|
|
652
652
|
protobase migrate [connection string | --env VAR] [--plan]
|
|
653
653
|
```
|
|
654
654
|
|
|
655
|
-
Applies the project's `db/migrations/*.sql` that the database has not applied yet, in file name order, as the runtime's [`migrate`](#build-serve) applies a bundle's:
|
|
655
|
+
Applies the project's `db/migrations/*.sql` that the database has not applied yet, in file name order, as the runtime's [`migrate`](#build-serve) applies a bundle's: behind the same lock, which it only tries, stopping at once while another run holds it, recorded in the same `migrations.applied` and, by each file's own last statement, in `migrations.history` (see [The record of migrations](../guides/deploy.md#the-record-of-migrations)), so a database either one migrated is current for the other. The files apply in batches, each in one transaction, cut after a file with an `.after.sql`, whose statements run outside a transaction before the next batch; a file a stopped run left unfinished is finished first. It prints each file it applies and each `.after.sql` it runs, or that the database is up to date; a project without `db/migrations` applies nothing and says so. It runs none of the project's code, so a project with only `protobase.config.ts`, no `package.json` and nothing installed, migrates as well. The URL comes as for [`scaffold`](#scaffold), and is needed only when there are migrations. A project that still has a `db/migrate.ts` recording in `public.schema_migrations` first copies in the presets' current `db/migrate.ts` and `drop.ts`, so the two keep one record. `--plan` is a dry run: it prints each `.after.sql` left unfinished, then each file not applied yet under its name, with its SQL and its `.after.sql`, from a read-only transaction, and applies and records nothing. <gap>`migrate` cannot report where the tables it touched differ from the record's model, nor refuse a Postgres older than the supported one, because comparing them after applying, and `migration check --database`, are not implemented.</gap>
|
|
656
656
|
|
|
657
657
|
## `migration`
|
|
658
658
|
|
|
@@ -662,19 +662,19 @@ A project with auth migrations written before the snapshot starts it with [`auth
|
|
|
662
662
|
|
|
663
663
|
```sh
|
|
664
664
|
protobase migration [--dir db/migrations] [--extend <dir>]
|
|
665
|
-
protobase migration --custom <name> [--record-config]
|
|
665
|
+
protobase migration --custom <name> [--record-config] [--after]
|
|
666
666
|
protobase migration check
|
|
667
667
|
protobase migration drop
|
|
668
668
|
protobase migration up
|
|
669
669
|
```
|
|
670
670
|
|
|
671
|
-
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, and the hash of the snapshot's model once it is applied. It writes nothing, the snapshot included, when nothing differs. Apply the file with the project's other migrations.
|
|
671
|
+
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, 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)); it counts as additive when it holds only sign-in steps. It writes nothing, the snapshot included, when nothing differs. Apply the file with the project's other migrations.
|
|
672
672
|
|
|
673
|
-
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 `physical`, every schema, table, column and index name the store has. 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 version followed by its row in `auth_migrations
|
|
673
|
+
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 `physical`, every schema, table, column and index name the store has. 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 version followed by its row in `auth_migrations`. Each runs only while `auth_migrations` lacks its version, 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`. <gap>`protobase migration` cannot write the sign-in store of a project with auth migrations from before `protobase.snapshot.json` because `protobase migration baseline`, which reads the database once to start the snapshot, is not implemented.</gap>
|
|
674
674
|
|
|
675
675
|
The rest of the file is what the other features the config enables still need of the database, compared with it, each under its own comment and named in the file name as in brackets: the [jobs schema](jobs.md#the-jobs-schema) when the config has jobs, `webhooks`, `workflows`, `notifications` or `mailFeedback`, or a resource has events, history, comments or an [AI field](ai.md) or is a [time rollup](data-config.md#keeping-it-up-to-date) (`jobs`), the table of the bounces and complaints of [`mailFeedback`](email.md#bounces-and-complaints) (`mail_feedback`), the [capture of events](events.md#migrations-and-startup) and the [history table](history.md#the-table) (`changes`), the columns of [rollup and formula fields](data-config.md#rollups-and-formulas), the triggers that keep the rollups, and the tables, indexes and refresh functions of [time rollups](data-config.md#time-rollups) (`computed`), the role the [assistant's read-only queries](assistant.md#the-built-in-backend) run as, when it finds the built-in assistant's key (`query`), the [comments table](comments.md#the-table) (`comments`), the [webhook subscriptions](webhooks.md#subscriptions-in-the-admin-app) of `webhooks` (`webhooks`), the [workflows, versions, runs and steps](workflows.md#turning-them-on) of `workflows` (`workflows`), the [devices and history tables](notifications.md#table-names) of `notifications` (`notifications`), the table of who unsubscribed from bulk mail of [`unsubscribe`](email.md#unsubscribe) (`unsubscribes`), the `realtime_relay` schema of [`realtime: { processes: 'many' }`](supabase-realtime.md#several-processes) (`realtime_relay`), the `channels` schema of [`realtime: { sqlSends: true }`](channels.md#from-sql) (`channel_sends`), the trigger of [`realtime.relay`](realtime-relay.md#sessions) that ends a deleted session's sockets and `realtime.members` with the triggers that keep it from channel records that list their members, also for an app with sign-in and a live resource whose conversation page has `members` (`relay`), and, with [`userTables`](user-tables.md#the-switch), the schemas of user tables (`user_tables`) and the delete of the definitions of tables that resources in code [own now](user-tables.md#taking-a-table-over-as-code) (`owned_definitions`). Those are compared only with `DATABASE_URL` set, against the database with the project's migrations applied, and the command says so without it. <gap>`protobase migration` cannot write the jobs, change capture, rollup and other feature schemas from the snapshot because recording their models in it is not implemented.</gap> It reads the config merged with those of `--extend` as `dev` merges them, and the `.env` nearest the current directory.
|
|
676
676
|
|
|
677
|
-
- `--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. It counts as not additive; once it only adds, put `-- protobase:additive` among its `-- protobase:` lines and `check` lints it with the lint rules Protobase's own steps pass, such as no dropped table or column, no new required column and no unique constraint without a check of the rows. 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.
|
|
677
|
+
- `--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. It counts as not additive; once it only adds, put `-- protobase:additive` among its `-- protobase:` lines and `check` lints it with the lint rules Protobase's own steps pass, such as no dropped table or column, no new required column and no unique constraint without a check of the rows. 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. 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)).
|
|
678
678
|
- `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, 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`, and a hand-written file marked additive that is not.
|
|
679
679
|
- `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.
|
|
680
680
|
- `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.
|
|
@@ -710,7 +710,7 @@ Prints the app's entry for the apps file of [Realtime](realtime-relay.md), as JS
|
|
|
710
710
|
protobase auth migration [--dir db/migrations] [--name auth]
|
|
711
711
|
```
|
|
712
712
|
|
|
713
|
-
Run inside a project, against its database with the project's migrations applied. It reads the versions the store applied from its `auth_migrations` table and writes the auth migrations of this Protobase it has not, each followed by its row there, as the next migration in `--dir`: `009_auth.sql` after `008_...`, with the store's schema, user table, columns and id type as the config's `auth` names them. Nothing is written when the store is current and the project has a snapshot, nor with sign-in off, when it says so and exits 0. The file only adds, never drops; apply it with the project's other migrations. It starts with Protobase's lines and starts the project's `protobase.snapshot.json`, or moves it on, with the store at every step, so [`migration`](#migration) goes on from it. A project without a snapshot whose store is current, such as one whose auth migrations an earlier Protobase wrote, gets a file without statements that starts it. For a store made before 0.48, without `auth_migrations`, it writes the step that adopts it once, and refuses one that matches no version, naming what differs. See [migrations](auth.md#migrations).
|
|
713
|
+
Run inside a project, against its database with the project's migrations applied. It reads the versions the store applied from its `auth_migrations` table and writes the auth migrations of this Protobase it has not, each followed by its row there, as the next migration in `--dir`: `009_auth.sql` after `008_...`, with the store's schema, user table, columns and id type as the config's `auth` names them. Nothing is written when the store is current and the project has a snapshot, nor with sign-in off, when it says so and exits 0. The file only adds, never drops; apply it with the project's other migrations. It starts with Protobase's lines, ends with the statement that records it in `migrations.history`, and starts the project's `protobase.snapshot.json`, or moves it on, with the store at every step, so [`migration`](#migration) goes on from it. A project without a snapshot whose store is current, such as one whose auth migrations an earlier Protobase wrote, gets a file without statements that starts it, and one whose store is current but not in `migrations.history`, such as one migrated before that record, a file that only records it. For a store made before 0.48, without `auth_migrations`, it writes the step that adopts it once, and refuses one that matches no version, naming what differs. See [migrations](auth.md#migrations).
|
|
714
714
|
|
|
715
715
|
## `import supabase`
|
|
716
716
|
|