@protobase/cli 0.129.1 → 0.130.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.
Files changed (96) hide show
  1. package/dist/auth/config-organizations.js +15 -0
  2. package/dist/auth/register.js +8 -2
  3. package/dist/auth/write-migration.js +34 -12
  4. package/dist/cli/package.js +1 -1
  5. package/dist/config/build-project.js +1 -0
  6. package/dist/config/project-modules.js +64 -0
  7. package/dist/config/read-only-queries.js +9 -0
  8. package/dist/config/user-tables-config.js +1 -1
  9. package/dist/dev/dev-jobs.js +12 -6
  10. package/dist/dev/entry.js +12 -19
  11. package/dist/doctor/capture-files.js +3 -3
  12. package/dist/doctor/startup.js +2 -4
  13. package/dist/migration/apply-migrations.js +9 -6
  14. package/dist/migration/baseline/read-live-modules.js +31 -0
  15. package/dist/migration/baseline/read-live-store.js +18 -4
  16. package/dist/migration/baseline/write-baseline.js +50 -17
  17. package/dist/migration/migrate-project.js +3 -3
  18. package/dist/migration/migration-project.js +29 -15
  19. package/dist/migration/older-code/catalog.js +34 -0
  20. package/dist/migration/older-code/contractions.js +86 -0
  21. package/dist/migration/older-code/lint-files.js +55 -0
  22. package/dist/migration/older-code/refusal.js +9 -0
  23. package/dist/migration/older-code/trial.js +58 -0
  24. package/dist/migration/parts.js +8 -104
  25. package/dist/migration/record/after-file.js +20 -2
  26. package/dist/migration/register.js +44 -19
  27. package/dist/migration/release/release-record.js +9 -7
  28. package/dist/migration/release/release-steps.js +15 -3
  29. package/dist/migration/snapshot/auth-difference.js +107 -15
  30. package/dist/migration/snapshot/auth-target.js +9 -3
  31. package/dist/migration/snapshot/check.js +24 -5
  32. package/dist/migration/snapshot/custom.js +6 -3
  33. package/dist/migration/snapshot/drop.js +5 -1
  34. package/dist/migration/snapshot/header.js +11 -4
  35. package/dist/migration/snapshot/module-changes.js +22 -0
  36. package/dist/migration/snapshot/module-prompts.js +28 -0
  37. package/dist/migration/snapshot/module-sections.js +38 -0
  38. package/dist/migration/snapshot/next-snapshot.js +13 -7
  39. package/dist/migration/snapshot/off-choice.js +11 -0
  40. package/dist/migration/snapshot/organizations-off-facts.js +49 -0
  41. package/dist/migration/snapshot/revival-rows.js +34 -0
  42. package/dist/migration/snapshot/run-migration.js +81 -15
  43. package/dist/migration/snapshot/snapshot-file.js +7 -0
  44. package/dist/migration/snapshot/terminal-prompts.js +21 -0
  45. package/dist/migration/snapshot/write-file.js +1 -1
  46. package/dist/migration/summary.js +3 -2
  47. package/dist/organizations/api.js +4 -2
  48. package/dist/organizations/commands.js +27 -10
  49. package/dist/organizations/pin-source.js +20 -0
  50. package/dist/organizations/pin.js +40 -0
  51. package/dist/organizations/register.js +20 -12
  52. package/dist/scaffold/protobase-tables.js +2 -2
  53. package/dist/serve/create-admin.js +6 -3
  54. package/dist/serve/lifecycle.js +2 -2
  55. package/dist/serve/migrate-release.js +1 -1
  56. package/dist/serve/relay-check.js +7 -8
  57. package/dist/serve/startup-checks.js +12 -22
  58. package/dist/supabase/load-phase.js +3 -1
  59. package/dist/supabase/project-users.js +4 -1
  60. package/dist/users/commands.js +44 -6
  61. package/dist/users/load-auth.js +9 -3
  62. package/dist/users/manage.js +16 -1
  63. package/dist/users/register.js +28 -25
  64. package/dist/users/set-disabled.js +3 -2
  65. package/dist/users/users-api.js +9 -3
  66. package/dist/worker/start-worker.js +7 -4
  67. package/package.json +8 -8
  68. package/skills/protobase/references/features/api-functions.md +1 -0
  69. package/skills/protobase/references/features/build-and-run.md +3 -2
  70. package/skills/protobase/references/features/sign-in-and-accounts.md +2 -1
  71. package/skills/protobase/references/guides/api-functions.md +27 -2
  72. package/skills/protobase/references/guides/deploy.md +2 -2
  73. package/skills/protobase/references/reference/assistant.md +1 -1
  74. package/skills/protobase/references/reference/auth.md +52 -17
  75. package/skills/protobase/references/reference/calls.md +1 -1
  76. package/skills/protobase/references/reference/cli.md +39 -27
  77. package/skills/protobase/references/reference/comments.md +1 -1
  78. package/skills/protobase/references/reference/config/api.md +1 -1
  79. package/skills/protobase/references/reference/config/jobs-and-events.md +1 -1
  80. package/skills/protobase/references/reference/config/sign-in.md +22 -4
  81. package/skills/protobase/references/reference/config.md +1 -1
  82. package/skills/protobase/references/reference/data-config.md +9 -9
  83. package/skills/protobase/references/reference/derived.md +1 -1
  84. package/skills/protobase/references/reference/email.md +2 -2
  85. package/skills/protobase/references/reference/events.md +2 -2
  86. package/skills/protobase/references/reference/history.md +1 -1
  87. package/skills/protobase/references/reference/jobs.md +5 -5
  88. package/skills/protobase/references/reference/live.md +2 -2
  89. package/skills/protobase/references/reference/notifications.md +4 -4
  90. package/skills/protobase/references/reference/personal-access-tokens.md +2 -2
  91. package/skills/protobase/references/reference/realtime-relay.md +1 -1
  92. package/skills/protobase/references/reference/status.md +2 -2
  93. package/skills/protobase/references/reference/supabase-rest.md +1 -1
  94. package/skills/protobase/references/reference/user-tables.md +1 -1
  95. package/skills/protobase/references/reference/webhooks.md +1 -1
  96. package/dist/migration/snapshot/lint-custom.js +0 -23
