@protobase/cli 0.128.0 → 0.129.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/auth/migration-file.js +3 -1
  2. package/dist/auth/write-migration.js +15 -5
  3. package/dist/cli/package.js +1 -1
  4. package/dist/dev/entry.js +5 -4
  5. package/dist/migration/apply-migrations.js +96 -25
  6. package/dist/migration/baseline/read-live-store.js +36 -0
  7. package/dist/migration/baseline/write-baseline.js +47 -0
  8. package/dist/migration/plan-migrations.js +26 -24
  9. package/dist/migration/record/after-file.js +22 -0
  10. package/dist/migration/record/fill-row.js +25 -0
  11. package/dist/migration/record/migration-dir.js +34 -0
  12. package/dist/migration/record/pending.js +36 -0
  13. package/dist/migration/record/record-block.js +38 -0
  14. package/dist/migration/record/run-after.js +23 -0
  15. package/dist/migration/register.js +20 -2
  16. package/dist/migration/release/apply-release-steps.js +6 -5
  17. package/dist/migration/release/release-record.js +30 -0
  18. package/dist/migration/snapshot/auth-difference.js +9 -2
  19. package/dist/migration/snapshot/check.js +3 -5
  20. package/dist/migration/snapshot/custom.js +15 -5
  21. package/dist/migration/snapshot/drop.js +9 -4
  22. package/dist/migration/snapshot/migration-files.js +3 -2
  23. package/dist/migration/snapshot/next-snapshot.js +18 -8
  24. package/dist/migration/snapshot/run-migration.js +4 -3
  25. package/dist/migration/snapshot/snapshot-file.js +4 -3
  26. package/dist/migration/snapshot/write-file.js +20 -4
  27. package/dist/serve/create-admin.js +3 -2
  28. package/dist/serve/migrate-release.js +14 -7
  29. package/dist/serve/startup-checks.js +6 -4
  30. package/dist/users/set-disabled.js +3 -2
  31. package/package.json +8 -8
  32. package/skills/protobase/references/features/build-and-run.md +4 -3
  33. package/skills/protobase/references/guides/deploy.md +15 -1
  34. package/skills/protobase/references/reference/auth.md +1 -1
  35. package/skills/protobase/references/reference/cli.md +10 -8
@@ -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
- if (sql === void 0 && snapshot) return;
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: sql === void 0 ? currentStoreText(writer) : migrationText(sql, writer)
42
+ body,
43
+ additive: true
34
44
  }, draft, randomUUID());
35
45
  };
36
46
  //#endregion
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.128.0";
2
+ var version = "0.129.1";
3
3
  //#endregion
