@protobase/cli 0.26.0 → 0.26.2
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/package.js +1 -1
- package/dist/supabase/dump-phase.js +65 -20
- package/dist/supabase/extensions.js +17 -12
- package/dist/supabase/import-plan.js +37 -0
- package/dist/supabase/import-state.js +5 -1
- package/dist/supabase/load-phase.js +6 -4
- package/dist/supabase/load-script.js +4 -2
- package/dist/supabase/replay.js +15 -0
- package/dist/supabase/report.js +19 -3
- package/dist/supabase/rewrite.js +38 -9
- package/dist/supabase/schema-migration.js +7 -4
- package/dist/supabase/source-facts.js +71 -10
- package/dist/supabase/target-extensions.js +36 -0
- package/dist/supabase/webhooks.js +43 -0
- package/package.json +6 -6
- package/skills/protobase/SKILL.md +1 -1
- package/skills/protobase/references/reference/cli.md +2 -2
- package/skills/protobase/references/reference/supabase-realtime.md +23 -3
package/dist/package.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { nextMigrationName } from "../auth/migration-file.js";
|
|
2
2
|
import { connect } from "../db/connect.js";
|
|
3
3
|
import { checkoutMarkers, edgeFunctions } from "./checkout.js";
|
|
4
|
-
import {
|
|
4
|
+
import { importPlan, probedExtensions } from "./import-plan.js";
|
|
5
5
|
import { importState } from "./import-state.js";
|
|
6
6
|
import { runPgTool } from "./pg-tools.js";
|
|
7
|
+
import { replayScript } from "./replay.js";
|
|
7
8
|
import { schemaMigration } from "./schema-migration.js";
|
|
8
|
-
import { appSchemas, cronJobs, databaseMarkers, dumpedTables, extensions, httpTriggers, platformMigrationTables, realtimeTables, tablesSize, vaultSecrets } from "./source-facts.js";
|
|
9
|
+
import { appSchemas, cronJobs, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets } from "./source-facts.js";
|
|
9
10
|
import { ensureApiRoles, existingTables } from "./target-checks.js";
|
|
11
|
+
import { creatableExtensions } from "./target-extensions.js";
|
|
10
12
|
import path from "node:path";
|
|
11
13
|
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
12
14
|
import postgres from "postgres";
|
|
@@ -18,21 +20,60 @@ const checkSupabase = async (sql) => {
|
|
|
18
20
|
if (missing.length > 0) throw new Error(`The source database is not a Supabase database: it lacks the ${missing.join(" and ")}`);
|
|
19
21
|
return markers;
|
|
20
22
|
};
|
|
21
|
-
/**
|
|
22
|
-
const
|
|
23
|
+
/** Which of `names` the project's database lets the importing role create. */
|
|
24
|
+
const targetExtensions = async (url, names) => {
|
|
25
|
+
const sql = postgres(url, {
|
|
26
|
+
max: 1,
|
|
27
|
+
onnotice: () => {}
|
|
28
|
+
});
|
|
29
|
+
try {
|
|
30
|
+
return await creatableExtensions(sql, names);
|
|
31
|
+
} finally {
|
|
32
|
+
await sql.end();
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* What the source holds, read in the transaction whose snapshot the dumps take, so all of it is of one moment, with
|
|
37
|
+
* what the import does with it on the project's database at `targetUrl`; and the replay of what the dump cannot carry.
|
|
38
|
+
*/
|
|
39
|
+
const readSource = async (sql, targetUrl) => {
|
|
23
40
|
const schemas = await appSchemas(sql);
|
|
24
41
|
const tables = await dumpedTables(sql, schemas);
|
|
25
|
-
const sourceExtensions =
|
|
42
|
+
const sourceExtensions = await extensions(sql);
|
|
43
|
+
const triggers = await httpTriggers(sql, schemas);
|
|
44
|
+
const plan = importPlan({
|
|
45
|
+
extensions: sourceExtensions,
|
|
46
|
+
httpTriggers: triggers
|
|
47
|
+
}, await targetExtensions(targetUrl, probedExtensions(sourceExtensions)));
|
|
48
|
+
const secrets = plan.vault ? await vaultSecretValues(sql) : void 0;
|
|
49
|
+
const queues = await pgmqQueues(sql);
|
|
50
|
+
const replayed = plan.queues ? (queues ?? []).filter((queue) => !queue.partitioned) : [];
|
|
26
51
|
return {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
52
|
+
manifest: {
|
|
53
|
+
schemas,
|
|
54
|
+
tables,
|
|
55
|
+
bytes: await tablesSize(sql, tables),
|
|
56
|
+
cronJobs: await cronJobs(sql),
|
|
57
|
+
vaultSecrets: await vaultSecrets(sql),
|
|
58
|
+
vaultReplayed: secrets !== void 0,
|
|
59
|
+
queues: queues?.map((queue) => ({
|
|
60
|
+
name: queue.name,
|
|
61
|
+
partitioned: queue.partitioned,
|
|
62
|
+
messages: queue.messages.length
|
|
63
|
+
})),
|
|
64
|
+
queuesReplayed: plan.queues && queues !== void 0,
|
|
65
|
+
realtimeTables: await realtimeTables(sql),
|
|
66
|
+
extensionsLeftOut: plan.leftOut,
|
|
67
|
+
httpTriggers: triggers,
|
|
68
|
+
httpSent: plan.httpSent,
|
|
69
|
+
hypertables: await hypertables(sql, schemas),
|
|
70
|
+
routinesLeftOut: await routinesIn(sql, schemas, plan.missing.languages)
|
|
71
|
+
},
|
|
72
|
+
plan,
|
|
73
|
+
replay: replayScript({
|
|
74
|
+
secrets: secrets ?? [],
|
|
75
|
+
queues: replayed
|
|
76
|
+
})
|
|
36
77
|
};
|
|
37
78
|
};
|
|
38
79
|
/** Fails unless the target can take the schema migration: makes the API roles it lacks, and finds no table in the way. */
|
|
@@ -54,8 +95,9 @@ const checkTarget = async (url, tables) => {
|
|
|
54
95
|
const pattern = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
55
96
|
/**
|
|
56
97
|
* The import's first run: dumps the Supabase database's schemas and data as of one snapshot, writes the schema as
|
|
57
|
-
* the project's next migration,
|
|
58
|
-
*
|
|
98
|
+
* the project's next migration, with the extensions the project's database can create, and keeps the data dump, the
|
|
99
|
+
* replay of Vault's secrets and pgmq's queues and what the report needs in `supabase-import/` for the run that loads
|
|
100
|
+
* it, once the project's migrations are applied.
|
|
59
101
|
*/
|
|
60
102
|
const runDumpPhase = async (options, out) => {
|
|
61
103
|
const checkout = checkoutMarkers(options.projectDir);
|
|
@@ -68,7 +110,7 @@ const runDumpPhase = async (options, out) => {
|
|
|
68
110
|
await reserved`begin isolation level repeatable read read only`;
|
|
69
111
|
const [exported] = await reserved`select pg_export_snapshot() as snapshot`;
|
|
70
112
|
const snapshot = exported.snapshot;
|
|
71
|
-
const source = await readSource(reserved);
|
|
113
|
+
const { manifest: source, plan, replay } = await readSource(reserved, options.targetUrl);
|
|
72
114
|
const created = await checkTarget(options.targetUrl, source.tables);
|
|
73
115
|
if (created.length > 0) out(`created the roles ${created.join(", ")} in the project's database\n`);
|
|
74
116
|
await state.prepare();
|
|
@@ -88,24 +130,27 @@ const runDumpPhase = async (options, out) => {
|
|
|
88
130
|
`--file=${state.data}`
|
|
89
131
|
]);
|
|
90
132
|
await reserved`commit`;
|
|
133
|
+
if (replay) await state.writeReplay(replay);
|
|
91
134
|
const migration = schemaMigration(await readFile(schemaFile, "utf8"), {
|
|
92
135
|
schemas: source.schemas,
|
|
93
|
-
extensions:
|
|
136
|
+
extensions: plan.extensions,
|
|
137
|
+
webhooks: plan.webhooks,
|
|
138
|
+
missing: plan.missing
|
|
94
139
|
});
|
|
95
140
|
await rm(schemaFile);
|
|
96
141
|
await mkdir(options.migrationsDir, { recursive: true });
|
|
97
142
|
const file = nextMigrationName(await readdir(options.migrationsDir), "supabase_schema");
|
|
98
143
|
await writeFile(path.join(options.migrationsDir, file), migration.text, { flag: "wx" });
|
|
99
|
-
const { trusted, ...facts } = source;
|
|
100
144
|
await state.writeManifest({
|
|
101
145
|
migration: file,
|
|
102
146
|
leftOut: migration.leftOut,
|
|
103
147
|
checkout,
|
|
104
148
|
functions: await edgeFunctions(options.projectDir),
|
|
105
|
-
...
|
|
149
|
+
...source
|
|
106
150
|
});
|
|
107
151
|
out(`wrote ${path.relative(options.projectDir, path.join(options.migrationsDir, file))}, the schemas ${source.schemas.join(", ")}\n`);
|
|
108
152
|
out(`dumped ${source.tables.length} tables' data into ${path.relative(options.projectDir, state.data)}, which git ignores\n`);
|
|
153
|
+
if (replay) out(`kept Vault's secrets and pgmq's queues to make again in ${path.relative(options.projectDir, state.replay)}, which git ignores\n`);
|
|
109
154
|
out("next: apply the migration with the project's migrations, then run `protobase import supabase` again to load the data\n");
|
|
110
155
|
} finally {
|
|
111
156
|
reserved.release();
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
//#region src/supabase/extensions.ts
|
|
2
2
|
/**
|
|
3
3
|
* Extensions every Supabase database has for the platform itself (its GraphQL API, Vault, statistics), which an app's
|
|
4
|
-
* schema does not use; pg_cron and pg_net are not among them, since the report lists what uses them.
|
|
4
|
+
* schema does not use; pg_cron and pg_net are not among them, since the report lists what uses them. Vault comes over
|
|
5
|
+
* apart, with the secrets it holds.
|
|
5
6
|
*/
|
|
6
7
|
const platformExtensions = /* @__PURE__ */ new Set([
|
|
7
8
|
"plpgsql",
|
|
@@ -10,21 +11,25 @@ const platformExtensions = /* @__PURE__ */ new Set([
|
|
|
10
11
|
"pgsodium",
|
|
11
12
|
"pg_stat_statements"
|
|
12
13
|
]);
|
|
14
|
+
const appExtensions = (extensions) => extensions.filter((extension) => !platformExtensions.has(extension.name));
|
|
15
|
+
/** Extensions that are a language of the same name, which Supabase dropped after Postgres 15: its functions need converting. */
|
|
16
|
+
const languageExtensions = [
|
|
17
|
+
"plv8",
|
|
18
|
+
"plls",
|
|
19
|
+
"plcoffee"
|
|
20
|
+
];
|
|
13
21
|
/**
|
|
14
|
-
* The app's extensions, by what the import does with them:
|
|
15
|
-
* migration creates
|
|
22
|
+
* The app's extensions, by what the import does with them: those the project's database can create (`creatable`, as
|
|
23
|
+
* it answered), the migration creates in the schema they had; the report lists the others.
|
|
16
24
|
*/
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
untrusted: app.filter((extension) => !extension.trusted)
|
|
22
|
-
};
|
|
23
|
-
};
|
|
25
|
+
const sortExtensions = (extensions, creatable) => ({
|
|
26
|
+
created: extensions.filter((extension) => creatable.has(extension.name)),
|
|
27
|
+
leftOut: extensions.filter((extension) => !creatable.has(extension.name))
|
|
28
|
+
});
|
|
24
29
|
const quoted = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
25
30
|
/** The statements that create `extensions` where the dump expects them. */
|
|
26
31
|
const createExtensions = (extensions) => {
|
|
27
|
-
return [...[...new Set(extensions.map((extension) => extension.schema))].filter((schema) => schema !== "public").map((schema) => `CREATE SCHEMA IF NOT EXISTS ${quoted(schema)};\n`), ...extensions.map((extension) => `CREATE EXTENSION IF NOT EXISTS ${quoted(extension.name)} WITH SCHEMA ${quoted(extension.schema)};\n`)].join("");
|
|
32
|
+
return [...[...new Set(extensions.map((extension) => extension.schema))].filter((schema) => schema !== "public" && schema !== "pg_catalog").map((schema) => `CREATE SCHEMA IF NOT EXISTS ${quoted(schema)};\n`), ...extensions.map((extension) => `CREATE EXTENSION IF NOT EXISTS ${quoted(extension.name)} WITH SCHEMA ${quoted(extension.schema)};\n`)].join("");
|
|
28
33
|
};
|
|
29
34
|
//#endregion
|
|
30
|
-
export { appExtensions, createExtensions };
|
|
35
|
+
export { appExtensions, createExtensions, languageExtensions, sortExtensions };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { appExtensions, languageExtensions, sortExtensions } from "./extensions.js";
|
|
2
|
+
import { isWebhook } from "./webhooks.js";
|
|
3
|
+
//#region src/supabase/import-plan.ts
|
|
4
|
+
/**
|
|
5
|
+
* The schemas of timescaledb's own functions, which a hypertable's insert-blocking trigger calls. The dump restores a
|
|
6
|
+
* hypertable as a plain table, which that trigger would keep empty, so it is always left out.
|
|
7
|
+
*/
|
|
8
|
+
const timescaleSchemas = ["_timescaledb_functions", "_timescaledb_internal"];
|
|
9
|
+
/** The extensions to ask the project's database about: the app's, and Vault where the source has it. */
|
|
10
|
+
const probedExtensions = (extensions) => [...appExtensions(extensions).map((extension) => extension.name), ...extensions.filter((extension) => extension.name === "supabase_vault").map((extension) => extension.name)];
|
|
11
|
+
/**
|
|
12
|
+
* What the import carries over to the project's database, given the extensions it said it may create (`creatable`):
|
|
13
|
+
* the extensions the migration creates, and the ones it leaves out; whether Vault's secrets and pgmq's queues are made
|
|
14
|
+
* again; whether Database Webhooks get their shim; and what the dump's rewrite leaves out for want of an extension.
|
|
15
|
+
*/
|
|
16
|
+
const importPlan = (source, creatable) => {
|
|
17
|
+
const sorted = sortExtensions(appExtensions(source.extensions), creatable);
|
|
18
|
+
const created = (name) => sorted.created.some((extension) => extension.name === name);
|
|
19
|
+
const leftOut = (name) => sorted.leftOut.some((extension) => extension.name === name);
|
|
20
|
+
const vault = source.extensions.filter((extension) => extension.name === "supabase_vault" && creatable.has(extension.name));
|
|
21
|
+
const webhooks = created("pg_net") && source.httpTriggers.some(isWebhook);
|
|
22
|
+
const missing = {
|
|
23
|
+
triggerSchemas: [...webhooks ? [] : ["supabase_functions"], ...timescaleSchemas],
|
|
24
|
+
languages: languageExtensions.filter(leftOut)
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
extensions: [...sorted.created, ...vault],
|
|
28
|
+
leftOut: sorted.leftOut,
|
|
29
|
+
vault: vault.length > 0,
|
|
30
|
+
queues: created("pgmq"),
|
|
31
|
+
webhooks,
|
|
32
|
+
httpSent: created("pg_net"),
|
|
33
|
+
missing
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
//#endregion
|
|
37
|
+
export { importPlan, probedExtensions };
|
|
@@ -4,12 +4,14 @@ import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
|
4
4
|
//#region src/supabase/import-state.ts
|
|
5
5
|
/**
|
|
6
6
|
* The project's folder for an import in progress, kept out of git: the data dump, which holds the users' password
|
|
7
|
-
* hashes and every row,
|
|
7
|
+
* hashes and every row, and the replay of Vault's secrets and pgmq's queues, which holds the secrets' values, each
|
|
8
|
+
* readable by its owner only until the load deletes it; the manifest; and the report.
|
|
8
9
|
*/
|
|
9
10
|
const importState = (projectDir) => {
|
|
10
11
|
const dir = path.join(projectDir, "supabase-import");
|
|
11
12
|
const files = {
|
|
12
13
|
data: path.join(dir, "data.sql"),
|
|
14
|
+
replay: path.join(dir, "replay.sql"),
|
|
13
15
|
load: path.join(dir, "load.sql"),
|
|
14
16
|
manifest: path.join(dir, "import.json"),
|
|
15
17
|
report: path.join(dir, "report.md")
|
|
@@ -26,7 +28,9 @@ const importState = (projectDir) => {
|
|
|
26
28
|
await ignoreInGit(projectDir, "/supabase-import/");
|
|
27
29
|
await writeFile(files.data, "", { mode: 384 });
|
|
28
30
|
},
|
|
31
|
+
writeReplay: (script) => writeFile(files.replay, script, { mode: 384 }),
|
|
29
32
|
hasData: () => existsSync(files.data),
|
|
33
|
+
hasReplay: () => existsSync(files.replay),
|
|
30
34
|
hasManifest: () => existsSync(files.manifest),
|
|
31
35
|
readManifest: async () => JSON.parse(await readFile(files.manifest, "utf8")),
|
|
32
36
|
writeManifest: (manifest) => writeFile(files.manifest, `${JSON.stringify(manifest, null, 2)}\n`, { mode: 384 })
|
|
@@ -36,16 +36,17 @@ const doctorOutput = async (url, configDir) => {
|
|
|
36
36
|
return text;
|
|
37
37
|
};
|
|
38
38
|
/**
|
|
39
|
-
* The import's second run, once the schema migration is applied: loads the data dump
|
|
40
|
-
*
|
|
41
|
-
* report.
|
|
39
|
+
* The import's second run, once the schema migration is applied: loads the data dump, with the replay of Vault's
|
|
40
|
+
* secrets and pgmq's queues when the dump made one, in one transaction, deletes both, scaffolds the config from the
|
|
41
|
+
* imported tables of the app's schemas, leaving the project's own alone, and writes the report.
|
|
42
42
|
*/
|
|
43
43
|
const runLoadPhase = async (options, out) => {
|
|
44
44
|
const state = importState(options.projectDir);
|
|
45
45
|
const manifest = await state.readManifest();
|
|
46
46
|
if (!existsSync(path.join(options.migrationsDir, manifest.migration))) throw new Error(`The import's migration ${manifest.migration} is not in ${options.migrationsDir}; remove supabase-import/ and import again`);
|
|
47
47
|
await checkReady(options.targetUrl, manifest);
|
|
48
|
-
|
|
48
|
+
const replay = state.hasReplay() ? state.replay : void 0;
|
|
49
|
+
await writeFile(state.load, loadScript(state.data, manifest.tables, replay), { mode: 384 });
|
|
49
50
|
await runPgTool("psql", options.targetUrl, [
|
|
50
51
|
"--no-psqlrc",
|
|
51
52
|
"--quiet",
|
|
@@ -55,6 +56,7 @@ const runLoadPhase = async (options, out) => {
|
|
|
55
56
|
]);
|
|
56
57
|
await rm(state.load);
|
|
57
58
|
await rm(state.data);
|
|
59
|
+
if (replay) await rm(replay);
|
|
58
60
|
out(`loaded ${manifest.tables.reduce((sum, table) => sum + table.rows, 0)} rows into ${manifest.tables.length} tables; each count matches the source\n`);
|
|
59
61
|
const schemas = manifest.schemas.filter((schema) => !platformSchemas.includes(schema));
|
|
60
62
|
const sql = connect(options.targetUrl);
|
|
@@ -7,12 +7,14 @@ const checkRows = (table) => `DO $$ DECLARE found bigint; BEGIN SELECT count(*)
|
|
|
7
7
|
/**
|
|
8
8
|
* The psql script that loads the data dump at `dataFile` into `tables`, for `psql --single-transaction`: the app's
|
|
9
9
|
* triggers are off while it loads, so a sign-up trigger on auth.users does not run again for users who already have
|
|
10
|
-
* their rows, then back on;
|
|
10
|
+
* their rows, then back on; the replay at `replayFile`, when there is one, makes Vault's secrets and pgmq's queues
|
|
11
|
+
* again; every table's rows are counted against the source's before the transaction commits.
|
|
11
12
|
*/
|
|
12
|
-
const loadScript = (dataFile, tables) => [
|
|
13
|
+
const loadScript = (dataFile, tables, replayFile) => [
|
|
13
14
|
...tables.map((table) => `ALTER TABLE ${qualified(table)} DISABLE TRIGGER USER;\n`),
|
|
14
15
|
`\\i ${literal(dataFile)}\n`,
|
|
15
16
|
...tables.map((table) => `ALTER TABLE ${qualified(table)} ENABLE TRIGGER USER;\n`),
|
|
17
|
+
...replayFile ? [`\\i ${literal(replayFile)}\n`] : [],
|
|
16
18
|
...tables.map(checkRows)
|
|
17
19
|
].join("");
|
|
18
20
|
//#endregion
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
//#region src/supabase/replay.ts
|
|
2
|
+
const literal = (text) => text === null ? "NULL" : `'${text.replaceAll("'", "''")}'`;
|
|
3
|
+
const jsonb = (text) => `${literal(text)}::jsonb`;
|
|
4
|
+
/** Vault's secrets, made again with their values: Vault encrypts them with the project database's own key. */
|
|
5
|
+
const secretsScript = (secrets) => secrets.map((secret) => `SELECT vault.create_secret(${literal(secret.secret)}, ${literal(secret.name)}, ${literal(secret.description)});\n`).join("");
|
|
6
|
+
/** A queue, made again as it was, and its messages sent again in order, each with its headers and visibility time. */
|
|
7
|
+
const queueScript = (queue) => [`SELECT pgmq.${queue.unlogged ? "create_unlogged" : "create"}(${literal(queue.name)});\n`, ...queue.messages.map((message) => `SELECT pgmq.send(${literal(queue.name)}, ${jsonb(message.message)}, ${jsonb(message.headers)}, ${literal(message.visibleAt)}::timestamptz);\n`)].join("");
|
|
8
|
+
/**
|
|
9
|
+
* The psql script that makes again, through each extension's own API, what a dump cannot carry over: Vault's secrets,
|
|
10
|
+
* whose ciphertext only Supabase's key opens, and pgmq's queues, whose tables belong to the extension. It holds the
|
|
11
|
+
* secrets' values, so it lives only in `supabase-import/`, readable by its owner, until the load deletes it.
|
|
12
|
+
*/
|
|
13
|
+
const replayScript = (input) => secretsScript(input.secrets) + input.queues.map(queueScript).join("");
|
|
14
|
+
//#endregion
|
|
15
|
+
export { replayScript };
|
package/dist/supabase/report.js
CHANGED
|
@@ -4,6 +4,19 @@ const starterBytes = 524288e3;
|
|
|
4
4
|
const megabytes = (bytes) => `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
5
5
|
const code = (text) => `\`${text.replaceAll("`", "'")}\``;
|
|
6
6
|
const section = (title, intro, items, unreadable = "The importing role could not read them; list them in the Supabase dashboard.") => `## ${title}\n\n${items === void 0 ? unreadable : items.length === 0 ? "None." : `${intro}\n\n${items.map((item) => `- ${item}`).join("\n")}`}\n`;
|
|
7
|
+
const secretName = (secret) => `${secret.name ?? "unnamed"}${secret.description ? `: ${secret.description}` : ""}`;
|
|
8
|
+
const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
9
|
+
const trigger = (one) => `${one.trigger} on ${one.schema}.${one.table}, calling ${one.function}`;
|
|
10
|
+
/** What the import made again through an extension's own API, or kept since the project's database runs the extension. */
|
|
11
|
+
const carried = (manifest) => [
|
|
12
|
+
...manifest.vaultReplayed ? (manifest.vaultSecrets ?? []).map((secret) => `Vault secret ${secretName(secret)}`) : [],
|
|
13
|
+
...manifest.queuesReplayed ? (manifest.queues ?? []).filter((queue) => !queue.partitioned).map((queue) => `pgmq queue ${queue.name}, with ${plural(queue.messages, "message")}`) : [],
|
|
14
|
+
...manifest.httpSent ? manifest.httpTriggers.map((one) => `HTTP trigger ${trigger(one)}`) : []
|
|
15
|
+
];
|
|
16
|
+
/** What pgmq's queues leave for a person: every queue without pgmq, and a partitioned queue's partitions with it. */
|
|
17
|
+
const queuesLeft = (manifest) => manifest.queues?.filter((queue) => !manifest.queuesReplayed || queue.partitioned).map((queue) => `${queue.name}${queue.partitioned ? ", partitioned" : ""}, with ${plural(queue.messages, "message")}`);
|
|
18
|
+
/** What uses an extension Supabase dropped after Postgres 15, which a person converts. */
|
|
19
|
+
const conversions = (manifest) => [...manifest.hypertables.map((table) => `hypertable ${table.schema}.${table.table}, ${plural(table.rows, "row")} in chunks the dump leaves out: make it a plain or pg_partman-partitioned table and copy its rows with \`INSERT … SELECT\``), ...manifest.routinesLeftOut.map((routine) => `function ${routine.name}, written in ${routine.language}: rewrite it in plpgsql or as a Protobase function`)];
|
|
7
20
|
/**
|
|
8
21
|
* The import's report: what it loaded, and what it could not carry over, for a person or their AI assistant to finish.
|
|
9
22
|
* `doctor` is `protobase doctor`'s output on the scaffolded config, or `undefined` when there was no config to check.
|
|
@@ -14,11 +27,14 @@ const importReport = (manifest, doctor) => [
|
|
|
14
27
|
`The imported tables take ${megabytes(manifest.bytes)} in the source database${manifest.bytes > starterBytes ? `, more than the ${megabytes(starterBytes)} of the Starter plan: pick a larger plan` : `, within the ${megabytes(starterBytes)} of the Starter plan`}.\n`,
|
|
15
28
|
`The migration leaves out ${manifest.leftOut} statement${manifest.leftOut === 1 ? "" : "s"} of the dump, as comments: grants to Supabase's own roles and the like.\n`,
|
|
16
29
|
"## Rows loaded\n\nEach count matched the source before the load committed.\n\n| Table | Rows |\n| --- | --- |\n" + manifest.tables.map((table) => `| ${table.schema}.${table.table} | ${table.rows} |`).join("\n") + "\n",
|
|
30
|
+
section("Made again", "A dump cannot carry these. The load made Vault's secrets and pgmq's queues again through each extension's own API, in the same transaction, and pg_net sends the HTTP triggers' calls from the project's database, Database Webhooks' through the `supabase_functions.http_request` the migration creates.", carried(manifest)),
|
|
17
31
|
section("Cron jobs", "pg_cron's jobs live in its own schema, which the import does not carry over. Recreate each as a Protobase job with a schedule.", manifest.cronJobs?.map((job) => `${job.name ?? "unnamed"}, ${code(job.schedule)}: ${code(job.command)}`)),
|
|
18
32
|
section("Realtime tables", "The `supabase_realtime` publication sends these tables' changes to Realtime clients. Give each the live updates the app needs.", manifest.realtimeTables.map((table) => `${table.schema}.${table.table}`)),
|
|
19
|
-
section("Vault secrets", "
|
|
20
|
-
section("
|
|
21
|
-
section("
|
|
33
|
+
section("Vault secrets", "The project's database has no Vault, or the importing role could not read the secrets' values, so they stay in Supabase. Enter each again where the app reads it, such as an environment variable.", manifest.vaultReplayed ? [] : manifest.vaultSecrets?.map(secretName)),
|
|
34
|
+
section("pgmq queues", "pgmq owns its queues' tables, so the dump leaves them out. Make each again with pgmq where the project's database has it, partitioned ones with `pgmq.create_partitioned`, and send its messages again.", queuesLeft(manifest)),
|
|
35
|
+
section("Extensions left out", "The project's database does not let the importing role create these, so the migration does not. Replace what the app uses them for, or have the database's administrator make them available.", manifest.extensionsLeftOut.map((extension) => `${extension.name} (schema ${extension.schema})`)),
|
|
36
|
+
section("To convert", "Supabase dropped timescaledb, plv8, plls and plcoffee after Postgres 15. The migration restores a hypertable as a plain table without its rows, and leaves out a function in a language the project's database does not have, as comments; convert each.", conversions(manifest)),
|
|
37
|
+
section("HTTP triggers", "These triggers call out over HTTP with pg_net or a database webhook, and the project's database has no pg_net. The migration keeps a trigger calling the app's own function, but nothing sends; it leaves out a webhook's. Move each call to a Protobase event subscription or job.", manifest.httpSent ? [] : manifest.httpTriggers.map(trigger)),
|
|
22
38
|
section("Edge Functions", "`supabase/functions` holds these, which the import does not convert.", manifest.functions),
|
|
23
39
|
`## Indexes the scan guard needs\n\n${doctor === void 0 ? "No resources were scaffolded, so `protobase doctor` had nothing to check." : `\`protobase doctor\` on the scaffolded config. The API refuses a read that no index serves; add each index it names in a migration of its own.\n\n\`\`\`\n${doctor.trimEnd()}\n\`\`\``}\n`
|
|
24
40
|
].join("\n");
|
package/dist/supabase/rewrite.js
CHANGED
|
@@ -7,8 +7,6 @@ import { tokenize, wordsAt } from "./tokens.js";
|
|
|
7
7
|
* `service_role` are not among them; the app's grants and policies name those.
|
|
8
8
|
*/
|
|
9
9
|
const isSupabaseRole = (role) => role === "dashboard_user" || role === "authenticator" || role === "postgres" || role.startsWith("supabase_");
|
|
10
|
-
/** Schemas whose functions a trigger may call that the import does not carry over: database webhooks call these. */
|
|
11
|
-
const webhookSchemas = ["supabase_functions"];
|
|
12
10
|
const keep = (text) => ({ keep: text });
|
|
13
11
|
/** The grantee list of a GRANT or REVOKE: the role names after its last top-level TO (or FROM), up to its options. */
|
|
14
12
|
const grantees = (statement, tokens, from, keyword) => {
|
|
@@ -43,18 +41,45 @@ const defaultPrivileges = (statement, tokens) => {
|
|
|
43
41
|
const rewritten = statement.slice(0, tokens[3].start) + statement.slice(tokens[next].start);
|
|
44
42
|
return defaultPrivileges(rewritten, tokenize(rewritten));
|
|
45
43
|
};
|
|
44
|
+
/** A routine's qualified name at token `at` (`schema.name`), and its name with the signature after it, as the dump writes both. */
|
|
45
|
+
const routineAt = (statement, tokens, at) => {
|
|
46
|
+
if (statement[tokens[at + 1]?.start ?? 0] !== "." || statement[tokens[at + 3]?.start ?? 0] !== "(") return void 0;
|
|
47
|
+
const close = tokens.findIndex((token, i) => i > at + 3 && token.depth === tokens[at + 3].depth && statement[token.start] === ")");
|
|
48
|
+
return {
|
|
49
|
+
name: `${tokens[at].word}.${tokens[at + 2].word}`,
|
|
50
|
+
signature: statement.slice(tokens[at].start, tokens[close].end)
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
/** A CREATE FUNCTION or PROCEDURE in a missing language, left out, or a statement naming one left out before. */
|
|
54
|
+
const routineVerdict = (statement, tokens, missing, routines) => {
|
|
55
|
+
const at = (...words) => wordsAt(statement, tokens, 0, words);
|
|
56
|
+
const create = at("create", "function") || at("create", "procedure") ? 2 : at("create", "or", "replace", "function") || at("create", "or", "replace", "procedure") ? 4 : -1;
|
|
57
|
+
if (create !== -1) {
|
|
58
|
+
const name = tokens[tokens.findIndex((token, i) => i > create && token.depth === 0 && wordsAt(statement, tokens, i, ["language"])) + 1]?.word;
|
|
59
|
+
const routine = routineAt(statement, tokens, create);
|
|
60
|
+
if (!name || !routine || !missing.languages.includes(name)) return void 0;
|
|
61
|
+
routines.names.add(routine.name);
|
|
62
|
+
routines.signatures.add(routine.signature);
|
|
63
|
+
return { drop: `it is written in ${name}, which the project's database does not have; the report lists it for conversion` };
|
|
64
|
+
}
|
|
65
|
+
if (routines.signatures.size === 0) return void 0;
|
|
66
|
+
return tokens.some((token, i) => (token.word === "function" || token.word === "procedure") && routines.signatures.has(routineAt(statement, tokens, i + 1)?.signature ?? "")) ? { drop: "it names a function left out above" } : void 0;
|
|
67
|
+
};
|
|
46
68
|
/** A statement as it should restore on a Protobase database, or why it is left out. */
|
|
47
|
-
const rewriteStatement = (statement) => {
|
|
69
|
+
const rewriteStatement = (statement, missing, routines) => {
|
|
48
70
|
const tokens = tokenize(statement);
|
|
49
71
|
const at = (...words) => wordsAt(statement, tokens, 0, words);
|
|
72
|
+
const routine = routineVerdict(statement, tokens, missing, routines);
|
|
73
|
+
if (routine) return routine;
|
|
50
74
|
if (at("grant") || at("revoke")) return withoutSupabaseGrantees(statement, tokens, 0);
|
|
51
75
|
if (at("alter", "default", "privileges")) return defaultPrivileges(statement, tokens);
|
|
52
76
|
if (at("create", "schema", "public") || at("comment", "on", "schema", "public") || at("alter", "schema", "public")) return { drop: "the public schema already exists and is not the import's to change" };
|
|
53
77
|
if (at("alter", "publication") || at("create", "publication")) return { drop: "publications are Supabase Realtime's; the report lists their tables" };
|
|
54
78
|
if (at("create", "trigger") || at("create", "constraint", "trigger") || at("create", "or", "replace", "trigger")) {
|
|
55
79
|
const call = tokens.findIndex((_, i) => wordsAt(statement, tokens, i, ["execute", "function"]) || wordsAt(statement, tokens, i, ["execute", "procedure"]));
|
|
56
|
-
const
|
|
57
|
-
if (
|
|
80
|
+
const called = call === -1 ? void 0 : routineAt(statement, tokens, call + 2);
|
|
81
|
+
if (called && missing.triggerSchemas.includes(called.name.split(".")[0])) return { drop: `it calls ${called.name}, which the import does not carry over; the report lists it` };
|
|
82
|
+
if (called && routines.names.has(called.name)) return { drop: "it calls a function left out above" };
|
|
58
83
|
}
|
|
59
84
|
return keep(statement);
|
|
60
85
|
};
|
|
@@ -62,16 +87,20 @@ const rewriteStatement = (statement) => {
|
|
|
62
87
|
const leftOut = (statement, reason) => `-- Left out by protobase import supabase: ${reason}.\n${statement.replace(/^/gm, "-- ")}`;
|
|
63
88
|
/**
|
|
64
89
|
* A `pg_dump --schema-only` of a Supabase database, rewritten to restore without errors as a role that is not a
|
|
65
|
-
* superuser and has none of Supabase's own roles,
|
|
66
|
-
* rule never touches a function body or a string.
|
|
90
|
+
* superuser and has none of Supabase's own roles, on a database lacking what `missing` names, and how many statements
|
|
91
|
+
* it leaves out. Statements are parsed, so a rule never touches a function body or a string.
|
|
67
92
|
*/
|
|
68
|
-
const rewriteSchemaDump = (dump) => {
|
|
93
|
+
const rewriteSchemaDump = (dump, missing) => {
|
|
69
94
|
let leftOutCount = 0;
|
|
95
|
+
const routines = {
|
|
96
|
+
names: /* @__PURE__ */ new Set(),
|
|
97
|
+
signatures: /* @__PURE__ */ new Set()
|
|
98
|
+
};
|
|
70
99
|
return {
|
|
71
100
|
sql: splitDump(dump).map((piece) => {
|
|
72
101
|
if (piece.kind === "meta") return "";
|
|
73
102
|
if (piece.kind === "gap") return piece.text;
|
|
74
|
-
const verdict = rewriteStatement(piece.text);
|
|
103
|
+
const verdict = rewriteStatement(piece.text, missing, routines);
|
|
75
104
|
if ("keep" in verdict) return verdict.keep;
|
|
76
105
|
leftOutCount++;
|
|
77
106
|
return leftOut(piece.text, verdict.drop);
|
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
import { createExtensions } from "./extensions.js";
|
|
2
|
+
import { webhooksShim } from "./webhooks.js";
|
|
2
3
|
import { rewriteSchemaDump } from "./rewrite.js";
|
|
3
4
|
import { resetSettings, sessionSettings } from "./session-settings.js";
|
|
4
5
|
//#region src/supabase/schema-migration.ts
|
|
5
6
|
/**
|
|
6
|
-
* The migration that restores a Supabase database's schemas: the
|
|
7
|
-
*
|
|
8
|
-
* how many of the dump's
|
|
7
|
+
* The migration that restores a Supabase database's schemas: the extensions they use that the project's database can
|
|
8
|
+
* create, the Database Webhooks shim where it has pg_net, the schema dump as it restores there without a superuser,
|
|
9
|
+
* and the session settings the dump changed put back for the migrations after it; and how many of the dump's
|
|
10
|
+
* statements it leaves out.
|
|
9
11
|
*/
|
|
10
12
|
const schemaMigration = (dump, input) => {
|
|
11
|
-
const rewritten = rewriteSchemaDump(dump);
|
|
13
|
+
const rewritten = rewriteSchemaDump(dump, input.missing);
|
|
12
14
|
return {
|
|
13
15
|
text: [
|
|
14
16
|
`-- The schemas ${input.schemas.join(", ")} of a Supabase database, written by \`protobase import supabase\`.\n`,
|
|
15
17
|
"-- Applied with the project's other migrations. Statements naming Supabase's own roles are left out as comments.\n\n",
|
|
16
18
|
createExtensions(input.extensions),
|
|
19
|
+
input.webhooks ? `\n${webhooksShim}` : "",
|
|
17
20
|
"\n",
|
|
18
21
|
rewritten.sql,
|
|
19
22
|
"\n",
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
//#region src/supabase/source-facts.ts
|
|
2
2
|
/**
|
|
3
3
|
* Schemas of a Supabase database that belong to the platform rather than the app: its services' own (Realtime, Vault,
|
|
4
|
-
* GraphQL, webhooks, migrations, the pooler) and those of its extensions
|
|
5
|
-
*
|
|
4
|
+
* GraphQL, webhooks, migrations, the pooler) and those of its extensions, which the migration makes with them (pgmq's
|
|
5
|
+
* holds only its own tables, but is no member of it). auth and storage are the platform's too, but the app's tables
|
|
6
|
+
* point at them and its triggers and policies live in them, so the import carries them over.
|
|
6
7
|
*/
|
|
7
8
|
const platformSchemas = [
|
|
8
9
|
"extensions",
|
|
@@ -17,6 +18,7 @@ const platformSchemas = [
|
|
|
17
18
|
"supabase_migrations",
|
|
18
19
|
"cron",
|
|
19
20
|
"net",
|
|
21
|
+
"pgmq",
|
|
20
22
|
"pgbouncer",
|
|
21
23
|
"_analytics",
|
|
22
24
|
"pgtle"
|
|
@@ -41,7 +43,10 @@ const appSchemas = async (sql) => {
|
|
|
41
43
|
order by 1
|
|
42
44
|
`).map((row) => row.name);
|
|
43
45
|
};
|
|
44
|
-
/**
|
|
46
|
+
/**
|
|
47
|
+
* The tables of `schemas` the data dump fills, each with its rows counted now: its own rows, as pg_dump copies them,
|
|
48
|
+
* without those of tables inheriting from it, such as a timescaledb hypertable's chunks.
|
|
49
|
+
*/
|
|
45
50
|
const dumpedTables = async (sql, schemas) => {
|
|
46
51
|
const tables = await sql`
|
|
47
52
|
select n.nspname as schema, c.relname as table from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
@@ -51,7 +56,7 @@ const dumpedTables = async (sql, schemas) => {
|
|
|
51
56
|
`;
|
|
52
57
|
const counted = [];
|
|
53
58
|
for (const table of tables) {
|
|
54
|
-
const [row] = await sql`select count(*) as rows from ${sql(table.schema)}.${sql(table.table)}`;
|
|
59
|
+
const [row] = await sql`select count(*) as rows from only ${sql(table.schema)}.${sql(table.table)}`;
|
|
55
60
|
counted.push({
|
|
56
61
|
...table,
|
|
57
62
|
rows: Number(row.rows)
|
|
@@ -68,10 +73,7 @@ const tablesSize = async (sql, tables) => {
|
|
|
68
73
|
return Number(row.bytes ?? 0);
|
|
69
74
|
};
|
|
70
75
|
const extensions = (sql) => sql`
|
|
71
|
-
select e.extname as name, n.nspname as schema
|
|
72
|
-
from pg_extension e join pg_namespace n on n.oid = e.extnamespace
|
|
73
|
-
left join pg_available_extension_versions v on v.name = e.extname and v.version = e.extversion
|
|
74
|
-
order by 1
|
|
76
|
+
select e.extname as name, n.nspname as schema from pg_extension e join pg_namespace n on n.oid = e.extnamespace order by 1
|
|
75
77
|
`;
|
|
76
78
|
/** Whether the importing role may read `table`, which exists only when its feature is on. */
|
|
77
79
|
const readable = async (sql, table) => {
|
|
@@ -85,13 +87,72 @@ const cronJobs = async (sql) => {
|
|
|
85
87
|
if (!await readable(sql, "cron.job")) return void 0;
|
|
86
88
|
return sql`select jobname as name, schedule, command from cron.job order by jobid`;
|
|
87
89
|
};
|
|
88
|
-
/** Vault's secrets by name
|
|
90
|
+
/** Vault's secrets by name, for the report. */
|
|
89
91
|
const vaultSecrets = async (sql) => {
|
|
90
92
|
const [row] = await sql`select to_regclass('vault.secrets') is not null as exists`;
|
|
91
93
|
if (!row.exists) return [];
|
|
92
94
|
if (!await readable(sql, "vault.secrets")) return void 0;
|
|
93
95
|
return sql`select name, description from vault.secrets order by name`;
|
|
94
96
|
};
|
|
97
|
+
/**
|
|
98
|
+
* Vault's secrets with their values, decrypted, for the replay: the ciphertext opens only with Supabase's key.
|
|
99
|
+
* `undefined` when the role may not read them.
|
|
100
|
+
*/
|
|
101
|
+
const vaultSecretValues = async (sql) => {
|
|
102
|
+
if (!await readable(sql, "vault.decrypted_secrets")) return void 0;
|
|
103
|
+
return sql`select name, description, decrypted_secret as secret from vault.decrypted_secrets order by created_at, id`;
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* pgmq's queues with their messages, in order. The extension owns the queues' tables, so pg_dump leaves them out.
|
|
107
|
+
* `undefined` when the role may not read them.
|
|
108
|
+
*/
|
|
109
|
+
const pgmqQueues = async (sql) => {
|
|
110
|
+
const [row] = await sql`select to_regclass('pgmq.meta') is not null as exists`;
|
|
111
|
+
if (!row.exists) return [];
|
|
112
|
+
if (!await readable(sql, "pgmq.meta")) return void 0;
|
|
113
|
+
const meta = await sql`
|
|
114
|
+
select queue_name as name, is_unlogged as unlogged, is_partitioned as partitioned from pgmq.meta order by created_at, queue_name
|
|
115
|
+
`;
|
|
116
|
+
const queues = [];
|
|
117
|
+
for (const queue of meta) {
|
|
118
|
+
const messages = await sql`
|
|
119
|
+
select q.message::text as message, nullif(to_jsonb(q) -> 'headers', 'null')::text as headers, q.vt::text as "visibleAt"
|
|
120
|
+
from pgmq.${sql(`q_${queue.name}`)} q order by q.msg_id
|
|
121
|
+
`;
|
|
122
|
+
queues.push({
|
|
123
|
+
...queue,
|
|
124
|
+
messages: [...messages]
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
return queues;
|
|
128
|
+
};
|
|
129
|
+
/** timescaledb's hypertables in `schemas`, with their rows, which live in chunks the dump leaves out. */
|
|
130
|
+
const hypertables = async (sql, schemas) => {
|
|
131
|
+
const [row] = await sql`select to_regclass('timescaledb_information.hypertables') is not null as exists`;
|
|
132
|
+
if (!row.exists) return [];
|
|
133
|
+
const tables = await sql`
|
|
134
|
+
select hypertable_schema as schema, hypertable_name as table from timescaledb_information.hypertables
|
|
135
|
+
where hypertable_schema = any(${schemas}) order by 1, 2
|
|
136
|
+
`;
|
|
137
|
+
const counted = [];
|
|
138
|
+
for (const table of tables) {
|
|
139
|
+
const [count] = await sql`select count(*) as rows from ${sql(table.schema)}.${sql(table.table)}`;
|
|
140
|
+
counted.push({
|
|
141
|
+
...table,
|
|
142
|
+
rows: Number(count.rows)
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
return counted;
|
|
146
|
+
};
|
|
147
|
+
/** The functions and procedures of `schemas` written in `languages`, as `schema.name`. */
|
|
148
|
+
const routinesIn = async (sql, schemas, languages) => {
|
|
149
|
+
return [...await sql`
|
|
150
|
+
select n.nspname || '.' || p.proname as name, l.lanname as language
|
|
151
|
+
from pg_proc p join pg_namespace n on n.oid = p.pronamespace join pg_language l on l.oid = p.prolang
|
|
152
|
+
where n.nspname = any(${schemas}) and l.lanname = any(${languages})
|
|
153
|
+
order by 1
|
|
154
|
+
`];
|
|
155
|
+
};
|
|
95
156
|
const realtimeTables = (sql) => sql`
|
|
96
157
|
select schemaname as schema, tablename as table from pg_publication_tables where pubname = 'supabase_realtime' order by 1, 2
|
|
97
158
|
`;
|
|
@@ -107,4 +168,4 @@ const httpTriggers = (sql, schemas) => sql`
|
|
|
107
168
|
order by 1, 2, 3
|
|
108
169
|
`;
|
|
109
170
|
//#endregion
|
|
110
|
-
export { appSchemas, cronJobs, databaseMarkers, dumpedTables, extensions, httpTriggers, platformMigrationTables, realtimeTables, tablesSize, vaultSecrets };
|
|
171
|
+
export { appSchemas, cronJobs, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
//#region src/supabase/target-extensions.ts
|
|
2
|
+
const literal = (text) => `'${text.replaceAll("'", "''")}'`;
|
|
3
|
+
/**
|
|
4
|
+
* The statements, run in order on one connection, whose third answers which of `names` the connected role may create
|
|
5
|
+
* in its database, one row per name. It tries each in a transaction it rolls back, since only trying tells: a Supabase
|
|
6
|
+
* style image lets a database owner create its allowlisted extensions, pg_cron only in the database it serves, and
|
|
7
|
+
* Postgres alone only its trusted ones. A failure to create is the answer, so the function returns it instead.
|
|
8
|
+
*/
|
|
9
|
+
const extensionProbe = (names) => [
|
|
10
|
+
"BEGIN",
|
|
11
|
+
`CREATE FUNCTION pg_temp.may_create_extension(name text) RETURNS boolean LANGUAGE plpgsql AS $$
|
|
12
|
+
BEGIN
|
|
13
|
+
EXECUTE format('CREATE EXTENSION IF NOT EXISTS %I CASCADE', name);
|
|
14
|
+
RETURN true;
|
|
15
|
+
EXCEPTION WHEN others THEN
|
|
16
|
+
RETURN false;
|
|
17
|
+
END $$`,
|
|
18
|
+
`SELECT name, pg_temp.may_create_extension(name) AS creatable FROM unnest(ARRAY[${names.map(literal).join(", ")}]::text[]) AS name ORDER BY 1`,
|
|
19
|
+
"ROLLBACK"
|
|
20
|
+
];
|
|
21
|
+
/** Which of `names` the role at `sql` may create in the project's database. */
|
|
22
|
+
const creatableExtensions = async (sql, names) => {
|
|
23
|
+
const reserved = await sql.reserve();
|
|
24
|
+
try {
|
|
25
|
+
const [begin, define, probe, rollback] = extensionProbe(names);
|
|
26
|
+
await reserved.unsafe(begin);
|
|
27
|
+
await reserved.unsafe(define);
|
|
28
|
+
const rows = await reserved.unsafe(probe);
|
|
29
|
+
await reserved.unsafe(rollback);
|
|
30
|
+
return new Set(rows.filter((row) => row.creatable).map((row) => row.name));
|
|
31
|
+
} finally {
|
|
32
|
+
reserved.release();
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
//#endregion
|
|
36
|
+
export { creatableExtensions, extensionProbe };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
//#region src/supabase/webhooks.ts
|
|
2
|
+
/** Whether `trigger` is a Database Webhook: Supabase's dashboard makes them as triggers calling this function. */
|
|
3
|
+
const isWebhook = (trigger) => trigger.function === "supabase_functions.http_request";
|
|
4
|
+
/**
|
|
5
|
+
* `supabase_functions.http_request`, which Database Webhooks' triggers call, over pg_net as Supabase defines it
|
|
6
|
+
* (supabase/supabase `docker/volumes/db/webhooks.sql`): the trigger's arguments are the URL, the method (GET or POST),
|
|
7
|
+
* the headers, the query parameters and the timeout in milliseconds, and a POST sends the row as Supabase does. Unlike
|
|
8
|
+
* Supabase's, it keeps no `hooks` table of its own, since pg_net keeps each response in `net._http_response`; and it
|
|
9
|
+
* runs as its owner, so the API roles whose writes fire a webhook need no rights on pg_net.
|
|
10
|
+
*/
|
|
11
|
+
const webhooksShim = `CREATE SCHEMA IF NOT EXISTS supabase_functions;
|
|
12
|
+
CREATE FUNCTION supabase_functions.http_request() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path = '' AS $function$
|
|
13
|
+
DECLARE
|
|
14
|
+
url text := TG_ARGV[0]::text;
|
|
15
|
+
method text := TG_ARGV[1]::text;
|
|
16
|
+
headers jsonb := CASE WHEN TG_ARGV[2] IS NULL OR TG_ARGV[2] = 'null' THEN '{"Content-Type": "application/json"}'::jsonb ELSE TG_ARGV[2]::jsonb END;
|
|
17
|
+
params jsonb := CASE WHEN TG_ARGV[3] IS NULL OR TG_ARGV[3] = 'null' THEN '{}'::jsonb ELSE TG_ARGV[3]::jsonb END;
|
|
18
|
+
timeout_ms integer := CASE WHEN TG_ARGV[4] IS NULL OR TG_ARGV[4] = 'null' THEN 1000 ELSE TG_ARGV[4]::integer END;
|
|
19
|
+
BEGIN
|
|
20
|
+
IF url IS NULL OR url = 'null' THEN
|
|
21
|
+
RAISE EXCEPTION 'url argument is missing';
|
|
22
|
+
END IF;
|
|
23
|
+
CASE method
|
|
24
|
+
WHEN 'GET' THEN
|
|
25
|
+
PERFORM net.http_get(url, params, headers, timeout_ms);
|
|
26
|
+
WHEN 'POST' THEN
|
|
27
|
+
PERFORM net.http_post(
|
|
28
|
+
url,
|
|
29
|
+
jsonb_build_object('old_record', OLD, 'record', NEW, 'type', TG_OP, 'table', TG_TABLE_NAME, 'schema', TG_TABLE_SCHEMA),
|
|
30
|
+
params,
|
|
31
|
+
headers,
|
|
32
|
+
timeout_ms
|
|
33
|
+
);
|
|
34
|
+
ELSE
|
|
35
|
+
RAISE EXCEPTION 'method argument % is invalid', method;
|
|
36
|
+
END CASE;
|
|
37
|
+
RETURN NEW;
|
|
38
|
+
END
|
|
39
|
+
$function$;
|
|
40
|
+
REVOKE ALL ON FUNCTION supabase_functions.http_request() FROM PUBLIC;
|
|
41
|
+
`;
|
|
42
|
+
//#endregion
|
|
43
|
+
export { isWebhook, webhooksShim };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.26.
|
|
3
|
+
"version": "0.26.2",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -35,11 +35,11 @@
|
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"@hono/node-server": "^2.1.3",
|
|
37
37
|
"@hono/vite-dev-server": "^0.26.1",
|
|
38
|
-
"@protobase/layout": "0.26.
|
|
39
|
-
"@protobase/query": "0.26.
|
|
40
|
-
"@protobase/schema": "0.26.
|
|
41
|
-
"@protobase/server": "0.26.
|
|
42
|
-
"@protobase/ui": "0.26.
|
|
38
|
+
"@protobase/layout": "0.26.2",
|
|
39
|
+
"@protobase/query": "0.26.2",
|
|
40
|
+
"@protobase/schema": "0.26.2",
|
|
41
|
+
"@protobase/server": "0.26.2",
|
|
42
|
+
"@protobase/ui": "0.26.2",
|
|
43
43
|
"@react-email/render": "^2.1.0",
|
|
44
44
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
45
45
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -66,7 +66,7 @@ Reference:
|
|
|
66
66
|
- When keeping or showing the changes of records → read [Record history](references/reference/history.md)
|
|
67
67
|
- When adding comments to records → read [Record comments](references/reference/comments.md)
|
|
68
68
|
- When open pages should refresh as records change → read [Live updates](references/reference/live.md)
|
|
69
|
-
- When an app
|
|
69
|
+
- When an app uses supabase-js Realtime (`postgres_changes` under RLS, broadcast, presence) → read [Supabase Realtime](references/reference/supabase-realtime.md)
|
|
70
70
|
- When filling fields with a model → read [AI fields and actions](references/reference/ai.md)
|
|
71
71
|
- When letting people without an account create records → read [Public forms](references/reference/forms.md)
|
|
72
72
|
- When running background jobs → read [Jobs](references/reference/jobs.md)
|
|
@@ -469,9 +469,9 @@ protobase import supabase [<connection> | --source-env <variable>] [--env DATABA
|
|
|
469
469
|
|
|
470
470
|
Turns a Supabase project's database into the project in the current directory, in two runs with the project's migrations between them. It needs PostgreSQL's `pg_dump` and `psql` on `PATH`, of the Supabase database's major version or newer, and reads the `.env` nearest the current directory for the project's database (`--env`).
|
|
471
471
|
|
|
472
|
-
1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql
|
|
472
|
+
1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault and pgmq, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, and pgmq's queues with their messages, since pgmq owns their tables.
|
|
473
473
|
2. **Apply the migration** with the project's other migrations, such as `bun run db:migrate`.
|
|
474
|
-
3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. It loads only into empty tables, deletes the data dump, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, and what needs a person: pg_cron jobs, Realtime tables, Vault secrets by name,
|
|
474
|
+
3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, what it made again, and what needs a person: pg_cron jobs, Realtime tables, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, Edge Functions, and the indexes [`doctor`](#doctor) finds missing.
|
|
475
475
|
|
|
476
476
|
Remove `supabase-import/` to import again. Signing in Supabase's users with Protobase's auth is not part of this command yet.
|
|
477
477
|
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
# Supabase Realtime
|
|
4
4
|
|
|
5
|
-
The Realtime-compatible /realtime/v1 that supabase-js's channel()
|
|
5
|
+
The Realtime-compatible /realtime/v1 that supabase-js's channel() joins, for postgres_changes checked under the subscriber's RLS policies, broadcasts and presence.
|
|
6
6
|
|
|
7
|
-
An app with API keys
|
|
7
|
+
An app with API keys also serves `/realtime/v1/websocket`, the socket that supabase-js's `channel()` joins. An app moved from Supabase keeps its `postgres_changes` listeners, broadcasts and presence: point the client at the app and give it the publishable key.
|
|
8
8
|
|
|
9
9
|
```ts
|
|
10
10
|
import { createClient } from '@supabase/supabase-js'
|
|
@@ -24,7 +24,27 @@ The server serves the socket when the host gives `createAdmin` its WebSocket upg
|
|
|
24
24
|
|
|
25
25
|
## Which tables
|
|
26
26
|
|
|
27
|
-
A channel may listen to the tables of the resources with [`.live()`](live.md)), by `schema` (`*` for any), `table` (every live table of the schema when left out), `event` (`INSERT`, `UPDATE`, `DELETE` or `*`) and `filter`. A table that is not live is refused when the channel joins, with Supabase's message. A filter is Supabase's: `column=operator.value`, with `eq`, `neq`, `lt`, `lte`, `gt`, `gte`, `in.(a,b)`, `like`, `ilike`, `match`, `imatch`, `is` and `isdistinct`, `not.` before the operator, and several conditions joined by commas, all of which must hold. Postgres compares each value as the column's type. `select` of columns is not supported yet;
|
|
27
|
+
A channel may listen to the tables of the resources with [`.live()`](live.md)), by `schema` (`*` for any), `table` (every live table of the schema when left out), `event` (`INSERT`, `UPDATE`, `DELETE` or `*`) and `filter`. A table that is not live is refused when the channel joins, with Supabase's message. A filter is Supabase's: `column=operator.value`, with `eq`, `neq`, `lt`, `lte`, `gt`, `gte`, `in.(a,b)`, `like`, `ilike`, `match`, `imatch`, `is` and `isdistinct`, `not.` before the operator, and several conditions joined by commas, all of which must hold. Postgres compares each value as the column's type. `select` of columns is not supported yet; private channels neither.
|
|
28
|
+
|
|
29
|
+
## Broadcast and presence
|
|
30
|
+
|
|
31
|
+
Channels on the same topic exchange broadcasts and see each other's presence, as on Supabase:
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
const room = supabase.channel('room', { config: { broadcast: { self: false, ack: true }, presence: { key: 'alice' } } })
|
|
35
|
+
room
|
|
36
|
+
.on('broadcast', { event: 'cursor' }, ({ payload }) => console.log(payload))
|
|
37
|
+
.on('presence', { event: 'sync' }, () => console.log(room.presenceState()))
|
|
38
|
+
.subscribe(async (status) => {
|
|
39
|
+
if (status !== 'SUBSCRIBED') return
|
|
40
|
+
await room.track({ online_at: new Date().toISOString() })
|
|
41
|
+
await room.send({ type: 'broadcast', event: 'cursor', payload: { x: 1, y: 2 } })
|
|
42
|
+
})
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
A broadcast reaches the topic's other channels, and the sender's own with `self`; with `ack`, `send` resolves once the server has it. Binary payloads go to clients on the default serializer (`vsn` 2.0.0) only. Presence follows Phoenix Presence: a channel tracks one presence under its `presence.key` (a random one when it names none), tracking again replaces it, and channels with presence enabled get the state when they join and each join and leave after, their own included. A channel that leaves, closes or whose token expires leaves the presence it tracked.
|
|
46
|
+
|
|
47
|
+
Broadcasts and presence go between the channels of one serving process, which is how a cloud app runs; several processes behind one address do not reach each other's channels. Sending without a joined channel, which supabase-js does over `POST /realtime/v1/api/broadcast`, is not supported.
|
|
28
48
|
|
|
29
49
|
## What a subscriber receives
|
|
30
50
|
|