@protobase/cli 0.122.1 → 0.123.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/register.js +1 -0
- package/dist/auth/write-migration.js +27 -10
- package/dist/cli/package.js +1 -1
- package/dist/dev/dev-relay.js +1 -1
- package/dist/doctor/startup.js +1 -1
- package/dist/main.js +1 -1
- package/dist/migration/load-project.js +6 -7
- package/dist/migration/migrate-project.js +5 -3
- package/dist/migration/parts.js +5 -8
- package/dist/migration/plan-migrations.js +25 -0
- package/dist/migration/register.js +75 -11
- package/dist/migration/snapshot/auth-difference.js +37 -0
- package/dist/migration/snapshot/auth-target.js +13 -0
- package/dist/migration/snapshot/check.js +26 -0
- package/dist/migration/snapshot/consistency.js +29 -0
- package/dist/migration/snapshot/custom.js +39 -0
- package/dist/migration/snapshot/drop.js +64 -0
- package/dist/migration/snapshot/header.js +34 -0
- package/dist/migration/snapshot/lint-custom.js +23 -0
- package/dist/migration/snapshot/migration-files.js +30 -0
- package/dist/migration/snapshot/next-snapshot.js +40 -0
- package/dist/migration/snapshot/preconditions.js +25 -0
- package/dist/migration/snapshot/run-migration.js +50 -0
- package/dist/migration/snapshot/snapshot-file.js +33 -0
- package/dist/migration/snapshot/up.js +24 -0
- package/dist/migration/snapshot/write-file.js +24 -0
- package/dist/migration/summary.js +6 -6
- package/dist/supabase/dump-phase.js +3 -2
- package/dist/supabase/load-phase.js +5 -0
- package/dist/supabase/project-users.js +4 -3
- package/dist/supabase/storage-copy.js +1 -1
- package/dist/supabase/store-migrations.js +42 -4
- package/dist/users/password.js +1 -1
- package/package.json +9 -8
- package/skills/protobase/references/features/build-and-run.md +2 -1
- package/skills/protobase/references/features/data-model.md +1 -0
- package/skills/protobase/references/features/email-and-public-forms.md +1 -1
- package/skills/protobase/references/reference/api.md +1 -1
- package/skills/protobase/references/reference/auth.md +1 -1
- package/skills/protobase/references/reference/cli.md +25 -6
- package/skills/protobase/references/reference/config/api.md +9 -1
- package/skills/protobase/references/reference/data-config.md +36 -0
- package/skills/protobase/references/reference/email.md +4 -3
- package/dist/migration/write-migrations.js +0 -32
|
@@ -16,5 +16,7 @@ const nextMigrationName = (files, name) => {
|
|
|
16
16
|
const authMigrationTitle = "The auth schema changes this version of Protobase needs";
|
|
17
17
|
/** The file's contents: what wrote it, `writer`, and why, then Better Auth's statements, one per paragraph. */
|
|
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
|
+
/** The text of the file that starts the snapshot of a project whose store is current already: no statements. */
|
|
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`;
|
|
19
21
|
//#endregion
|
|
20
|
-
export { authMigrationTitle, migrationText, nextMigrationName };
|
|
22
|
+
export { authMigrationTitle, currentStoreText, migrationText, nextMigrationName };
|
package/dist/auth/register.js
CHANGED
|
@@ -1,20 +1,37 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
1
|
+
import { protobaseVersion } from "../version/version.js";
|
|
2
|
+
import { readSnapshot } from "../migration/snapshot/snapshot-file.js";
|
|
3
|
+
import { readMigrationFiles } from "../migration/snapshot/migration-files.js";
|
|
4
|
+
import { refuseInconsistent } from "../migration/snapshot/consistency.js";
|
|
5
|
+
import { currentStoreText, migrationText } from "./migration-file.js";
|
|
6
|
+
import { writeMigrationFile } from "../migration/snapshot/write-file.js";
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
4
8
|
import { authSchemaMigration } from "@protobase/server";
|
|
9
|
+
import { latestSteps, storeModel, storeNames } from "@protobase/server/internal";
|
|
5
10
|
//#region src/auth/write-migration.ts
|
|
6
11
|
/**
|
|
7
12
|
* Writes the auth schema changes the database still needs as the next migration in `dir`, and returns its path;
|
|
8
13
|
* `undefined` when the database is current. The changes are found by comparing the database with what Better Auth
|
|
9
|
-
* needs, so the project's earlier migrations must be applied to it first.
|
|
14
|
+
* needs, so the project's earlier migrations must be applied to it first. The file brings the store to every step of
|
|
15
|
+
* this version, so the project's snapshot, started here when it has none, ends at it with the store there, and
|
|
16
|
+
* `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.
|
|
10
18
|
*/
|
|
11
|
-
const writeAuthMigration = async ({ auth, dir, name, writer }) => {
|
|
19
|
+
const writeAuthMigration = async ({ auth, projectDir, dir, name, writer }) => {
|
|
20
|
+
const snapshot = await readSnapshot(projectDir);
|
|
21
|
+
refuseInconsistent(snapshot, await readMigrationFiles(dir));
|
|
12
22
|
const sql = await authSchemaMigration(auth);
|
|
13
|
-
if (sql === void 0) return
|
|
14
|
-
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
23
|
+
if (sql === void 0 && snapshot) return;
|
|
24
|
+
const names = storeNames(auth);
|
|
25
|
+
const draft = {
|
|
26
|
+
previous: snapshot,
|
|
27
|
+
auth: storeModel(names, latestSteps(names.names.modules)),
|
|
28
|
+
organizationsOn: Boolean(auth.organizations),
|
|
29
|
+
protobaseVersion
|
|
30
|
+
};
|
|
31
|
+
return writeMigrationFile(projectDir, dir, {
|
|
32
|
+
name,
|
|
33
|
+
body: sql === void 0 ? currentStoreText(writer) : migrationText(sql, writer)
|
|
34
|
+
}, draft, randomUUID());
|
|
18
35
|
};
|
|
19
36
|
//#endregion
|
|
20
37
|
export { writeAuthMigration };
|
package/dist/cli/package.js
CHANGED
package/dist/dev/dev-relay.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { relayAppEntry } from "../relay/app-entry.js";
|
|
2
2
|
import { relayBinary } from "./relay-binary.js";
|
|
3
3
|
import { freePort, relayUrl, startRelay } from "./relay-process.js";
|
|
4
|
-
import { checkRelayOptions } from "@protobase/server";
|
|
5
4
|
import { randomBytes } from "node:crypto";
|
|
5
|
+
import { checkRelayOptions } from "@protobase/server";
|
|
6
6
|
//#region src/dev/dev-relay.ts
|
|
7
7
|
const store = globalThis;
|
|
8
8
|
const devLimits = {
|
package/dist/doctor/startup.js
CHANGED
|
@@ -2,11 +2,11 @@ import { buildProject } from "../config/build-project.js";
|
|
|
2
2
|
import { projectAdmin } from "../project/project-admin.js";
|
|
3
3
|
import { servedAdmin } from "../project/served-admin.js";
|
|
4
4
|
import { checkStartup } from "../serve/startup-checks.js";
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
5
6
|
import pg from "pg";
|
|
6
7
|
import { checkJobsSchema } from "@protobase/server";
|
|
7
8
|
import { readOrigins, readPasskeyDomain } from "@protobase/server/internal";
|
|
8
9
|
import { Kysely, PostgresDialect } from "kysely";
|
|
9
|
-
import { randomBytes } from "node:crypto";
|
|
10
10
|
//#region src/doctor/startup.ts
|
|
11
11
|
/**
|
|
12
12
|
* The app's URL, or a stand-in that sign-in accepts: on the passkey domain when the config or `PROTOBASE_PASSKEY_DOMAIN`
|
package/dist/main.js
CHANGED
|
@@ -8,11 +8,11 @@ import { registerOrganizations } from "./organizations/register.js";
|
|
|
8
8
|
import { registerFiles } from "./files/register.js";
|
|
9
9
|
import { registerEject } from "./eject/register.js";
|
|
10
10
|
import { registerEncryption } from "./encryption/register.js";
|
|
11
|
+
import { protobaseVersion } from "./version/version.js";
|
|
11
12
|
import { registerMigration } from "./migration/register.js";
|
|
12
13
|
import { registerMobile } from "./mobile/register.js";
|
|
13
14
|
import { registerNotifications } from "./notifications/register.js";
|
|
14
15
|
import { registerRelay } from "./relay/register.js";
|
|
15
|
-
import { protobaseVersion } from "./version/version.js";
|
|
16
16
|
import { registerSkill } from "./skill/register.js";
|
|
17
17
|
import { registerImport } from "./supabase/register.js";
|
|
18
18
|
import { registerToken, registerUsers } from "./users/register.js";
|
|
@@ -11,16 +11,15 @@ import { assistantSettings, authStoreTables, configExports } from "@protobase/se
|
|
|
11
11
|
import { checkStatusOptions } from "@protobase/server/internal";
|
|
12
12
|
//#region src/migration/load-project.ts
|
|
13
13
|
/**
|
|
14
|
-
* The project in `dir` as `protobase dev` merges it
|
|
15
|
-
*
|
|
16
|
-
* ends the pool it opened.
|
|
14
|
+
* The config of the project in `dir` as `protobase dev` merges it: protobase.config.ts, with the convention's resources
|
|
15
|
+
* when it names none, after the configs of `extensions` and the configs it extends, with the `.env` nearest it read.
|
|
17
16
|
*/
|
|
18
|
-
const
|
|
17
|
+
const loadMigrationConfig = async (dir, extensions = []) => {
|
|
19
18
|
loadNearestEnvFile(dir);
|
|
20
|
-
return
|
|
19
|
+
return loadSourceConfig(dir, {
|
|
21
20
|
command: "tool",
|
|
22
21
|
extensions
|
|
23
|
-
})
|
|
22
|
+
});
|
|
24
23
|
};
|
|
25
24
|
/**
|
|
26
25
|
* A merged project config, for what its database needs: its resources' models, a pool on `url`, its auth, and the
|
|
@@ -62,4 +61,4 @@ const migrationProject = async (config, url) => {
|
|
|
62
61
|
};
|
|
63
62
|
};
|
|
64
63
|
//#endregion
|
|
65
|
-
export {
|
|
64
|
+
export { loadMigrationConfig, migrationProject };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { applyMigrations } from "./apply-migrations.js";
|
|
2
|
+
import { planMigrations } from "./plan-migrations.js";
|
|
2
3
|
import { existsSync } from "node:fs";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import postgres from "postgres";
|
|
@@ -7,9 +8,10 @@ const migrationsDir = "db/migrations";
|
|
|
7
8
|
/**
|
|
8
9
|
* The CLI's `migrate`: applies the project's db/migrations to the database, as the runtime's `migrate` applies a
|
|
9
10
|
* bundle's (see applyMigrations). It runs none of the project's code, so it needs no package.json or install. The
|
|
10
|
-
* connection is asked for only when there is something to apply.
|
|
11
|
+
* connection is asked for only when there is something to apply. With `plan`, it prints what it would apply instead
|
|
12
|
+
* (see planMigrations).
|
|
11
13
|
*/
|
|
12
|
-
const migrateProject = async (projectDir, connectionUrl, out) => {
|
|
14
|
+
const migrateProject = async (projectDir, connectionUrl, out, plan = false) => {
|
|
13
15
|
const dir = path.join(projectDir, migrationsDir);
|
|
14
16
|
if (!existsSync(dir)) {
|
|
15
17
|
out(`the project has no ${migrationsDir}\n`);
|
|
@@ -20,7 +22,7 @@ const migrateProject = async (projectDir, connectionUrl, out) => {
|
|
|
20
22
|
onnotice: () => {}
|
|
21
23
|
});
|
|
22
24
|
try {
|
|
23
|
-
await applyMigrations(sql, dir, out);
|
|
25
|
+
await (plan ? planMigrations(sql, dir, out) : applyMigrations(sql, dir, out));
|
|
24
26
|
} finally {
|
|
25
27
|
await sql.end();
|
|
26
28
|
}
|
package/dist/migration/parts.js
CHANGED
|
@@ -1,18 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { authSchemaMigration, callsMigration, capturedBy, changesMigration, channelSendsMigration, commentsMigration, computedMigration, derivedMigration, hasBuckets, jobsSchemaMigration, mailFeedbackMigration, mailFeedbackResource, notificationsMigration, ownedDefinitionsMigration, queryRunnerMigration, realtimeRelayMigration, relayMigration, relayed, sqlSends, statusMigration, unsubscribesMigration, userTablesMigration, webhooksMigration, workflowsMigration } from "@protobase/server";
|
|
1
|
+
import { callsMigration, capturedBy, changesMigration, channelSendsMigration, commentsMigration, computedMigration, derivedMigration, hasBuckets, jobsSchemaMigration, mailFeedbackMigration, mailFeedbackResource, notificationsMigration, ownedDefinitionsMigration, queryRunnerMigration, realtimeRelayMigration, relayMigration, relayed, sqlSends, statusMigration, unsubscribesMigration, userTablesMigration, webhooksMigration, workflowsMigration } from "@protobase/server";
|
|
3
2
|
//#region src/migration/parts.ts
|
|
4
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* Every feature the project's config enables but the auth store, which the snapshot holds, in the order their
|
|
5
|
+
* statements are written.
|
|
6
|
+
*/
|
|
5
7
|
const migrationParts = (project) => {
|
|
6
8
|
const comments = project.models.some((model) => model.comments);
|
|
7
9
|
const aiFields = project.models.some((model) => Object.values(model.fields).some((field) => field.ai));
|
|
8
10
|
const feedback = project.mailFeedback ? [mailFeedbackResource.toModel()] : [];
|
|
9
11
|
const captured = [...project.models, ...feedback];
|
|
10
12
|
return [
|
|
11
|
-
...project.auth ? [{
|
|
12
|
-
name: "auth",
|
|
13
|
-
title: authMigrationTitle,
|
|
14
|
-
sql: () => authSchemaMigration(project.auth)
|
|
15
|
-
}] : [],
|
|
16
13
|
...project.jobs.length > 0 || captured.some(capturedBy(captured)) || comments || aiFields || project.models.some(hasBuckets) || project.webhooks || project.workflows || project.notifications || project.realtime?.relay ? [{
|
|
17
14
|
name: "jobs",
|
|
18
15
|
title: "The jobs schema this version of Protobase needs",
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
3
|
+
//#region src/migration/plan-migrations.ts
|
|
4
|
+
const appliedNames = async (tx) => {
|
|
5
|
+
const [record] = await tx`
|
|
6
|
+
select to_regclass('migrations.applied') is not null as applied,
|
|
7
|
+
(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`;
|
|
8
|
+
if (record.applied) return (await tx`select name from migrations.applied`).map((row) => row.name);
|
|
9
|
+
if (record.earlier) return (await tx`select name from public.schema_migrations`).map((row) => row.name);
|
|
10
|
+
return [];
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* `protobase migrate --plan`: prints each `*.sql` file of `dir` that `migrate` would apply, in its order, under its
|
|
14
|
+
* name, with its SQL, from a read-only transaction: it applies and records nothing. Returns the names.
|
|
15
|
+
*/
|
|
16
|
+
const planMigrations = async (sql, dir, out) => {
|
|
17
|
+
const files = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
|
|
18
|
+
const done = new Set(await sql.begin("read only", (tx) => appliedNames(tx)));
|
|
19
|
+
const pending = files.filter((file) => !done.has(file));
|
|
20
|
+
for (const file of pending) out(`-- ${file}\n${(await readFile(path.join(dir, file), "utf8")).trimEnd()}\n\n`);
|
|
21
|
+
out(pending.length > 0 ? `${pending.length} migrations to apply; nothing was applied\n` : "the database is up to date\n");
|
|
22
|
+
return pending;
|
|
23
|
+
};
|
|
24
|
+
//#endregion
|
|
25
|
+
export { planMigrations };
|
|
@@ -1,32 +1,96 @@
|
|
|
1
1
|
import { resolveConnectionUrl } from "../db/connection-url.js";
|
|
2
2
|
import { loadNearestEnvFile } from "../dev/env.js";
|
|
3
|
+
import { protobaseVersion } from "../version/version.js";
|
|
3
4
|
import path from "node:path";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
4
6
|
//#region src/migration/register.ts
|
|
5
7
|
const out = (text) => process.stdout.write(text);
|
|
6
8
|
const collect = (value, previous) => [...previous, value];
|
|
9
|
+
const loadAuthTarget = async (opts) => {
|
|
10
|
+
const [{ loadMigrationConfig }, { authTarget }, { resolveExtensions }] = await Promise.all([
|
|
11
|
+
import("./load-project.js"),
|
|
12
|
+
import("./snapshot/auth-target.js"),
|
|
13
|
+
import("../project/extensions.js")
|
|
14
|
+
]);
|
|
15
|
+
const config = await loadMigrationConfig(process.cwd(), resolveExtensions(opts.extend));
|
|
16
|
+
return {
|
|
17
|
+
config,
|
|
18
|
+
auth: await authTarget(config)
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
const folderOptions = (command) => command.option("--dir <dir>", "migrations folder", "db/migrations").option("--extend <dir>", "merge the protobase.config.ts in this folder before the project's, as dev and build do, repeatable", collect, []);
|
|
7
22
|
const registerMigration = (program) => {
|
|
8
|
-
program.command("migrate").description("Apply the project's db/migrations/*.sql not applied yet, in one transaction, as the runtime's migrate applies a bundle's").argument("[connection]", "connection string (default: DATABASE_URL from the environment or .env)").option("--env <variable>", "read the connection string from this environment variable").action(async (connection, opts) => {
|
|
23
|
+
program.command("migrate").description("Apply the project's db/migrations/*.sql not applied yet, in one transaction, as the runtime's migrate applies a bundle's").argument("[connection]", "connection string (default: DATABASE_URL from the environment or .env)").option("--env <variable>", "read the connection string from this environment variable").option("--plan", "print each migration not applied yet with its SQL, and apply nothing").action(async (connection, opts) => {
|
|
9
24
|
loadNearestEnvFile(process.cwd());
|
|
10
25
|
const { migrateProject } = await import("./migrate-project.js");
|
|
11
|
-
await migrateProject(process.cwd(), () => resolveConnectionUrl(connection, opts.env), out);
|
|
26
|
+
await migrateProject(process.cwd(), () => resolveConnectionUrl(connection, opts.env), out, Boolean(opts.plan));
|
|
12
27
|
});
|
|
13
|
-
program.command("migration").description("Write what the
|
|
14
|
-
|
|
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) => {
|
|
29
|
+
if (opts.recordConfig && !opts.custom) throw new Error("--record-config goes with --custom <name>");
|
|
30
|
+
const { config, auth } = await loadAuthTarget(opts);
|
|
31
|
+
const dir = path.resolve(opts.dir);
|
|
32
|
+
if (opts.custom) {
|
|
33
|
+
const { writeCustomMigration } = await import("./snapshot/custom.js");
|
|
34
|
+
const file = await writeCustomMigration({
|
|
35
|
+
projectDir: process.cwd(),
|
|
36
|
+
dir,
|
|
37
|
+
name: opts.custom,
|
|
38
|
+
recordConfig: Boolean(opts.recordConfig),
|
|
39
|
+
auth,
|
|
40
|
+
protobaseVersion,
|
|
41
|
+
newId: randomUUID
|
|
42
|
+
});
|
|
43
|
+
out(`wrote ${path.relative(process.cwd(), file)} and protobase.snapshot.json: write its statements\n`);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const [{ migrationProject }, { migrationParts }, { runMigration }, { migrationSummary }] = await Promise.all([
|
|
15
47
|
import("./load-project.js"),
|
|
16
48
|
import("./parts.js"),
|
|
17
|
-
import("./
|
|
18
|
-
import("./summary.js")
|
|
19
|
-
import("../project/extensions.js")
|
|
49
|
+
import("./snapshot/run-migration.js"),
|
|
50
|
+
import("./summary.js")
|
|
20
51
|
]);
|
|
21
|
-
const
|
|
52
|
+
const url = process.env.DATABASE_URL;
|
|
53
|
+
const project = url ? await migrationProject(config, url) : void 0;
|
|
22
54
|
try {
|
|
23
|
-
const
|
|
24
|
-
|
|
55
|
+
const file = await runMigration({
|
|
56
|
+
projectDir: process.cwd(),
|
|
57
|
+
dir,
|
|
58
|
+
auth,
|
|
59
|
+
database: project && url ? {
|
|
60
|
+
url,
|
|
61
|
+
parts: migrationParts(project)
|
|
62
|
+
} : void 0,
|
|
63
|
+
protobaseVersion,
|
|
64
|
+
newId: randomUUID
|
|
65
|
+
});
|
|
66
|
+
out(migrationSummary(file, process.cwd(), {
|
|
67
|
+
hasAuth: Boolean(auth),
|
|
68
|
+
compared: Boolean(project)
|
|
69
|
+
}));
|
|
25
70
|
} finally {
|
|
26
|
-
await project
|
|
71
|
+
await project?.close();
|
|
27
72
|
}
|
|
28
73
|
process.exit(0);
|
|
29
74
|
});
|
|
75
|
+
folderOptions(migration.command("check").description("Report, writing nothing, what keeps the migrations and protobase.snapshot.json from matching the config; exit code 1 when anything does, for CI")).action(async (opts) => {
|
|
76
|
+
const { auth } = await loadAuthTarget(opts);
|
|
77
|
+
const { checkMigrations } = await import("./snapshot/check.js");
|
|
78
|
+
const found = await checkMigrations(process.cwd(), path.resolve(opts.dir), auth);
|
|
79
|
+
if (found.length === 0) {
|
|
80
|
+
out("the migrations and protobase.snapshot.json match the config\n");
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
out(found.map((line) => `${line}\n`).join(""));
|
|
84
|
+
process.exitCode = 1;
|
|
85
|
+
});
|
|
86
|
+
migration.command("drop").description("Delete the newest migration `protobase migration` wrote and take protobase.snapshot.json back to the one before it").option("--dir <dir>", "migrations folder", "db/migrations").action(async (opts) => {
|
|
87
|
+
const { dropMigration } = await import("./snapshot/drop.js");
|
|
88
|
+
out(`deleted ${await dropMigration(process.cwd(), path.resolve(opts.dir))} and took protobase.snapshot.json back\n`);
|
|
89
|
+
});
|
|
90
|
+
migration.command("up").description("Rewrite protobase.snapshot.json in this version's format").action(async () => {
|
|
91
|
+
const { upgradeSnapshot } = await import("./snapshot/up.js");
|
|
92
|
+
out(`${await upgradeSnapshot(process.cwd())}\n`);
|
|
93
|
+
});
|
|
30
94
|
};
|
|
31
95
|
//#endregion
|
|
32
96
|
export { registerMigration };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { snapshotFile } from "./snapshot-file.js";
|
|
2
|
+
import { latestSteps, nameChanges, offlineStepsMigration, storeModel } from "@protobase/server/internal";
|
|
3
|
+
//#region src/migration/snapshot/auth-difference.ts
|
|
4
|
+
/** Each module's last step in a model. */
|
|
5
|
+
const lastStepsOf = (model) => Object.fromEntries(Object.entries(model.modules).map(([module, entry]) => [module, entry.lastStep]));
|
|
6
|
+
/**
|
|
7
|
+
* What the config asks of the auth store that Protobase's steps cannot write, one line each: sign-in turned off while
|
|
8
|
+
* the snapshot has the store, or a name or type the store has changed. None when the steps can bring it there.
|
|
9
|
+
*/
|
|
10
|
+
const authRefusals = (snapshot, target) => {
|
|
11
|
+
const before = snapshot?.model.auth;
|
|
12
|
+
if (!before) return [];
|
|
13
|
+
if (!target) return [`sign-in is off while ${snapshotFile} has the auth store, and turning it off is not supported yet`];
|
|
14
|
+
return nameChanges(before, storeModel(target.names, lastStepsOf(before))).map((change) => `the auth store's ${change}`);
|
|
15
|
+
};
|
|
16
|
+
/** How to write what the steps cannot, once refused. */
|
|
17
|
+
const customHint = "Write the change by hand with `protobase migration --custom <name> --record-config`.";
|
|
18
|
+
/**
|
|
19
|
+
* The difference between the snapshot's auth store and the config's, from the snapshot alone: the steps after each
|
|
20
|
+
* module's last one (`migration`, undefined when there are none), and the store's model once they are applied.
|
|
21
|
+
*/
|
|
22
|
+
const authDifference = (snapshot, target) => {
|
|
23
|
+
const refusals = authRefusals(snapshot, target);
|
|
24
|
+
if (refusals.length > 0) throw new Error(`${refusals.join("; ")}. ${customHint}`);
|
|
25
|
+
if (!target) return {
|
|
26
|
+
model: void 0,
|
|
27
|
+
migration: void 0
|
|
28
|
+
};
|
|
29
|
+
const before = snapshot?.model.auth;
|
|
30
|
+
const migration = offlineStepsMigration(target.names, before && lastStepsOf(before));
|
|
31
|
+
return {
|
|
32
|
+
migration,
|
|
33
|
+
model: storeModel(target.names, migration || !before ? latestSteps(target.names.names.modules) : lastStepsOf(before))
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
//#endregion
|
|
37
|
+
export { authDifference, authRefusals, customHint, lastStepsOf };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { settingsStoreNames } from "@protobase/server/internal";
|
|
2
|
+
//#region src/migration/snapshot/auth-target.ts
|
|
3
|
+
/** The config's auth store, from its `auth` and whether auth/hooks.ts gives users their ids; `undefined` with sign-in off. */
|
|
4
|
+
const authTarget = async (config) => {
|
|
5
|
+
if (!config.auth) return;
|
|
6
|
+
const hooks = await config.authFiles?.module("auth/hooks.ts")?.();
|
|
7
|
+
return {
|
|
8
|
+
names: settingsStoreNames(config.auth, typeof hooks?.generateUserId === "function"),
|
|
9
|
+
organizationsOn: Boolean(config.auth.organizations)
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
//#endregion
|
|
13
|
+
export { authTarget };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { readSnapshot, snapshotFile } from "./snapshot-file.js";
|
|
2
|
+
import { readMigrationFiles } from "./migration-files.js";
|
|
3
|
+
import { inconsistencies } from "./consistency.js";
|
|
4
|
+
import "../../auth/migration-file.js";
|
|
5
|
+
import { authRefusals, lastStepsOf } from "./auth-difference.js";
|
|
6
|
+
import { lintCustomFiles } from "./lint-custom.js";
|
|
7
|
+
import { offlineStepsMigration } from "@protobase/server/internal";
|
|
8
|
+
//#region src/migration/snapshot/check.ts
|
|
9
|
+
/**
|
|
10
|
+
* `protobase migration check`, for CI: what keeps the migrations from matching the config, one line each, from the
|
|
11
|
+
* files and the snapshot alone, writing nothing. The snapshot disagreeing with the files, a config change the
|
|
12
|
+
* migrations lack, and a hand-written migration marked additive that is not. None when they match.
|
|
13
|
+
*/
|
|
14
|
+
const checkMigrations = async (projectDir, dir, auth) => {
|
|
15
|
+
const snapshot = await readSnapshot(projectDir);
|
|
16
|
+
const files = await readMigrationFiles(dir);
|
|
17
|
+
const found = inconsistencies(snapshot, files);
|
|
18
|
+
const before = snapshot?.model.auth;
|
|
19
|
+
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 auth migration\`, against the database with the project's migrations applied`);
|
|
21
|
+
else if (refusals.length > 0) found.push(...refusals);
|
|
22
|
+
else if (auth && offlineStepsMigration(auth.names, before && lastStepsOf(before))) found.push("the config and this version of Protobase need auth store steps the migrations lack: run `protobase migration`");
|
|
23
|
+
return [...found, ...lintCustomFiles(files)];
|
|
24
|
+
};
|
|
25
|
+
//#endregion
|
|
26
|
+
export { checkMigrations };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { modelHash, snapshotFile } from "./snapshot-file.js";
|
|
2
|
+
import { protobaseFiles, sharedNumbers } from "./migration-files.js";
|
|
3
|
+
//#region src/migration/snapshot/consistency.ts
|
|
4
|
+
/**
|
|
5
|
+
* What makes the snapshot disagree with the migration files, one line each: two files sharing a number, as after
|
|
6
|
+
* merging two branches that each wrote one, a snapshot that does not end at the newest file Protobase wrote, or one
|
|
7
|
+
* whose model was edited since it was written. None when they agree.
|
|
8
|
+
*/
|
|
9
|
+
const inconsistencies = (snapshot, files) => {
|
|
10
|
+
const shared = sharedNumbers(files).map((same) => `${same.map(({ file }) => file).join(" and ")} share a number`);
|
|
11
|
+
const newest = protobaseFiles(files).at(-1);
|
|
12
|
+
if (!snapshot) return newest ? [...shared, `${newest.file} was written by \`protobase migration\`, and the project has no ${snapshotFile}`] : shared;
|
|
13
|
+
const ends = newest === void 0 ? [`${snapshotFile} ends at ${snapshot.endsAt.file}, which is not among the migrations`] : newest.header.id === snapshot.endsAt.id ? [] : [`${snapshotFile} ends at ${snapshot.endsAt.file}, not at the newest migration Protobase wrote, ${newest.file}`];
|
|
14
|
+
const edited = modelHash(snapshot.model) === snapshot.modelHash ? [] : [`${snapshotFile}'s model does not match its modelHash: it was edited or merged by hand`];
|
|
15
|
+
return [
|
|
16
|
+
...shared,
|
|
17
|
+
...ends,
|
|
18
|
+
...edited
|
|
19
|
+
];
|
|
20
|
+
};
|
|
21
|
+
/** How to resolve them once two branches each wrote a migration. */
|
|
22
|
+
const resolveHint = `Delete this branch's newest migration, take the other branch's ${snapshotFile}, and run \`protobase migration\` again.`;
|
|
23
|
+
/** Refuses to go on while the snapshot disagrees with the files. */
|
|
24
|
+
const refuseInconsistent = (snapshot, files) => {
|
|
25
|
+
const found = inconsistencies(snapshot, files);
|
|
26
|
+
if (found.length > 0) throw new Error(`${found.join("; ")}. ${resolveHint}`);
|
|
27
|
+
};
|
|
28
|
+
//#endregion
|
|
29
|
+
export { inconsistencies, refuseInconsistent, resolveHint };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { readSnapshot, snapshotFile } from "./snapshot-file.js";
|
|
2
|
+
import { readMigrationFiles } from "./migration-files.js";
|
|
3
|
+
import { refuseInconsistent } from "./consistency.js";
|
|
4
|
+
import { lastStepsOf } from "./auth-difference.js";
|
|
5
|
+
import { writeMigrationFile } from "./write-file.js";
|
|
6
|
+
import { storeModel } from "@protobase/server/internal";
|
|
7
|
+
//#region src/migration/snapshot/custom.ts
|
|
8
|
+
const body = (recordConfig) => [
|
|
9
|
+
`-- Written by hand; \`protobase migration --custom\` numbered it and made ${snapshotFile} end at it.`,
|
|
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
|
+
...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
|
+
].join("\n");
|
|
14
|
+
/**
|
|
15
|
+
* `protobase migration --custom <name>`: writes an empty numbered migration for the developer to fill, and makes the
|
|
16
|
+
* snapshot end at it. With `recordConfig`, the snapshot takes the config's auth store names, each module at the step
|
|
17
|
+
* it was. Returns the file's path.
|
|
18
|
+
*/
|
|
19
|
+
const writeCustomMigration = async ({ projectDir, dir, name, recordConfig, auth, protobaseVersion, newId }) => {
|
|
20
|
+
const snapshot = await readSnapshot(projectDir);
|
|
21
|
+
refuseInconsistent(snapshot, await readMigrationFiles(dir));
|
|
22
|
+
const before = snapshot?.model.auth;
|
|
23
|
+
const draft = {
|
|
24
|
+
previous: snapshot,
|
|
25
|
+
auth: recordConfig ? before && auth && storeModel(auth.names, lastStepsOf(before)) : before,
|
|
26
|
+
organizationsOn: auth?.organizationsOn ?? false,
|
|
27
|
+
protobaseVersion
|
|
28
|
+
};
|
|
29
|
+
return writeMigrationFile(projectDir, dir, {
|
|
30
|
+
name,
|
|
31
|
+
body: body(recordConfig),
|
|
32
|
+
kind: {
|
|
33
|
+
custom: true,
|
|
34
|
+
additive: false
|
|
35
|
+
}
|
|
36
|
+
}, draft, newId());
|
|
37
|
+
};
|
|
38
|
+
//#endregion
|
|
39
|
+
export { writeCustomMigration };
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { modelHash, readSnapshot, removeSnapshot, snapshotFile, writeSnapshot } from "./snapshot-file.js";
|
|
2
|
+
import { protobaseFiles, readMigrationFiles } from "./migration-files.js";
|
|
3
|
+
import { refuseInconsistent } from "./consistency.js";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { rm } from "node:fs/promises";
|
|
6
|
+
import { storeNamesList } from "@protobase/server/internal";
|
|
7
|
+
//#region src/migration/snapshot/drop.ts
|
|
8
|
+
const atSteps = (model, steps) => {
|
|
9
|
+
if (!model || Object.keys(steps).length === 0) return;
|
|
10
|
+
const modules = Object.entries(model.modules).filter(([module]) => steps[module] !== void 0);
|
|
11
|
+
return {
|
|
12
|
+
...model,
|
|
13
|
+
modules: Object.fromEntries(modules.map(([module, entry]) => [module, {
|
|
14
|
+
...entry,
|
|
15
|
+
lastStep: steps[module]
|
|
16
|
+
}]))
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* `protobase migration drop`: deletes the newest migration Protobase wrote and takes the snapshot back to the one
|
|
21
|
+
* before it, or removes the snapshot when it was the first. Refuses while the snapshot disagrees with the files, so it
|
|
22
|
+
* never deletes another branch's migration, and when the snapshot before cannot be rebuilt exactly, as after a
|
|
23
|
+
* hand-written migration that recorded the config. Returns the file it deleted.
|
|
24
|
+
*/
|
|
25
|
+
const dropMigration = async (projectDir, dir) => {
|
|
26
|
+
const snapshot = await readSnapshot(projectDir);
|
|
27
|
+
if (!snapshot) throw new Error(`The project has no ${snapshotFile}: no migration of Protobase's to drop`);
|
|
28
|
+
const files = await readMigrationFiles(dir);
|
|
29
|
+
refuseInconsistent(snapshot, files);
|
|
30
|
+
const written = protobaseFiles(files);
|
|
31
|
+
const newest = written.at(-1);
|
|
32
|
+
const previous = written.at(-2);
|
|
33
|
+
if (!previous) {
|
|
34
|
+
await rm(path.join(dir, newest.file));
|
|
35
|
+
await removeSnapshot(projectDir);
|
|
36
|
+
return newest.file;
|
|
37
|
+
}
|
|
38
|
+
const auth = atSteps(snapshot.model.auth, previous.header.steps);
|
|
39
|
+
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`);
|
|
41
|
+
const rebuilt = {
|
|
42
|
+
...snapshot,
|
|
43
|
+
protobaseVersion: previous.header.version,
|
|
44
|
+
endsAt: {
|
|
45
|
+
file: previous.file,
|
|
46
|
+
id: previous.header.id
|
|
47
|
+
},
|
|
48
|
+
modelHash: previous.header.model,
|
|
49
|
+
model,
|
|
50
|
+
decisions: {
|
|
51
|
+
...snapshot.decisions,
|
|
52
|
+
organizations: {
|
|
53
|
+
...snapshot.decisions.organizations,
|
|
54
|
+
everOn: previous.header.organizationsEverOn
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
physical: auth ? { auth: storeNamesList(auth) } : {}
|
|
58
|
+
};
|
|
59
|
+
await rm(path.join(dir, newest.file));
|
|
60
|
+
await writeSnapshot(projectDir, rebuilt);
|
|
61
|
+
return newest.file;
|
|
62
|
+
};
|
|
63
|
+
//#endregion
|
|
64
|
+
export { dropMigration };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
//#region src/migration/snapshot/header.ts
|
|
2
|
+
const line = /^-- protobase:([a-z-]+)(?: (.*))?$/;
|
|
3
|
+
const headerText = ({ id, version, steps, model, organizationsEverOn, custom, additive }) => [
|
|
4
|
+
`-- protobase:id ${id}`,
|
|
5
|
+
`-- protobase:version ${version}`,
|
|
6
|
+
`-- protobase:steps ${Object.entries(steps).map(([module, step]) => `${module}=${step}`).join(" ")}`.trimEnd(),
|
|
7
|
+
`-- protobase:model ${model}`,
|
|
8
|
+
...organizationsEverOn ? ["-- protobase:organizations ever-on"] : [],
|
|
9
|
+
...custom ? ["-- protobase:custom"] : [],
|
|
10
|
+
...additive ? ["-- protobase:additive"] : []
|
|
11
|
+
].join("\n");
|
|
12
|
+
/** The header of a migration's text; `undefined` when it does not start with Protobase's id. */
|
|
13
|
+
const parseHeader = (text) => {
|
|
14
|
+
const values = /* @__PURE__ */ new Map();
|
|
15
|
+
for (const row of text.split("\n")) {
|
|
16
|
+
const found = line.exec(row);
|
|
17
|
+
if (!found) break;
|
|
18
|
+
values.set(found[1], found[2] ?? "");
|
|
19
|
+
}
|
|
20
|
+
const id = values.get("id");
|
|
21
|
+
if (!id) return;
|
|
22
|
+
const steps = (values.get("steps") ?? "").split(" ").filter(Boolean).map((pair) => pair.split("="));
|
|
23
|
+
return {
|
|
24
|
+
id,
|
|
25
|
+
version: values.get("version") ?? "",
|
|
26
|
+
steps: Object.fromEntries(steps.map(([module, step]) => [module, Number(step)])),
|
|
27
|
+
model: values.get("model") ?? "",
|
|
28
|
+
organizationsEverOn: values.get("organizations") === "ever-on",
|
|
29
|
+
custom: values.has("custom"),
|
|
30
|
+
additive: values.has("additive")
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
//#endregion
|
|
34
|
+
export { headerText, parseHeader };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { lintSteps } from "@protobase/server/internal";
|
|
3
|
+
//#region src/migration/snapshot/lint-custom.ts
|
|
4
|
+
const createTable = /^\s*create\s+table\s+(?:if\s+not\s+exists\s+)?((?:(?:"[^"]+"|\w+)\.)?(?:"[^"]+"|\w+))/gim;
|
|
5
|
+
/**
|
|
6
|
+
* What makes each hand-written migration marked additive unsafe to apply unattended, by the same lint as Protobase's
|
|
7
|
+
* own steps (Squawk, with the rules `lintSteps` refuses). A hand-written one that is not marked counts as not additive
|
|
8
|
+
* and is not linted.
|
|
9
|
+
*/
|
|
10
|
+
const lintCustomFiles = (files) => {
|
|
11
|
+
const additive = files.filter(({ header }) => header?.custom && header.additive);
|
|
12
|
+
if (additive.length === 0) return [];
|
|
13
|
+
const squawk = createRequire(import.meta.url).resolve("squawk-cli/js/bin/squawk");
|
|
14
|
+
const steps = additive.map(({ file, text }) => ({
|
|
15
|
+
label: file,
|
|
16
|
+
sql: text,
|
|
17
|
+
made: [...text.matchAll(createTable)].map((match) => match[1]),
|
|
18
|
+
checked: false
|
|
19
|
+
}));
|
|
20
|
+
return lintSteps(steps, squawk).map(({ step, rule, message }) => `${step} is marked additive and breaks ${rule}: ${message}`);
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
export { lintCustomFiles };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { parseHeader } from "./header.js";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
5
|
+
//#region src/migration/snapshot/migration-files.ts
|
|
6
|
+
const numbered = /^(\d+)_.*\.sql$/;
|
|
7
|
+
/** The numbered migrations of `dir`, by number then name; none when it does not exist. */
|
|
8
|
+
const readMigrationFiles = async (dir) => {
|
|
9
|
+
if (!existsSync(dir)) return [];
|
|
10
|
+
const names = (await readdir(dir)).filter((file) => numbered.test(file)).sort();
|
|
11
|
+
return (await Promise.all(names.map(async (file) => {
|
|
12
|
+
const text = await readFile(path.join(dir, file), "utf8");
|
|
13
|
+
const header = parseHeader(text);
|
|
14
|
+
return {
|
|
15
|
+
file,
|
|
16
|
+
number: Number(numbered.exec(file)[1]),
|
|
17
|
+
text,
|
|
18
|
+
...header && { header }
|
|
19
|
+
};
|
|
20
|
+
}))).sort((a, b) => a.number - b.number || a.file.localeCompare(b.file));
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* The files of each number two or more of them share, one of them written by Protobase, such as one from each of two
|
|
24
|
+
* merged branches. Hand-written files that shared a number before the snapshot are history already applied, and stay.
|
|
25
|
+
*/
|
|
26
|
+
const sharedNumbers = (files) => [...new Set(files.map(({ number }) => number))].map((number) => files.filter((file) => file.number === number)).filter((same) => same.length > 1 && same.some((file) => file.header !== void 0));
|
|
27
|
+
/** The files Protobase wrote, in order. */
|
|
28
|
+
const protobaseFiles = (files) => files.filter((file) => file.header !== void 0);
|
|
29
|
+
//#endregion
|
|
30
|
+
export { protobaseFiles, readMigrationFiles, sharedNumbers };
|