@@ -3,14 +3,15 @@ import { mailFeedbackOn } from "../config/mail-feedback-config.js";
3
3
  import { unsubscribeOn } from "../config/unsubscribe-config.js";
4
4
  import { userTablesOn } from "../config/user-tables-config.js";
5
5
  import { projectAuth } from "../config/build-project.js";
6
+ import { readOnlyQueriesOn } from "../config/read-only-queries.js";
6
7
  import { openAppDatabase } from "../project/pg-db.js";
7
8
  import pg from "pg";
8
- import { assistantSettings, authStoreTables, configExports } from "@protobase/server";
9
- import { checkStatusOptions } from "@protobase/server/internal";
9
+ import { configExports, neededModules } from "@protobase/server";
10
+ import { checkStatusOptions, storeNames } from "@protobase/server/internal";
10
11
  //#region src/migration/migration-project.ts
11
12
  /**
12
- * A merged project config, for what its database needs: its resources' models, a pool on `url`, its auth, and the
13
- * features that write migrations. `close` ends the pool.
13
+ * A merged project config, for what its database needs: its resources' models, a pool on `url`, its auth, the schema
14
+ * modules it needs, and the features that write migrations. `close` ends the pool.
14
15
  */
15
16
  const migrationProject = async (config, url) => {
16
17
  if (!url) throw new Error("No database: set DATABASE_URL");
@@ -23,27 +24,40 @@ const migrationProject = async (config, url) => {
23
24
  projectAuth(config, database)
24
25
  ]);
25
26
  const exported = configExports(resources);