4
4
  export { version };
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, checkAuthSchema, checkCalls, checkChanges, checkChannelSends, checkComments, checkComputed, checkDerived, checkNotificationsSchema, checkQueryRunner, checkRealtimeRelay, checkResourcesOutsideAuthStore, checkStatusSchema, checkUserTablesSchema, checkWebhooksSchema, checkWorkflowsSchema, configExports, hasUsers, relayed, sqlSends } from "@protobase/server";
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 (project.auth && !store.__protobaseAuthSchemaChecked) {
31
- await checkAuthSchema(project.auth);
32
- store.__protobaseAuthSchemaChecked = true;
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 path from "node:path";
3
- import { readFile, readdir } from "node:fs/promises";
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` not yet recorded in `migrations.applied`, in file name order and in one
9
- * transaction behind an advisory lock: when one fails, none is applied. Run it before a new version serves, while
10
- * nothing else writes. Returns the names it applied.
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 files = (await readdir(dir)).filter((file) => file.endsWith(".sql")).sort();
14
- const applied = await sql.begin(async (tx) => {
15
- await tx`select pg_advisory_xact_lock(${lockKey})`;
16
- const [record] = await tx`select to_regclass('migrations.applied') is null as fresh`;
17
- await tx`create schema if not exists migrations`;
18
- await tx`create table if not exists migrations.applied (name text primary key, applied_at timestamptz not null default now())`;
19
- if (record.fresh) await adoptPublicRecord(tx);
20
- const done = new Set((await tx`select name from migrations.applied`).map((row) => row.name));
21
- const pending = files.filter((file) => !done.has(file));
22
- for (const file of pending) {
23
- out(`applying ${file}\n`);
24
- await tx`select set_config('migrations.file', ${await readFile(path.join(dir, file), "utf8")}, true)`;
25
- await tx.unsafe(executeFile);
26
- await tx`insert into migrations.applied (name) values (${file})`;
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 };
@@ -0,0 +1,36 @@
1
+ import postgres from "postgres";
2
+ //#region src/migration/baseline/read-live-store.ts
3
+ /**
4
+ * The auth store at `url` as its schema has it, read once in a read-only transaction: every relation of the store's
5
+ * schema with its kind and columns, and the versions its `auth_migrations` records. Refuses a store without that
6
+ * table, one made before 0.48, which `protobase auth migration` adopts first.
7
+ */
8
+ const readLiveStore = async (url, names) => {
9
+ const sql = postgres(url, {
10
+ max: 1,
11
+ onnotice: () => {}
12
+ });
13
+ const record = names.names.table("auth_migrations");
14
+ try {
15
+ return await sql.begin("read only", async (tx) => {
16
+ const rows = await tx`
17
+ select c.relname as name, c.relkind as kind,
18
+ array(select a.attname::text from pg_catalog.pg_attribute a where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped order by a.attnum) as columns
19
+ from pg_catalog.pg_class c join pg_catalog.pg_namespace n on n.oid = c.relnamespace
20
+ where n.nspname = coalesce(${names.schema ?? null}::text, current_schema()) and c.relkind in ('r', 'p', 'v', 'm', 'f')`;
21
+ const relations = Object.fromEntries(rows.map(({ name, kind, columns }) => [name, {
22
+ kind,
23
+ columns
24
+ }]));
25
+ if (!relations[record.name]) throw new Error(`The auth store has no ${record.name} table, as a store made before 0.48: adopt it with \`protobase auth migration\` and apply that file first`);
26
+ return {
27
+ versions: (await tx.unsafe(`select ${String(record.columns.version)} as version from ${String(record)} order by 1`)).map(({ version }) => Number(version)),
28
+ relations
29
+ };
30
+ });
31
+ } finally {
32
+ await sql.end();
33
+ }
34
+ };
35
+ //#endregion
36
+ export { readLiveStore };
@@ -0,0 +1,47 @@
1
+ import { readSnapshot, snapshotFile } from "../snapshot/snapshot-file.js";
2
+ import { readMigrationFiles } from "../snapshot/migration-files.js";
3
+ import { refuseInconsistent } from "../snapshot/consistency.js";
4
+ import { writeMigrationFile } from "../snapshot/write-file.js";
5
+ import { readLiveStore } from "./read-live-store.js";
6
+ import { baselineStore, storeModel } from "@protobase/server/internal";
7
+ //#region src/migration/baseline/write-baseline.ts
8
+ const body = `-- Written by \`protobase migration baseline\` from the database: the auth store as the project's earlier migrations made it.
9
+ -- It changes nothing and drops nothing; it starts ${snapshotFile}, and \`protobase migration\` writes what the store lacks from it.
10
+ `;
11
+ /**
12
+ * `protobase migration baseline`: describes the auth store of a project without a snapshot, as its database has it,
13
+ * in a numbered migration that only records itself and the snapshot that ends at it, once. Each module that is on is
14
+ * at the step `auth_migrations` records, a module that is off but has tables is kept, organizations count as ever on
15
+ * when a table whose rows belong to one has the column that names it, and a user table another system made is
16
+ * external. Returns the file's path.
17
+ */
18
+ const writeBaseline = async ({ projectDir, dir, auth, url, protobaseVersion, newId }) => {
19
+ if (await readSnapshot(projectDir)) throw new Error(`The project has ${snapshotFile} already: a baseline only starts it, and \`protobase migration\` goes on from it`);
20
+ refuseInconsistent(void 0, await readMigrationFiles(dir));
21
+ const store = baselineStore(auth.names, await readLiveStore(url, auth.names));
22
+ const decisions = {
23
+ modules: {
24
+ kept: store.kept,
25
+ archived: []
26
+ },
27
+ organizations: {
28
+ everOn: store.organizationsEverOn,
29
+ defaultOrganization: null
30
+ },
31
+ external: store.external
32
+ };
33
+ const draft = {
34
+ previous: void 0,
35
+ auth: storeModel(auth.names, store.lastSteps),
36
+ organizationsOn: auth.organizationsOn,
37
+ protobaseVersion,
38
+ decisions
39
+ };
40
+ return writeMigrationFile(projectDir, dir, {
41
+ name: "baseline",
42
+ body,
43
+ additive: true
44
+ }, draft, newId());
45
+ };
46
+ //#endregion
47
+ export { writeBaseline };
@@ -1,31 +1,33 @@
1
- import path from "node:path";
2
- import { readFile, readdir } from "node:fs/promises";
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
- 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 [];
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 `*.sql` file of `dir` that `migrate` would apply, in its order, under its
22
- * name, with its SQL: it applies and records nothing. Returns the names.
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 file of pending) out(`-- ${file}\n${(await readFile(path.join(dir, file), "utf8")).trimEnd()}\n\n`);
27
- out(pending.length > 0 ? `${pending.length} migrations to apply; nothing was applied\n` : "the database is up to date\n");
28
- return pending;
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 { pendingIn, pendingMigrations, planMigrations };
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([
@@ -83,6 +85,22 @@ const registerMigration = (program) => {
83
85
  out(found.map((line) => `${line}\n`).join(""));
84
86
  process.exitCode = 1;
85
87
  });
88
+ folderOptions(migration.command("baseline").description("Start protobase.snapshot.json of a project whose auth migrations came before it from DATABASE_URL, read once, with a numbered migration that changes nothing")).action(async (opts) => {
89
+ const { auth } = await loadAuthTarget(opts);
90
+ if (!auth) throw new Error("sign-in is off in the project's config, so there is no auth store to describe");
91
+ const url = process.env.DATABASE_URL;
92
+ if (!url) throw new Error("No database: set DATABASE_URL to the project's database with its migrations applied");
93
+ const { writeBaseline } = await import("./baseline/write-baseline.js");
94
+ const file = await writeBaseline({
95
+ projectDir: process.cwd(),
96
+ dir: path.resolve(opts.dir),
97
+ auth,
98
+ url,
99
+ protobaseVersion,
100
+ newId: randomUUID
101
+ });
102
+ out(`wrote ${path.relative(process.cwd(), file)} and protobase.snapshot.json: apply it with the project's migrations, then run \`protobase migration\`\n`);
103
+ });
86
104
  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
105
  const { dropMigration } = await import("./snapshot/drop.js");
88
106
  out(`deleted ${await dropMigration(process.cwd(), path.resolve(opts.dir))} and took protobase.snapshot.json back\n`);
@@ -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, each as `migrate` runs a file, so
5
- * none commits early: when one fails, such as a check that refuses the rows already there, none is applied. `find` runs
6
- * once the lock is held, so a run that waited on another finds the steps from what that one committed.
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 pg_advisory_xact_lock(${lockKey})`;
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`);