27
+ const models = exported.resources.map((source) => source.toModel());
28
+ const views = exported.views.map((source) => source.toModel());
29
+ const app = {
30
+ models,
31
+ views,
32
+ jobs,
33
+ signIn: Boolean(auth),
34
+ ...auth && { authStore: storeNames(auth) },
35
+ mailFeedback: mailFeedbackOn(config),
36
+ unsubscribe: unsubscribeOn(config),
37
+ webhooks,
38
+ workflows: config.workflows,
39
+ notifications,
40
+ ...config.status && { status: checkStatusOptions(config.status) },
41
+ calls: config.calls,
42
+ realtime: config.realtime,
43
+ events: config.events,
44
+ userTables: userTablesOn(config),
45
+ readOnlyQueries: readOnlyQueriesOn(config.assistant, process.env)
46
+ };
26
47
  return {
27
- models: exported.resources.map((source) => source.toModel()),
28
- views: exported.views.map((source) => source.toModel()),
48
+ models,
49
+ views,
50
+ /** The schema modules the config needs (`neededModules`). */
51
+ modules: neededModules(app),
29
52
  db: database.db,
30
53
  ...auth && { auth },
31
54
  ...config.events && { events: config.events },
32
55
  ...webhooks && { webhooks },
33
56
  ...config.workflows && { workflows: config.workflows },
34
57
  ...config.realtime && { realtime: config.realtime },
35
- ...config.calls && { calls: config.calls },
36
58
  ...notifications && { notifications },
37
- ...config.status && { status: checkStatusOptions(config.status) },
38
59
  jobs,
39
60
  userTables: userTablesOn(config),
40
- unsubscribe: unsubscribeOn(config),
41
- mailFeedback: mailFeedbackOn(config),
42
- readOnlyQueries: assistantSettings(config.assistant, process.env)?.kind === "built-in",
43
- authTables: auth ? authStoreTables(auth) : {
44
- tables: [],
45
- schemas: []
46
- },
47
61
  close: async () => {
48
62
  await database.db.destroy();
49
63
  }
@@ -0,0 +1,34 @@
1
+ //#region src/migration/older-code/catalog.ts
2
+ const catalogSql = `with ns as (
3
+ select oid, nspname from pg_namespace
4
+ where nspname not in ('pg_catalog', 'information_schema', 'pg_toast') and nspname not like 'pg\\_temp\\_%' and nspname not like 'pg\\_toast\\_temp\\_%'
5
+ ), rel as (
6
+ select c.oid, format('%I.%I', ns.nspname, c.relname) as name, c.relkind::text as kind, obj_description(c.oid, 'pg_class') as comment from pg_class c join ns on ns.oid = c.relnamespace
7
+ where c.relkind in ('r', 'p', 'v', 'm', 'f', 'S')
8
+ ), fn as (
9
+ select p.oid, format('%I.%I(%s)', ns.nspname, p.proname, pg_get_function_identity_arguments(p.oid)) as key, pg_get_function_result(p.oid) as result
10
+ from pg_proc p join ns on ns.oid = p.pronamespace
11
+ )
12
+ select json_build_object(
13
+ 'relations', (select coalesce(json_agg(json_build_object('oid', oid::text, 'name', name, 'kind', kind, 'comment', comment)), '[]') from rel),
14
+ 'columns', (select coalesce(json_agg(json_build_object('relation', a.attrelid::text, 'name', a.attname, 'number', a.attnum, 'type', format_type(a.atttypid, a.atttypmod),
15
+ 'notNull', a.attnotnull, 'hasDefault', a.atthasdef, 'generated', a.attgenerated <> '')), '[]')
16
+ from pg_attribute a join rel on rel.oid = a.attrelid where a.attnum > 0 and not a.attisdropped and rel.kind <> 'S'),
17
+ 'constraints', (select coalesce(json_agg(json_build_object('relation', k.conrelid::text, 'name', k.conname, 'definition', pg_get_constraintdef(k.oid))), '[]')
18
+ from pg_constraint k join rel on rel.oid = k.conrelid where k.contype in ('c', 'u', 'f', 'p', 'x')),
19
+ 'uniqueIndexes', (select coalesce(json_agg(json_build_object('relation', i.indrelid::text, 'name', ic.relname, 'definition', pg_get_indexdef(i.indexrelid))), '[]')
20
+ from pg_index i join rel on rel.oid = i.indrelid join pg_class ic on ic.oid = i.indexrelid where i.indisunique),
21
+ 'functions', (select coalesce(json_agg(json_build_object('key', key, 'result', result)), '[]') from fn),
22
+ 'triggers', (select coalesce(json_agg(json_build_object('relation', t.tgrelid::text, 'function', fn.key, 'enabled', t.tgenabled::text, 'type', t.tgtype::int)), '[]')
23
+ from pg_trigger t join rel on rel.oid = t.tgrelid join fn on fn.oid = t.tgfoid where not t.tgisinternal),
24
+ 'enums', (select coalesce(json_agg(json_build_object('name', format('%I.%I', ns.nspname, t.typname),
25
+ 'labels', (select json_agg(e.enumlabel order by e.enumsortorder) from pg_enum e where e.enumtypid = t.oid))), '[]')
26
+ from pg_type t join ns on ns.oid = t.typnamespace where t.typtype = 'e')
27
+ ) as catalog`;
28
+ /** The database's schema as `contractions` compares it, read in `tx`. */
29
+ const readCatalog = async (tx) => {
30
+ const [row] = await tx.unsafe(catalogSql);
31
+ return row.catalog;
32
+ };
33
+ //#endregion
34
+ export { readCatalog };
@@ -0,0 +1,86 @@
1
+ import { bucketsCommentPrefix, retiredSchema } from "@protobase/server/internal";
2
+ //#region src/migration/older-code/contractions.ts
3
+ const kindNames = {
4
+ r: "table",
5
+ p: "table",
6
+ f: "foreign table",
7
+ v: "view",
8
+ m: "materialized view",
9
+ S: "sequence"
10
+ };
11
+ const holdsRows = /* @__PURE__ */ new Set([
12
+ "r",
13
+ "p",
14
+ "S"
15
+ ]);
16
+ const tables = /* @__PURE__ */ new Set(["r", "p"]);
17
+ const recomputed = (relation) => relation.comment?.startsWith(bucketsCommentPrefix) ?? false;
18
+ const eventBits = [
19
+ [4, "insert"],
20
+ [8, "delete"],
21
+ [16, "update"],
22
+ [32, "truncate"]
23
+ ];
24
+ const watchesRetired = (fn) => fn.startsWith(`${retiredSchema}.`);
25
+ const firedEvents = (triggers) => {
26
+ const events = /* @__PURE__ */ new Map();
27
+ for (const trigger of triggers.filter(({ enabled, function: fn }) => enabled !== "D" && !watchesRetired(fn))) events.set(trigger.function, (events.get(trigger.function) ?? 0) | trigger.type & 60);
28
+ return events;
29
+ };
30
+ const lostTriggers = (relation, before, after) => {
31
+ const now = firedEvents(after);
32
+ return [...firedEvents(before)].flatMap(([fn, had]) => {
33
+ const lost = eventBits.filter(([bit]) => had & bit && !((now.get(fn) ?? 0) & bit)).map(([, event]) => event);
34
+ return lost.length > 0 ? [`drops or disables the trigger calling ${fn} on ${relation.name} for ${lost.join(", ")}`] : [];
35
+ });
36
+ };
37
+ const byRelation = (items, oid) => items.filter((item) => item.relation === oid);
38
+ const columnChanges = (relation, before, after, keepsValues = tables.has(relation.kind)) => before.flatMap((had) => {
39
+ const now = after.find((column) => column.name === had.name);
40
+ const name = `${relation.name}.${had.name}`;
41
+ if (!now) return [`drops or renames column ${name}`];
42
+ if (keepsValues && !had.generated && now.number !== had.number) return [`drops column ${name} and adds it again, losing its values`];
43
+ if (now.type !== had.type) return [`changes the type of column ${name} from ${had.type} to ${now.type}`];
44
+ if (now.notNull && !had.notNull) return [`makes column ${name} not null`];
45
+ if (now.notNull && had.hasDefault && !now.hasDefault && !now.generated) return [`removes the default of the required column ${name}`];
46
+ return [];
47
+ });
48
+ const requiredColumns = (relation, before, after) => after.filter((column) => !before.some((had) => had.name === column.name) && column.notNull && !column.hasDefault && !column.generated).map((column) => `adds the required column ${relation.name}.${column.name} without a default`);
49
+ const newLimits = (relation, what, before, after) => after.filter((limit) => !before.some((had) => had.name === limit.name && had.definition === limit.definition)).map((limit) => `adds the ${what} ${limit.name} to ${relation.name}, which rows written by older code may break`);
50
+ const relationChanges = (before, after, relation) => {
51
+ const now = after.relations.find((found) => found.name === relation.name);
52
+ const kind = kindNames[relation.kind];
53
+ if (!now) return [`drops, renames or moves ${kind} ${relation.name}`];
54
+ if (now.kind !== relation.kind) return [`makes ${kind} ${relation.name} a ${kindNames[now.kind]}`];
55
+ const columns = [byRelation(before.columns, relation.oid), byRelation(after.columns, now.oid)];
56
+ if (now.oid !== relation.oid && recomputed(relation) && recomputed(now)) return columnChanges(relation, ...columns, false);
57
+ if (holdsRows.has(relation.kind) && now.oid !== relation.oid) return [`drops ${kind} ${relation.name} and makes it again, losing its rows`];
58
+ if (!tables.has(relation.kind)) return columnChanges(relation, ...columns);
59
+ const constraints = [byRelation(before.constraints, relation.oid), byRelation(after.constraints, now.oid)];
60
+ const indexes = [byRelation(before.uniqueIndexes, relation.oid), byRelation(after.uniqueIndexes, now.oid)].map((found) => found.filter((index) => !constraints[1].some((constraint) => constraint.name === index.name)));
61
+ return [
62
+ ...columnChanges(relation, ...columns),
63
+ ...requiredColumns(relation, ...columns),
64
+ ...newLimits(relation, "constraint", ...constraints),
65
+ ...newLimits(relation, "unique index", ...indexes),
66
+ ...lostTriggers(relation, byRelation(before.triggers, relation.oid), byRelation(after.triggers, now.oid))
67
+ ];
68
+ };
69
+ const functionChanges = (before, after) => before.functions.flatMap((had) => {
70
+ const now = after.functions.find((fn) => fn.key === had.key);
71
+ if (!now) return [`drops, renames or moves function ${had.key}, or changes its arguments`];
72
+ return now.result === had.result ? [] : [`changes what function ${had.key} returns from ${had.result} to ${now.result}`];
73
+ });
74
+ const enumChanges = (before, after) => before.enums.flatMap((had) => {
75
+ const now = after.enums.find((found) => found.name === had.name);
76
+ if (!now) return [`drops, renames or moves type ${had.name}`];
77
+ return had.labels.filter((label) => !now.labels.includes(label)).map((label) => `removes the value ${label} of type ${had.name}`);
78
+ });
79
+ /** What the change from `before` to `after` takes from older code, one line each; none when it only adds. */
80
+ const contractions = (before, after) => [
81
+ ...before.relations.flatMap((relation) => relationChanges(before, after, relation)),
82
+ ...functionChanges(before, after),
83
+ ...enumChanges(before, after)
84
+ ];
85
+ //#endregion
86
+ export { contractions };
@@ -0,0 +1,55 @@
1
+ import { breaksOlderCodeLine } from "../snapshot/header.js";
2
+ import { contractingRules, contractingSql, lockingRules, squawkReport } from "@protobase/server/internal";
3
+ //#region src/migration/older-code/lint-files.ts
4
+ /** The line that marks a statement Protobase wrote as taking what the migration `<id>` stopped older code from using. */
5
+ const contractLine = /^-- protobase:contract (\S+)[ \t]*$/gm;
6
+ const contractIds = (text) => [...text.matchAll(contractLine)].map((match) => match[1]);
7
+ const handWritten = async (file, text, header) => {
8
+ const marks = "`-- protobase:additive` nor `-- protobase:breaks-older-code`";
9
+ if (header.additive && header.breaksOlderCode) return [`${file} is marked both additive and as breaking older code: keep the one that holds`];
10
+ const problems = contractIds(text).length > 0 ? [`${file} is written by hand and has \`-- protobase:contract\`, which only Protobase's own paths write: mark the file \`-- ${breaksOlderCodeLine}\` instead`] : [];
11
+ if (!header.additive && !header.breaksOlderCode) return [...problems, `${file} is written by hand and says neither ${marks}: put the one that holds among its \`-- protobase:\` lines`];
12
+ if (!header.additive) return problems;
13
+ return [...problems, ...(await contractingSql(text)).map((line) => `${file} is marked additive and ${line}`)];
14
+ };
15
+ /**
16
+ * The problems of the files, one line each: a hand-written one that says neither that it is additive nor that it
17
+ * breaks older code, or says both, or has a statement marked as a contract, or is marked additive while a statement
18
+ * does not only add; and a file Protobase wrote whose contract names no migration before it.
19
+ */
20
+ const lintFiles = async (files) => {
21
+ const problems = [];
22
+ for (const [index, { file, text, header }] of files.entries()) {
23
+ if (!header) continue;
24
+ if (header.custom) {
25
+ problems.push(...await handWritten(file, text, header));
26
+ continue;
27
+ }
28
+ const earlier = new Set(files.slice(0, index).flatMap((before) => before.header ? [before.header.id] : []));
29
+ problems.push(...contractIds(text).filter((id) => !earlier.has(id)).map((id) => `${file} has \`-- protobase:contract ${id}\`, which names no migration before it`));
30
+ }
31
+ return problems;
32
+ };
33
+ const markedAt = (lines, line) => {
34
+ for (let at = line - 1; at >= 0 && !lines[at].trimEnd().endsWith(";"); at--) if (lines[at].startsWith("-- protobase:contract ")) return true;
35
+ return false;
36
+ };
37
+ /**
38
+ * What the lint reports of the files Protobase wrote or that are written by hand, without failing: a statement that
39
+ * holds a lock blocking reads while it scans or rewrites a table, and one in a file Protobase wrote that takes from
40
+ * older code without a contract mark, which `protobase migration` checked against the database it was written from.
41
+ */
42
+ const fileWarnings = (files) => {
43
+ const linted = files.filter(({ header }) => header !== void 0).map(({ file, text }) => ({
44
+ label: file,
45
+ sql: text
46
+ }));
47
+ return squawkReport(linted).flatMap(({ step, rule, message, line }) => {
48
+ const found = files.find(({ file }) => file === step);
49
+ const where = `${step} line ${line + 1}`;
50
+ const unmarked = !found.header.custom && contractingRules.includes(rule) && !markedAt(found.text.split("\n"), line);
51
+ return [...lockingRules.includes(rule) ? [`${where} holds a lock that blocks reads while it scans or rewrites the table (${rule}): ${message}`] : [], ...unmarked ? [`${where} takes from older code without \`-- protobase:contract\` (${rule}): ${message}`] : []];
52
+ });
53
+ };
54
+ //#endregion
55
+ export { fileWarnings, lintFiles };
@@ -0,0 +1,9 @@
1
+ //#region src/migration/older-code/refusal.ts
2
+ /** The way through for a change that breaks older code which no path of Protobase's writes. */
3
+ const breaksOlderCodeHint = "To make it anyway, write it by hand with `protobase migration --custom <name>` and put `-- protobase:breaks-older-code` among its `-- protobase:` lines: the version before then refuses to start on the database, and rolling back to it is blocked";
4
+ /** The refusal of a migration that would take from older code what `found` names, by section. */
5
+ const olderCodeRefusal = (found) => `The migration would break the code still running while it deploys, and the version before it once rolled back: ${found.map(({ name, found: lines }) => `${name} ${lines.join(", ")}`).join("; ")}. ${breaksOlderCodeHint}.`;
6
+ /** The lines under the intro of a file whose own paths' steps take what `found` names from older code, each by its section. */
7
+ const breaksOlderCodeNote = (found) => `-- It breaks older code: once it is applied, the version before refuses to start on the database, and rolling back to it is blocked.\n${found.map((line) => `-- ${line}.`).join("\n")}\n`;
8
+ //#endregion
9
+ export { breaksOlderCodeHint, breaksOlderCodeNote, olderCodeRefusal };
@@ -0,0 +1,58 @@
1
+ import { readCatalog } from "./catalog.js";
2
+ import { contractions } from "./contractions.js";
3
+ import { forceSetting } from "@protobase/server/internal";
4
+ import postgres from "postgres";
5
+ //#region src/migration/older-code/trial.ts
6
+ const rolledBack = Symbol("rolled back");
7
+ const lockTimeout = "10s";
8
+ const lockNotAvailable = "55P03";
9
+ /**
10
+ * Applies `sections` to the database at `url` in one transaction it rolls back, reading its schema before them and
11
+ * after each, so nothing changes: what the whole file takes from older code, each line under the sections that take
12
+ * it. Sections that take nothing are
13
+ * left out.
14
+ */
15
+ const trialContractions = async (url, sections) => {
16
+ const sql = postgres(url, {
17
+ max: 1,
18
+ onnotice: () => {}
19
+ });
20
+ const found = [];
21
+ try {
22
+ await sql.begin(async (tx) => {
23
+ await tx.unsafe(`set local lock_timeout = '${lockTimeout}'`);
24
+ await tx.unsafe(`select set_config('${forceSetting}', 'true', true)`);
25
+ const before = await readCatalog(tx);
26
+ const own = [];
27
+ const sinceStart = [];
28
+ let previous = before;
29
+ for (const section of sections) {
30
+ await tx.unsafe(section.text);
31
+ const now = await readCatalog(tx);
32
+ own.push(contractions(previous, now));
33
+ sinceStart.push(contractions(before, now));
34
+ previous = now;
35
+ }
36
+ const whole = sinceStart.at(-1) ?? [];
37
+ const firstAt = (line) => sinceStart.findIndex((lines) => lines.includes(line));
38
+ sections.forEach(({ name }, index) => {
39
+ const lines = whole.filter((line) => own[index].includes(line) || !own.some((lines) => lines.includes(line)) && firstAt(line) === index);
40
+ if (lines.length > 0) found.push({
41
+ name,
42
+ found: lines
43
+ });
44
+ });
45
+ throw rolledBack;
46
+ });
47
+ } catch (error) {
48
+ if (error === rolledBack) return found;
49
+ if (!(error instanceof postgres.PostgresError)) throw error;
50
+ const reason = error.code === lockNotAvailable ? "another session held a lock it needs for longer than 10s" : `Postgres refused it (${error.code})`;
51
+ throw new Error(`The migration was applied to DATABASE_URL and rolled back, to read what it changes, and failed: ${reason}. Apply the project's migrations to the database first and stop what holds its locks, or unset DATABASE_URL to write only the auth store's steps`, { cause: error });
52
+ } finally {
53
+ await sql.end();
54
+ }
55
+ throw new Error("Not implemented: the trial transaction ends by rolling back");
56
+ };
57
+ //#endregion
58
+ export { trialContractions };
@@ -1,111 +1,15 @@
1
- import { appRelayChannels, 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 { ownedDefinitionsMigration } from "@protobase/server";
2
2
  //#region src/migration/parts.ts
3
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.
4
+ * Every feature the project's config enables but the auth store and the schema modules, which the snapshot holds, in
5
+ * the order their statements are written, after theirs.
6
6
  */
7
7
  const migrationParts = (project) => {
8
- const comments = project.models.some((model) => model.comments);
9
- const aiFields = project.models.some((model) => Object.values(model.fields).some((field) => field.ai));
10
- const feedback = project.mailFeedback ? [mailFeedbackResource.toModel()] : [];
11
- const captured = [...project.models, ...feedback];
12
- const relayChannels = appRelayChannels(project.realtime?.relay, {
13
- views: project.views,
14
- models: project.models,
15
- signIn: Boolean(project.auth)
16
- });
17
- return [
18
- ...project.jobs.length > 0 || captured.some(capturedBy(captured)) || comments || aiFields || project.models.some(hasBuckets) || project.webhooks || project.workflows || project.notifications || relayChannels ? [{
19
- name: "jobs",
20
- title: "The jobs schema this version of Protobase needs",
21
- sql: () => jobsSchemaMigration(project.db)
22
- }] : [],
23
- ...project.mailFeedback ? [{
24
- name: "mail_feedback",
25
- title: "The table of the bounces and complaints of the mail the app sends",
26
- sql: () => mailFeedbackMigration(project.db)
27
- }] : [],
28
- {
29
- name: "changes",
30
- title: "The change capture the resources' events and history need",
31
- sql: () => changesMigration(project.db, captured, project.events, feedback.map((model) => model.name))
32
- },
33
- {
34
- name: "computed",
35
- title: "The columns of the resources' rollup and formula fields, the triggers that keep the rollups, and the tables and refresh functions of their time rollups",
36
- sql: () => computedMigration(project.db, project.models)
37
- },
38
- ...project.readOnlyQueries ? [{
39
- name: "query",
40
- title: "The role the assistant's read-only queries run as, which reads only the resources' tables",
41
- sql: () => queryRunnerMigration(project.db, project.models, project.authTables)
42
- }] : [],
43
- {
44
- name: "derived",
45
- title: "The state of the resources' derived values and what they read",
46
- sql: () => derivedMigration(project.db, project.models)
47
- },
48
- ...comments ? [{
49
- name: "comments",
50
- title: "The comments table of the resources with comments",
51
- sql: () => commentsMigration(project.db)
52
- }] : [],
53
- ...project.webhooks ? [{
54
- name: "webhooks",
55
- title: "The webhook subscriptions of webhooks",
56
- sql: () => webhooksMigration(project.db, project.webhooks, project.events)
57
- }] : [],
58
- ...project.workflows ? [{
59
- name: "workflows",
60
- title: "The workflows, their versions, runs and steps",
61
- sql: () => workflowsMigration(project.db, project.workflows)
62
- }] : [],
63
- ...project.notifications && !(project.notifications.store && project.notifications.historyStore) ? [{
64
- name: "notifications",
65
- title: "The tables of notifications",
66
- sql: () => notificationsMigration(project.db, project.notifications, project.auth)
67
- }] : [],
68
- ...project.status ? [{
69
- name: "status",
70
- title: "The statuses table of people's own status",
71
- sql: () => statusMigration(project.db, project.status, project.auth)
72
- }] : [],
73
- ...project.unsubscribe ? [{
74
- name: "unsubscribes",
75
- title: "The table of who unsubscribed from which topic of the bulk mail",
76
- sql: () => unsubscribesMigration(project.db)
77
- }] : [],
78
- ...project.calls ? [{
79
- name: "calls",
80
- title: "The calls on records, who is in them, whom they ring, their guests, and the signals between the processes serving the app",
81
- sql: () => callsMigration(project.db, project.events)
82
- }] : [],
83
- ...relayed(project.realtime) ? [{
84
- name: "realtime_relay",
85
- title: "The relay of Realtime broadcasts and presence between the processes serving the app",
86
- sql: () => realtimeRelayMigration(project.db)
87
- }] : [],
88
- ...project.userTables ? [{
89
- name: "user_tables",
90
- title: "The schemas of the tables users add and of their definitions, and pg_trgm",
91
- sql: () => userTablesMigration(project.db)
92
- }] : [],
93
- ...project.userTables ? [{
94
- name: "owned_definitions",
95
- title: "The delete of the definitions of user tables that resources in code own now",
96
- sql: () => ownedDefinitionsMigration(project.db, project.models)
97
- }] : [],
98
- ...relayChannels ? [{
99
- name: "relay",
100
- title: "The trigger that closes a deleted sign-in session's sockets on the realtime relay, and realtime.members with the triggers that keep it from the channel records that list their members",
101
- sql: ({ authWritten }) => relayMigration(project.db, project.auth, authWritten, relayChannels, project.models)
102
- }] : [],
103
- ...sqlSends(project.realtime) ? [{
104
- name: "channel_sends",
105
- title: "SQL's broadcasts to the record channels, channels.send()",
106
- sql: () => channelSendsMigration(project.db)
107
- }] : []
108
- ];
8
+ return [...project.userTables ? [{
9
+ name: "owned_definitions",
10
+ title: "The delete of the definitions of user tables that resources in code own now",
11
+ sql: () => ownedDefinitionsMigration(project.db, project.models)
12
+ }] : []];
109
13
  };
110
14
  //#endregion
111
15
  export { migrationParts };
@@ -2,8 +2,26 @@
2
2
  /** The `.after.sql` beside the migration `file`. */
3
3
  const afterFileOf = (file) => file.replace(/\.sql$/, ".after.sql");
4
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 !== "");
5
+ const dollarTag = /\$(?:[A-Za-z_][\w]*)?\$/g;
6
+ /**
7
+ * Its statements: each ends with a semicolon at the end of a line outside a dollar-quoted body, so a `do` block whose
8
+ * own statements end lines is one statement. Comment lines between them are dropped.
9
+ */
10
+ const afterStatements = (text) => {
11
+ const statements = [];
12
+ let lines = [];
13
+ let open;
14
+ for (const line of text.replaceAll("\r\n", "\n").split("\n")) {
15
+ if (open === void 0 && /^\s*--/.test(line)) continue;
16
+ for (const [tag] of line.matchAll(dollarTag)) open = open === void 0 ? tag : open === tag ? void 0 : open;
17
+ lines.push(line);
18
+ if (open !== void 0 || !/;[ \t]*$/.test(line)) continue;
19
+ statements.push(lines.join("\n").replace(/;[ \t]*$/, ""));
20
+ lines = [];
21
+ }
22
+ statements.push(lines.join("\n"));
23
+ return statements.map((statement) => statement.trim()).filter((statement) => statement !== "");
24
+ };
7
25
  const identifier = "(?:\"(?:[^\"]|\"\")+\"|[A-Za-z_][\\w$]*)";
8
26
  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
27
  /** The index a statement builds concurrently, as Postgres names it; `undefined` for any other statement. */
@@ -20,12 +20,15 @@ const loadAuthTarget = async (opts) => {
20
20
  };
21
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, []);
22
22
  const registerMigration = (program) => {
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) => {
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").option("--force", "turn a sign-in module on again even while the tables it kept off hold rows, which come back into use").action(async (connection, opts) => {
24
24
  loadNearestEnvFile(process.cwd());
25
25
  const { migrateProject } = await import("./migrate-project.js");
26
- await migrateProject(process.cwd(), () => resolveConnectionUrl(connection, opts.env), out, Boolean(opts.plan));
26
+ await migrateProject(process.cwd(), () => resolveConnectionUrl(connection, opts.env), out, {
27
+ plan: Boolean(opts.plan),
28
+ force: Boolean(opts.force)
29
+ });
27
30
  });
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) => {
31
+ const migration = folderOptions(program.command("migration").description("Write what the config and this version of Protobase need beyond protobase.snapshot.json as the project's next numbered SQL migration, and rewrite the snapshot").option("--custom <name>", "write an empty numbered migration to fill by hand, and make the snapshot end at it").option("--record-config", "with --custom: record the config's auth store names in the snapshot, which the file makes the store match").option("--after", "with --custom: write an empty .after.sql beside it too, for statements that cannot run in a transaction, such as create index concurrently").option("--off <choice>", "what becomes of the tables of a sign-in module the config turns off, without asking: keep").option("--force", "write the migration that turns a kept sign-in module on again even while its tables hold rows")).action(async (opts) => {
29
32
  if (opts.recordConfig && !opts.custom) throw new Error("--record-config goes with --custom <name>");
30
33
  if (opts.after && !opts.custom) throw new Error("--after goes with --custom <name>");
31
34
  const { config, auth } = await loadAuthTarget(opts);
@@ -45,26 +48,41 @@ const registerMigration = (program) => {
45
48
  out(`wrote ${path.relative(process.cwd(), file)}${opts.after ? ", its .after.sql" : ""} and protobase.snapshot.json: write its statements\n`);
46
49
  return;
47
50
  }
48
- const [{ migrationProject }, { migrationParts }, { runMigration }, { migrationSummary }] = await Promise.all([
51
+ const [{ migrationProject }, { configModules }, { schemaModules }, { migrationParts }, { runMigration }, { migrationSummary }, { offChoice }, { trialContractions }, prompts] = await Promise.all([
49
52
  import("./migration-project.js"),
53
+ import("../config/project-modules.js"),
54
+ import("@protobase/server/internal"),
50
55
  import("./parts.js"),
51
56
  import("./snapshot/run-migration.js"),
52
- import("./summary.js")
57
+ import("./summary.js"),
58
+ import("./snapshot/off-choice.js"),
59
+ import("./older-code/trial.js"),
60
+ import("./snapshot/terminal-prompts.js")
53
61
  ]);
62
+ const off = offChoice(opts.off);
54
63
  const url = process.env.DATABASE_URL;
55
64
  const project = url ? await migrationProject(config, url) : void 0;
56
65
  try {
66
+ const asks = process.stdin.isTTY ? prompts.terminalPrompts() : void 0;
67
+ const database = project && url ? {
68
+ url,
69
+ parts: migrationParts(project),
70
+ contractions: (sections) => trialContractions(url, sections),
71
+ readModule: (id, input) => schemaModules[id].read(project.db, input)
72
+ } : void 0;
73
+ const modules = project ? project.modules : await configModules(config);
57
74
  const file = await runMigration({
58
75
  projectDir: process.cwd(),
59
76
  dir,
60
77
  auth,
61
- database: project && url ? {
62
- url,
63
- parts: migrationParts(project)
64
- } : void 0,
78
+ modules,
79
+ database,
65
80
  protobaseVersion,
66
- newId: randomUUID
67
- });
81
+ newId: randomUUID,
82
+ ...off && { off },
83
+ force: Boolean(opts.force),
84
+ ...asks?.prompts
85
+ }).finally(() => asks?.close());
68
86
  out(migrationSummary(file, process.cwd(), {
69
87
  hasAuth: Boolean(auth),
70
88
  compared: Boolean(project)
@@ -74,10 +92,17 @@ const registerMigration = (program) => {
74
92
  }
75
93
  process.exit(0);
76
94
  });
77
- 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) => {
78
- const { auth } = await loadAuthTarget(opts);
79
- const { checkMigrations } = await import("./snapshot/check.js");
80
- const found = await checkMigrations(process.cwd(), path.resolve(opts.dir), auth);
95
+ folderOptions(migration.command("check").description("Report, writing nothing, what keeps the migrations and protobase.snapshot.json from matching the config, and warn of statements that lock reads or take from older code unmarked; exit code 1 when anything but a warning is found, for CI")).action(async (opts) => {
96
+ const { config, auth } = await loadAuthTarget(opts);
97
+ const [{ checkMigrations }, { fileWarnings }, { readMigrationFiles }, { configModules }] = await Promise.all([
98
+ import("./snapshot/check.js"),
99
+ import("./older-code/lint-files.js"),
100
+ import("./snapshot/migration-files.js"),
101
+ import("../config/project-modules.js")
102
+ ]);
103
+ const dir = path.resolve(opts.dir);
104
+ const found = await checkMigrations(process.cwd(), dir, auth, await configModules(config));
105
+ out(fileWarnings(await readMigrationFiles(dir)).map((line) => `warning: ${line}\n`).join(""));
81
106
  if (found.length === 0) {
82
107
  out("the migrations and protobase.snapshot.json match the config\n");
83
108
  return;
@@ -85,16 +110,16 @@ const registerMigration = (program) => {
85
110
  out(found.map((line) => `${line}\n`).join(""));
86
111
  process.exitCode = 1;
87
112
  });
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");
113
+ folderOptions(migration.command("baseline").description("Describe in protobase.snapshot.json, from DATABASE_URL read once, the auth store of a project whose auth migrations came before it, and the schema modules it does not record yet, with a numbered migration that changes nothing")).action(async (opts) => {
114
+ const { config, auth } = await loadAuthTarget(opts);
91
115
  const url = process.env.DATABASE_URL;
92
116
  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");
117
+ const [{ writeBaseline }, { configModules }] = await Promise.all([import("./baseline/write-baseline.js"), import("../config/project-modules.js")]);
94
118
  const file = await writeBaseline({
95
119
  projectDir: process.cwd(),
96
120
  dir: path.resolve(opts.dir),
97
121
  auth,
122
+ modules: await configModules(config),
98
123
  url,
99
124
  protobaseVersion,
100
125
  newId: randomUUID
@@ -3,12 +3,14 @@ import { modelHash, recordsRuntimeModel, runtimeModel, storeNamesList } from "@p
3
3
  //#region src/migration/release/release-record.ts
4
4
  /**
5
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.
6
+ * does: the model this release reads with the project's auth and schema modules, additive when only the auth store's
7
+ * steps, which only add, and schema modules' statements the code before runs on apply. `undefined` when the release
8
+ * reads nothing of the record, or the record holds its model already and no step applies.
8
9
  */
9
- const releaseRecord = async (auth, steps, protobaseVersion, id) => {
10
- if (steps.length === 0 && await recordsRuntimeModel(auth)) return;
11
- const model = runtimeModel(auth);
10
+ const releaseRecord = async (project, steps, protobaseVersion, id) => {
11
+ const model = runtimeModel(project.auth, project.modules);
12
+ if (!model.auth && !model.modules) return;
13
+ if (steps.length === 0 && await recordsRuntimeModel(project.db, model)) return;
12
14
  const row = {
13
15
  id,
14
16
  number: null,
@@ -16,8 +18,8 @@ const releaseRecord = async (auth, steps, protobaseVersion, id) => {
16
18
  protobaseVersion,
17
19
  model,
18
20
  modelHash: modelHash(model),
19
- physical: { auth: storeNamesList(model.auth) },
20
- additive: steps.every(({ name }) => name === "auth"),
21
+ physical: model.auth ? { auth: storeNamesList(model.auth) } : {},
22
+ additive: steps.every(({ name, breaks }) => name === "auth" || breaks !== void 0 && breaks.length === 0),
21
23
  completed: true
22
24
  };
23
25
  return {