@protobase/cli 0.25.11 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +2 -0
- package/dist/package.js +1 -1
- package/dist/project/project-admin.js +4 -2
- package/dist/serve/lifecycle.js +5 -3
- package/dist/supabase/checkout.js +18 -0
- package/dist/supabase/dump-phase.js +116 -0
- package/dist/supabase/extensions.js +30 -0
- package/dist/supabase/import-state.js +43 -0
- package/dist/supabase/load-phase.js +75 -0
- package/dist/supabase/load-script.js +19 -0
- package/dist/supabase/pg-tools.js +37 -0
- package/dist/supabase/register.js +26 -0
- package/dist/supabase/report.js +26 -0
- package/dist/supabase/rewrite.js +83 -0
- package/dist/supabase/run.js +23 -0
- package/dist/supabase/schema-migration.js +26 -0
- package/dist/supabase/session-settings.js +24 -0
- package/dist/supabase/source-facts.js +110 -0
- package/dist/supabase/statements.js +91 -0
- package/dist/supabase/target-checks.js +56 -0
- package/dist/supabase/tokens.js +84 -0
- package/package.json +8 -6
- package/skills/protobase/SKILL.md +1 -0
- package/skills/protobase/references/reference/auth.md +12 -1
- package/skills/protobase/references/reference/cli.md +14 -0
- package/skills/protobase/references/reference/supabase-realtime.md +39 -0
package/dist/main.js
CHANGED
|
@@ -21,6 +21,7 @@ import { registerOrganizations } from "./organizations/register.js";
|
|
|
21
21
|
import { registerFiles } from "./files/register.js";
|
|
22
22
|
import { registerMigration } from "./migration/register.js";
|
|
23
23
|
import { registerSkill } from "./skill/register.js";
|
|
24
|
+
import { registerImport } from "./supabase/register.js";
|
|
24
25
|
import { registerToken, registerUsers } from "./users/register.js";
|
|
25
26
|
import { statSync } from "node:fs";
|
|
26
27
|
import path from "node:path";
|
|
@@ -130,6 +131,7 @@ registerAuth(program);
|
|
|
130
131
|
registerMigration(program);
|
|
131
132
|
registerFiles(program);
|
|
132
133
|
registerSkill(program);
|
|
134
|
+
registerImport(program);
|
|
133
135
|
const run = (argv) => program.parseAsync(argv).catch((error) => {
|
|
134
136
|
process.stderr.write(`error: ${error.message}\n`);
|
|
135
137
|
process.exitCode = 1;
|
package/dist/package.js
CHANGED
|
@@ -4,9 +4,10 @@ import { configExports, createAdmin, jobDefinitions } from "@protobase/server";
|
|
|
4
4
|
* The admin API of a project over `db`, as `dev`, `serve` and `worker` build it: its config module's resources, views,
|
|
5
5
|
* pages and subscriptions, and the rest of its config; served from a bundle, the plugins it carries and their field
|
|
6
6
|
* types. `jobs` are the project's own and the delivery of its events and history. With a `reporter`, every error the API turns
|
|
7
|
-
* into a 500 goes to the error tracker too, besides the project's `onUnhandledError` or the console.
|
|
7
|
+
* into a 500 goes to the error tracker too, besides the project's `onUnhandledError` or the console. With the host's
|
|
8
|
+
* `upgradeWebSocket`, it serves `/realtime/v1` too.
|
|
8
9
|
*/
|
|
9
|
-
const projectAdmin = (project, config, db, ui, reporter) => {
|
|
10
|
+
const projectAdmin = (project, config, db, ui, reporter, upgradeWebSocket) => {
|
|
10
11
|
const { resources, views, pages, userMenu, bottomBars, subscriptions } = configExports(config);
|
|
11
12
|
const own = jobDefinitions(project.jobs ?? {});
|
|
12
13
|
const unhandled = project.options?.onUnhandledError ?? ((error) => console.error(error));
|
|
@@ -30,6 +31,7 @@ const projectAdmin = (project, config, db, ui, reporter) => {
|
|
|
30
31
|
bundlePlugins: ui.plugins,
|
|
31
32
|
fieldTypes: ui.fieldTypes
|
|
32
33
|
},
|
|
34
|
+
...upgradeWebSocket && { upgradeWebSocket },
|
|
33
35
|
options: {
|
|
34
36
|
...project.options,
|
|
35
37
|
onUnhandledError: (error, request) => {
|
package/dist/serve/lifecycle.js
CHANGED
|
@@ -4,7 +4,8 @@ import { createServeApp } from "./app.js";
|
|
|
4
4
|
import { startCleanupTimer } from "./cleanup-timer.js";
|
|
5
5
|
import { checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
|
|
6
6
|
import pg from "pg";
|
|
7
|
-
import { createAdaptorServer } from "@hono/node-server";
|
|
7
|
+
import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
|
|
8
|
+
import { WebSocketServer } from "ws";
|
|
8
9
|
//#region src/serve/lifecycle.ts
|
|
9
10
|
const listen = (server, port) => new Promise((resolve, reject) => {
|
|
10
11
|
server.once("error", reject);
|
|
@@ -31,7 +32,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
|
|
|
31
32
|
env: process.env
|
|
32
33
|
});
|
|
33
34
|
if (env.startupChecks && project.webhooks) await checkWebhooksSchema(db, project.webhooks);
|
|
34
|
-
const { admin, jobs: definitions } = projectAdmin(project, project.config, db, ui, reporter);
|
|
35
|
+
const { admin, jobs: definitions } = projectAdmin(project, project.config, db, ui, reporter, upgradeWebSocket);
|
|
35
36
|
if (env.startupChecks && definitions.length > 0) await checkJobsSchema(db);
|
|
36
37
|
const jobs = definitions.length > 0 ? await startJobs({
|
|
37
38
|
db,
|
|
@@ -48,7 +49,8 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
|
|
|
48
49
|
});
|
|
49
50
|
const server = createAdaptorServer({
|
|
50
51
|
fetch: app.fetch,
|
|
51
|
-
overrideGlobalObjects: false
|
|
52
|
+
overrideGlobalObjects: false,
|
|
53
|
+
websocket: { server: new WebSocketServer({ noServer: true }) }
|
|
52
54
|
});
|
|
53
55
|
await listen(server, env.port).catch(async (error) => {
|
|
54
56
|
await jobs?.stop();
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { readdir } from "node:fs/promises";
|
|
4
|
+
//#region src/supabase/checkout.ts
|
|
5
|
+
/** The Supabase CLI's files in a checkout: `supabase/config.toml`, `supabase/migrations/`, `supabase/functions/`. */
|
|
6
|
+
const checkoutMarkers = (projectDir) => [
|
|
7
|
+
"supabase/config.toml",
|
|
8
|
+
"supabase/migrations",
|
|
9
|
+
"supabase/functions"
|
|
10
|
+
].filter((marker) => existsSync(path.join(projectDir, marker)));
|
|
11
|
+
/** The Edge Functions in `supabase/functions/`: its folders, except `_shared` and the like. */
|
|
12
|
+
const edgeFunctions = async (projectDir) => {
|
|
13
|
+
const dir = path.join(projectDir, "supabase", "functions");
|
|
14
|
+
if (!existsSync(dir)) return [];
|
|
15
|
+
return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith("_") && !entry.name.startsWith(".")).map((entry) => entry.name).sort();
|
|
16
|
+
};
|
|
17
|
+
//#endregion
|
|
18
|
+
export { checkoutMarkers, edgeFunctions };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { nextMigrationName } from "../auth/migration-file.js";
|
|
2
|
+
import { connect } from "../db/connect.js";
|
|
3
|
+
import { checkoutMarkers, edgeFunctions } from "./checkout.js";
|
|
4
|
+
import { appExtensions } from "./extensions.js";
|
|
5
|
+
import { importState } from "./import-state.js";
|
|
6
|
+
import { runPgTool } from "./pg-tools.js";
|
|
7
|
+
import { schemaMigration } from "./schema-migration.js";
|
|
8
|
+
import { appSchemas, cronJobs, databaseMarkers, dumpedTables, extensions, httpTriggers, platformMigrationTables, realtimeTables, tablesSize, vaultSecrets } from "./source-facts.js";
|
|
9
|
+
import { ensureApiRoles, existingTables } from "./target-checks.js";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
12
|
+
import postgres from "postgres";
|
|
13
|
+
//#region src/supabase/dump-phase.ts
|
|
14
|
+
/** Fails unless the database at `sql` is Supabase's: its auth and storage schemas, and its own admin role. */
|
|
15
|
+
const checkSupabase = async (sql) => {
|
|
16
|
+
const markers = await databaseMarkers(sql);
|
|
17
|
+
const missing = [...["auth", "storage"].filter((schema) => !markers.schemas.includes(schema)).map((schema) => `schema ${schema}`), ...markers.roles.includes("supabase_admin") ? [] : ["role supabase_admin"]];
|
|
18
|
+
if (missing.length > 0) throw new Error(`The source database is not a Supabase database: it lacks the ${missing.join(" and ")}`);
|
|
19
|
+
return markers;
|
|
20
|
+
};
|
|
21
|
+
/** What the source holds, read in the transaction whose snapshot the dumps take, so all of it is of one moment. */
|
|
22
|
+
const readSource = async (sql) => {
|
|
23
|
+
const schemas = await appSchemas(sql);
|
|
24
|
+
const tables = await dumpedTables(sql, schemas);
|
|
25
|
+
const sourceExtensions = appExtensions(await extensions(sql));
|
|
26
|
+
return {
|
|
27
|
+
schemas,
|
|
28
|
+
tables,
|
|
29
|
+
bytes: await tablesSize(sql, tables),
|
|
30
|
+
trusted: sourceExtensions.trusted,
|
|
31
|
+
untrustedExtensions: sourceExtensions.untrusted,
|
|
32
|
+
cronJobs: await cronJobs(sql),
|
|
33
|
+
vaultSecrets: await vaultSecrets(sql),
|
|
34
|
+
realtimeTables: await realtimeTables(sql),
|
|
35
|
+
httpTriggers: await httpTriggers(sql, schemas)
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
/** Fails unless the target can take the schema migration: makes the API roles it lacks, and finds no table in the way. */
|
|
39
|
+
const checkTarget = async (url, tables) => {
|
|
40
|
+
const sql = postgres(url, {
|
|
41
|
+
max: 1,
|
|
42
|
+
onnotice: () => {}
|
|
43
|
+
});
|
|
44
|
+
try {
|
|
45
|
+
const created = await ensureApiRoles(sql);
|
|
46
|
+
const existing = await existingTables(sql, tables);
|
|
47
|
+
if (existing.length > 0) throw new Error(`The project's database already has ${existing.length} of the tables to import, such as ${existing.slice(0, 5).join(", ")}; import into a database without them`);
|
|
48
|
+
return created;
|
|
49
|
+
} finally {
|
|
50
|
+
await sql.end();
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
/** A name as a pg_dump pattern matches it exactly, whatever its case or characters. */
|
|
54
|
+
const pattern = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
55
|
+
/**
|
|
56
|
+
* 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, and keeps the data dump and what the report needs in `supabase-import/` for the run
|
|
58
|
+
* that loads it, once the project's migrations are applied.
|
|
59
|
+
*/
|
|
60
|
+
const runDumpPhase = async (options, out) => {
|
|
61
|
+
const checkout = checkoutMarkers(options.projectDir);
|
|
62
|
+
if (checkout.length > 0) out(`found the Supabase project's ${checkout.join(", ")}\n`);
|
|
63
|
+
const state = importState(options.projectDir);
|
|
64
|
+
const sql = connect(options.sourceUrl);
|
|
65
|
+
const reserved = await sql.reserve();
|
|
66
|
+
try {
|
|
67
|
+
await checkSupabase(reserved);
|
|
68
|
+
await reserved`begin isolation level repeatable read read only`;
|
|
69
|
+
const [exported] = await reserved`select pg_export_snapshot() as snapshot`;
|
|
70
|
+
const snapshot = exported.snapshot;
|
|
71
|
+
const source = await readSource(reserved);
|
|
72
|
+
const created = await checkTarget(options.targetUrl, source.tables);
|
|
73
|
+
if (created.length > 0) out(`created the roles ${created.join(", ")} in the project's database\n`);
|
|
74
|
+
await state.prepare();
|
|
75
|
+
const schemaFile = path.join(state.dir, "schema.sql");
|
|
76
|
+
const tableArgs = [...source.schemas.map((schema) => `--schema=${pattern(schema)}`), ...platformMigrationTables.map((table) => `--exclude-table=${table.split(".").map(pattern).join(".")}`)];
|
|
77
|
+
await runPgTool("pg_dump", options.sourceUrl, [
|
|
78
|
+
"--schema-only",
|
|
79
|
+
"--no-owner",
|
|
80
|
+
`--snapshot=${snapshot}`,
|
|
81
|
+
...tableArgs,
|
|
82
|
+
`--file=${schemaFile}`
|
|
83
|
+
]);
|
|
84
|
+
await runPgTool("pg_dump", options.sourceUrl, [
|
|
85
|
+
"--data-only",
|
|
86
|
+
`--snapshot=${snapshot}`,
|
|
87
|
+
...tableArgs,
|
|
88
|
+
`--file=${state.data}`
|
|
89
|
+
]);
|
|
90
|
+
await reserved`commit`;
|
|
91
|
+
const migration = schemaMigration(await readFile(schemaFile, "utf8"), {
|
|
92
|
+
schemas: source.schemas,
|
|
93
|
+
extensions: source.trusted
|
|
94
|
+
});
|
|
95
|
+
await rm(schemaFile);
|
|
96
|
+
await mkdir(options.migrationsDir, { recursive: true });
|
|
97
|
+
const file = nextMigrationName(await readdir(options.migrationsDir), "supabase_schema");
|
|
98
|
+
await writeFile(path.join(options.migrationsDir, file), migration.text, { flag: "wx" });
|
|
99
|
+
const { trusted, ...facts } = source;
|
|
100
|
+
await state.writeManifest({
|
|
101
|
+
migration: file,
|
|
102
|
+
leftOut: migration.leftOut,
|
|
103
|
+
checkout,
|
|
104
|
+
functions: await edgeFunctions(options.projectDir),
|
|
105
|
+
...facts
|
|
106
|
+
});
|
|
107
|
+
out(`wrote ${path.relative(options.projectDir, path.join(options.migrationsDir, file))}, the schemas ${source.schemas.join(", ")}\n`);
|
|
108
|
+
out(`dumped ${source.tables.length} tables' data into ${path.relative(options.projectDir, state.data)}, which git ignores\n`);
|
|
109
|
+
out("next: apply the migration with the project's migrations, then run `protobase import supabase` again to load the data\n");
|
|
110
|
+
} finally {
|
|
111
|
+
reserved.release();
|
|
112
|
+
await sql.end();
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
//#endregion
|
|
116
|
+
export { runDumpPhase };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
//#region src/supabase/extensions.ts
|
|
2
|
+
/**
|
|
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.
|
|
5
|
+
*/
|
|
6
|
+
const platformExtensions = /* @__PURE__ */ new Set([
|
|
7
|
+
"plpgsql",
|
|
8
|
+
"pg_graphql",
|
|
9
|
+
"supabase_vault",
|
|
10
|
+
"pgsodium",
|
|
11
|
+
"pg_stat_statements"
|
|
12
|
+
]);
|
|
13
|
+
/**
|
|
14
|
+
* The app's extensions, by what the import does with them: trusted ones a database owner may create, so the
|
|
15
|
+
* migration creates them in the schema they had; untrusted ones need a superuser, so the report lists them.
|
|
16
|
+
*/
|
|
17
|
+
const appExtensions = (extensions) => {
|
|
18
|
+
const app = extensions.filter((extension) => !platformExtensions.has(extension.name));
|
|
19
|
+
return {
|
|
20
|
+
trusted: app.filter((extension) => extension.trusted),
|
|
21
|
+
untrusted: app.filter((extension) => !extension.trusted)
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
const quoted = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
25
|
+
/** The statements that create `extensions` where the dump expects them. */
|
|
26
|
+
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("");
|
|
28
|
+
};
|
|
29
|
+
//#endregion
|
|
30
|
+
export { appExtensions, createExtensions };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
4
|
+
//#region src/supabase/import-state.ts
|
|
5
|
+
/**
|
|
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, readable by its owner only until the load deletes it; the manifest; and the report.
|
|
8
|
+
*/
|
|
9
|
+
const importState = (projectDir) => {
|
|
10
|
+
const dir = path.join(projectDir, "supabase-import");
|
|
11
|
+
const files = {
|
|
12
|
+
data: path.join(dir, "data.sql"),
|
|
13
|
+
load: path.join(dir, "load.sql"),
|
|
14
|
+
manifest: path.join(dir, "import.json"),
|
|
15
|
+
report: path.join(dir, "report.md")
|
|
16
|
+
};
|
|
17
|
+
return {
|
|
18
|
+
dir,
|
|
19
|
+
...files,
|
|
20
|
+
/** Creates the folder, ignored by git, and an empty data file only its owner may read, for pg_dump to fill. */
|
|
21
|
+
prepare: async () => {
|
|
22
|
+
await mkdir(dir, {
|
|
23
|
+
recursive: true,
|
|
24
|
+
mode: 448
|
|
25
|
+
});
|
|
26
|
+
await ignoreInGit(projectDir, "/supabase-import/");
|
|
27
|
+
await writeFile(files.data, "", { mode: 384 });
|
|
28
|
+
},
|
|
29
|
+
hasData: () => existsSync(files.data),
|
|
30
|
+
hasManifest: () => existsSync(files.manifest),
|
|
31
|
+
readManifest: async () => JSON.parse(await readFile(files.manifest, "utf8")),
|
|
32
|
+
writeManifest: (manifest) => writeFile(files.manifest, `${JSON.stringify(manifest, null, 2)}\n`, { mode: 384 })
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
/** Adds `entry` to the project's .gitignore unless a line already says it. */
|
|
36
|
+
const ignoreInGit = async (projectDir, entry) => {
|
|
37
|
+
const file = path.join(projectDir, ".gitignore");
|
|
38
|
+
const text = existsSync(file) ? await readFile(file, "utf8") : "";
|
|
39
|
+
if (text.split("\n").some((line) => line.trim() === entry || line.trim() === entry.slice(1))) return;
|
|
40
|
+
await appendFile(file, `${text === "" || text.endsWith("\n") ? "" : "\n"}${entry}\n`);
|
|
41
|
+
};
|
|
42
|
+
//#endregion
|
|
43
|
+
export { importState };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { connect } from "../db/connect.js";
|
|
2
|
+
import { runDoctor } from "../doctor/run.js";
|
|
3
|
+
import { runScaffold } from "../scaffold/run.js";
|
|
4
|
+
import { importState } from "./import-state.js";
|
|
5
|
+
import { runPgTool } from "./pg-tools.js";
|
|
6
|
+
import { loadScript, qualified } from "./load-script.js";
|
|
7
|
+
import { existingTables, filledTables, otherTables } from "./target-checks.js";
|
|
8
|
+
import { importReport } from "./report.js";
|
|
9
|
+
import { existsSync } from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { rm, writeFile } from "node:fs/promises";
|
|
12
|
+
//#region src/supabase/load-phase.ts
|
|
13
|
+
/** Schemas the import restores that scaffolding leaves alone: Supabase Auth's and Storage's own tables are no resources. */
|
|
14
|
+
const platformSchemas = ["auth", "storage"];
|
|
15
|
+
/** Fails unless every dumped table exists on the target, created by the applied migration, and holds no rows yet. */
|
|
16
|
+
const checkReady = async (url, manifest) => {
|
|
17
|
+
const sql = connect(url);
|
|
18
|
+
try {
|
|
19
|
+
const existing = new Set(await existingTables(sql, manifest.tables));
|
|
20
|
+
const missing = manifest.tables.filter((table) => !existing.has(qualified(table)));
|
|
21
|
+
if (missing.length > 0) throw new Error(`The project's database lacks ${missing.length} of the imported tables, such as ${missing.slice(0, 5).map((table) => `${table.schema}.${table.table}`).join(", ")}: apply ${manifest.migration} with the project's migrations first`);
|
|
22
|
+
const filled = await filledTables(sql, manifest.tables);
|
|
23
|
+
if (filled.length > 0) throw new Error(`The project's database already has rows in ${filled.slice(0, 5).join(", ")}; the import loads into empty tables only`);
|
|
24
|
+
} finally {
|
|
25
|
+
await sql.end();
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
/** `protobase doctor`'s output on the config at `configDir`, or `undefined` when there is none. */
|
|
29
|
+
const doctorOutput = async (url, configDir) => {
|
|
30
|
+
if (!existsSync(path.join(configDir, "index.ts"))) return void 0;
|
|
31
|
+
let text = "";
|
|
32
|
+
await runDoctor({
|
|
33
|
+
url,
|
|
34
|
+
configDir
|
|
35
|
+
}, (line) => text += line);
|
|
36
|
+
return text;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* The import's second run, once the schema migration is applied: loads the data dump in one transaction, deletes it,
|
|
40
|
+
* scaffolds the config from the imported tables of the app's schemas, leaving the project's own alone, and writes the
|
|
41
|
+
* report.
|
|
42
|
+
*/
|
|
43
|
+
const runLoadPhase = async (options, out) => {
|
|
44
|
+
const state = importState(options.projectDir);
|
|
45
|
+
const manifest = await state.readManifest();
|
|
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
|
+
await checkReady(options.targetUrl, manifest);
|
|
48
|
+
await writeFile(state.load, loadScript(state.data, manifest.tables), { mode: 384 });
|
|
49
|
+
await runPgTool("psql", options.targetUrl, [
|
|
50
|
+
"--no-psqlrc",
|
|
51
|
+
"--quiet",
|
|
52
|
+
"--single-transaction",
|
|
53
|
+
"--set=ON_ERROR_STOP=1",
|
|
54
|
+
`--file=${state.load}`
|
|
55
|
+
]);
|
|
56
|
+
await rm(state.load);
|
|
57
|
+
await rm(state.data);
|
|
58
|
+
out(`loaded ${manifest.tables.reduce((sum, table) => sum + table.rows, 0)} rows into ${manifest.tables.length} tables; each count matches the source\n`);
|
|
59
|
+
const schemas = manifest.schemas.filter((schema) => !platformSchemas.includes(schema));
|
|
60
|
+
const sql = connect(options.targetUrl);
|
|
61
|
+
const excludes = await otherTables(sql, schemas, manifest.tables).finally(() => sql.end());
|
|
62
|
+
for (const schema of schemas) await runScaffold({
|
|
63
|
+
url: options.targetUrl,
|
|
64
|
+
target: schema,
|
|
65
|
+
configDir: options.configDir,
|
|
66
|
+
yes: true,
|
|
67
|
+
dryRun: false,
|
|
68
|
+
ui: [],
|
|
69
|
+
excludes
|
|
70
|
+
}, out);
|
|
71
|
+
await writeFile(state.report, importReport(manifest, await doctorOutput(options.targetUrl, options.configDir)), { mode: 384 });
|
|
72
|
+
out(`wrote ${path.relative(options.projectDir, state.report)}: what the import could not carry over\n`);
|
|
73
|
+
};
|
|
74
|
+
//#endregion
|
|
75
|
+
export { runLoadPhase };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/supabase/load-script.ts
|
|
2
|
+
const identifier = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
3
|
+
const qualified = (table) => `${identifier(table.schema)}.${identifier(table.table)}`;
|
|
4
|
+
const literal = (text) => `'${text.replaceAll("'", "''")}'`;
|
|
5
|
+
/** Fails the transaction when a table holds other than the source's number of rows. */
|
|
6
|
+
const checkRows = (table) => `DO $$ DECLARE found bigint; BEGIN SELECT count(*) INTO found FROM ${qualified(table)}; IF found <> ${table.rows} THEN RAISE EXCEPTION 'table %.% has % rows after the load, the source had ${table.rows}', ${literal(table.schema)}, ${literal(table.table)}, found; END IF; END $$;\n`;
|
|
7
|
+
/**
|
|
8
|
+
* The psql script that loads the data dump at `dataFile` into `tables`, for `psql --single-transaction`: the app's
|
|
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; every table's rows are counted against the source's before the transaction commits.
|
|
11
|
+
*/
|
|
12
|
+
const loadScript = (dataFile, tables) => [
|
|
13
|
+
...tables.map((table) => `ALTER TABLE ${qualified(table)} DISABLE TRIGGER USER;\n`),
|
|
14
|
+
`\\i ${literal(dataFile)}\n`,
|
|
15
|
+
...tables.map((table) => `ALTER TABLE ${qualified(table)} ENABLE TRIGGER USER;\n`),
|
|
16
|
+
...tables.map(checkRows)
|
|
17
|
+
].join("");
|
|
18
|
+
//#endregion
|
|
19
|
+
export { loadScript, qualified };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
//#region src/supabase/pg-tools.ts
|
|
4
|
+
const exec = promisify(execFile);
|
|
5
|
+
/**
|
|
6
|
+
* The connection string without its password, which goes to the tool in `PGPASSWORD` instead, so no command line or
|
|
7
|
+
* error message carries it.
|
|
8
|
+
*/
|
|
9
|
+
const toolConnection = (url) => {
|
|
10
|
+
const parsed = new URL(url);
|
|
11
|
+
const password = decodeURIComponent(parsed.password);
|
|
12
|
+
parsed.password = "";
|
|
13
|
+
return {
|
|
14
|
+
dbname: parsed.toString(),
|
|
15
|
+
env: password ? { PGPASSWORD: password } : {}
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
/** Runs PostgreSQL's client tool `tool` (pg_dump, psql) on the database at `url`, failing with what it wrote to stderr. */
|
|
19
|
+
const runPgTool = async (tool, url, args) => {
|
|
20
|
+
const { dbname, env } = toolConnection(url);
|
|
21
|
+
try {
|
|
22
|
+
await exec(tool, [`--dbname=${dbname}`, ...args], {
|
|
23
|
+
env: {
|
|
24
|
+
...process.env,
|
|
25
|
+
...env
|
|
26
|
+
},
|
|
27
|
+
maxBuffer: 67108864
|
|
28
|
+
});
|
|
29
|
+
} catch (error) {
|
|
30
|
+
const failure = error;
|
|
31
|
+
if (failure.code === "ENOENT") throw new Error(`${tool} is not on PATH: install the PostgreSQL client tools, of the source database's major version or newer`);
|
|
32
|
+
if (typeof failure.stderr === "string") throw new Error(`${tool} failed: ${failure.stderr.trim()}`);
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
//#endregion
|
|
37
|
+
export { runPgTool, toolConnection };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { loadNearestEnvFile } from "../dev/env.js";
|
|
2
|
+
import { runSupabaseImport } from "./run.js";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
//#region src/supabase/register.ts
|
|
5
|
+
const out = (text) => process.stdout.write(text);
|
|
6
|
+
const variable = (name) => {
|
|
7
|
+
const value = process.env[name];
|
|
8
|
+
if (!value) throw new Error(`Environment variable ${name} is not set`);
|
|
9
|
+
return value;
|
|
10
|
+
};
|
|
11
|
+
const registerImport = (program) => {
|
|
12
|
+
program.command("import").description("Turn another platform's project into this Protobase project").command("supabase").description("Import a Supabase database into the project in the current directory. The first run dumps it and writes its schemas as the project's next migration; once the project's migrations are applied, the second run loads the data, scaffolds the config and writes supabase-import/report.md").argument("[source]", "the Supabase database's connection string, for the first run").option("--source-env <variable>", "read the Supabase connection string from this environment variable").option("--env <variable>", "environment variable holding the project's database URL", "DATABASE_URL").option("--dir <dir>", "migrations folder", "db/migrations").option("--config <dir>", "config folder", "config").action(async (source, opts) => {
|
|
13
|
+
if (source && opts.sourceEnv) throw new Error("Pass either a connection string or --source-env, not both");
|
|
14
|
+
const projectDir = process.cwd();
|
|
15
|
+
loadNearestEnvFile(projectDir);
|
|
16
|
+
await runSupabaseImport({
|
|
17
|
+
sourceUrl: source ?? (opts.sourceEnv ? variable(opts.sourceEnv) : void 0),
|
|
18
|
+
targetUrl: variable(opts.env),
|
|
19
|
+
projectDir,
|
|
20
|
+
migrationsDir: path.resolve(opts.dir),
|
|
21
|
+
configDir: path.resolve(opts.config)
|
|
22
|
+
}, out);
|
|
23
|
+
});
|
|
24
|
+
};
|
|
25
|
+
//#endregion
|
|
26
|
+
export { registerImport };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/supabase/report.ts
|
|
2
|
+
/** Protobase Cloud's Starter plan holds this much data; the import reports a larger database, it does not refuse it. */
|
|
3
|
+
const starterBytes = 524288e3;
|
|
4
|
+
const megabytes = (bytes) => `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
5
|
+
const code = (text) => `\`${text.replaceAll("`", "'")}\``;
|
|
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
|
+
/**
|
|
8
|
+
* The import's report: what it loaded, and what it could not carry over, for a person or their AI assistant to finish.
|
|
9
|
+
* `doctor` is `protobase doctor`'s output on the scaffolded config, or `undefined` when there was no config to check.
|
|
10
|
+
*/
|
|
11
|
+
const importReport = (manifest, doctor) => [
|
|
12
|
+
"# Supabase import\n",
|
|
13
|
+
`Schemas ${manifest.schemas.join(", ")}, restored by the migration \`${manifest.migration}\`, and their data, loaded in one transaction.\n`,
|
|
14
|
+
`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
|
+
`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
|
+
"## 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",
|
|
17
|
+
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
|
+
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", "Their values stay in Supabase. Enter each again where the app reads it, such as an environment variable.", manifest.vaultSecrets?.map((secret) => `${secret.name ?? "unnamed"}${secret.description ? `: ${secret.description}` : ""}`)),
|
|
20
|
+
section("Untrusted extensions", "Only a superuser may create these, so the migration does not. Replace what the app uses them for, or have the database's administrator create them.", manifest.untrustedExtensions.map((extension) => `${extension.name} (schema ${extension.schema})`)),
|
|
21
|
+
section("HTTP triggers", "These triggers call out over HTTP with pg_net or a database webhook. The migration keeps a trigger calling the app's own function, but pg_net is not there to send; it leaves out a webhook's. Move each call to a Protobase event subscription or job.", manifest.httpTriggers.map((trigger) => `${trigger.trigger} on ${trigger.schema}.${trigger.table}, calling ${trigger.function}`)),
|
|
22
|
+
section("Edge Functions", "`supabase/functions` holds these, which the import does not convert.", manifest.functions),
|
|
23
|
+
`## 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
|
+
].join("\n");
|
|
25
|
+
//#endregion
|
|
26
|
+
export { importReport };
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { splitDump } from "./statements.js";
|
|
2
|
+
import { tokenize, wordsAt } from "./tokens.js";
|
|
3
|
+
//#region src/supabase/rewrite.ts
|
|
4
|
+
/**
|
|
5
|
+
* Supabase's own roles, which a Protobase database does not have: the dashboard's, the platform services', the API
|
|
6
|
+
* gateway's login role, and `postgres`, the role the dump was taken as. The API roles `anon`, `authenticated` and
|
|
7
|
+
* `service_role` are not among them; the app's grants and policies name those.
|
|
8
|
+
*/
|
|
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
|
+
const keep = (text) => ({ keep: text });
|
|
13
|
+
/** The grantee list of a GRANT or REVOKE: the role names after its last top-level TO (or FROM), up to its options. */
|
|
14
|
+
const grantees = (statement, tokens, from, keyword) => {
|
|
15
|
+
const at = tokens.findLastIndex((token, i) => i >= from && token.depth === 0 && wordsAt(statement, tokens, i, [keyword]));
|
|
16
|
+
if (at === -1) return void 0;
|
|
17
|
+
const end = tokens.findIndex((token, i) => i > at && (token.word === "with" || token.word === "granted" || statement[token.start] === ";"));
|
|
18
|
+
const names = tokens.slice(at + 1, end === -1 ? void 0 : end).filter((token) => statement[token.start] !== ",");
|
|
19
|
+
return {
|
|
20
|
+
names,
|
|
21
|
+
start: names[0]?.start ?? 0,
|
|
22
|
+
end: names.at(-1)?.end ?? 0
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* A GRANT or REVOKE from `from` on, without the Supabase roles among its grantees: dropped when it names only those,
|
|
27
|
+
* since such a statement fails where the roles do not exist.
|
|
28
|
+
*/
|
|
29
|
+
const withoutSupabaseGrantees = (statement, tokens, from) => {
|
|
30
|
+
const list = grantees(statement, tokens, from, wordsAt(statement, tokens, from, ["grant"]) ? "to" : "from");
|
|
31
|
+
if (!list) return keep(statement);
|
|
32
|
+
const kept = list.names.filter((name) => !isSupabaseRole(name.word ?? ""));
|
|
33
|
+
if (kept.length === list.names.length) return keep(statement);
|
|
34
|
+
if (kept.length === 0) return { drop: "it names only Supabase's own roles" };
|
|
35
|
+
const names = kept.map((name) => statement.slice(name.start, name.end)).join(", ");
|
|
36
|
+
return keep(statement.slice(0, list.start) + names + statement.slice(list.end));
|
|
37
|
+
};
|
|
38
|
+
const nextGrant = (statement, tokens) => tokens.findIndex((_, i) => wordsAt(statement, tokens, i, ["grant"]) || wordsAt(statement, tokens, i, ["revoke"]));
|
|
39
|
+
/** `ALTER DEFAULT PRIVILEGES` for the importing role itself: without `FOR ROLE …`, which names a Supabase role. */
|
|
40
|
+
const defaultPrivileges = (statement, tokens) => {
|
|
41
|
+
if (!wordsAt(statement, tokens, 3, ["for"])) return withoutSupabaseGrantees(statement, tokens, nextGrant(statement, tokens));
|
|
42
|
+
const next = tokens.findIndex((_, i) => i > 4 && (wordsAt(statement, tokens, i, ["in"]) || wordsAt(statement, tokens, i, ["grant"]) || wordsAt(statement, tokens, i, ["revoke"])));
|
|
43
|
+
const rewritten = statement.slice(0, tokens[3].start) + statement.slice(tokens[next].start);
|
|
44
|
+
return defaultPrivileges(rewritten, tokenize(rewritten));
|
|
45
|
+
};
|
|
46
|
+
/** A statement as it should restore on a Protobase database, or why it is left out. */
|
|
47
|
+
const rewriteStatement = (statement) => {
|
|
48
|
+
const tokens = tokenize(statement);
|
|
49
|
+
const at = (...words) => wordsAt(statement, tokens, 0, words);
|
|
50
|
+
if (at("grant") || at("revoke")) return withoutSupabaseGrantees(statement, tokens, 0);
|
|
51
|
+
if (at("alter", "default", "privileges")) return defaultPrivileges(statement, tokens);
|
|
52
|
+
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
|
+
if (at("alter", "publication") || at("create", "publication")) return { drop: "publications are Supabase Realtime's; the report lists their tables" };
|
|
54
|
+
if (at("create", "trigger") || at("create", "constraint", "trigger") || at("create", "or", "replace", "trigger")) {
|
|
55
|
+
const call = tokens.findIndex((_, i) => wordsAt(statement, tokens, i, ["execute", "function"]) || wordsAt(statement, tokens, i, ["execute", "procedure"]));
|
|
56
|
+
const schema = tokens[call + 2]?.word;
|
|
57
|
+
if (call !== -1 && schema && webhookSchemas.includes(schema) && statement[tokens[call + 3]?.start ?? 0] === ".") return { drop: "it calls a Supabase database webhook; the report lists it" };
|
|
58
|
+
}
|
|
59
|
+
return keep(statement);
|
|
60
|
+
};
|
|
61
|
+
/** A left-out statement as comment lines, with why. */
|
|
62
|
+
const leftOut = (statement, reason) => `-- Left out by protobase import supabase: ${reason}.\n${statement.replace(/^/gm, "-- ")}`;
|
|
63
|
+
/**
|
|
64
|
+
* 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, and how many statements it leaves out. Statements are parsed, so a
|
|
66
|
+
* rule never touches a function body or a string.
|
|
67
|
+
*/
|
|
68
|
+
const rewriteSchemaDump = (dump) => {
|
|
69
|
+
let leftOutCount = 0;
|
|
70
|
+
return {
|
|
71
|
+
sql: splitDump(dump).map((piece) => {
|
|
72
|
+
if (piece.kind === "meta") return "";
|
|
73
|
+
if (piece.kind === "gap") return piece.text;
|
|
74
|
+
const verdict = rewriteStatement(piece.text);
|
|
75
|
+
if ("keep" in verdict) return verdict.keep;
|
|
76
|
+
leftOutCount++;
|
|
77
|
+
return leftOut(piece.text, verdict.drop);
|
|
78
|
+
}).join(""),
|
|
79
|
+
leftOut: leftOutCount
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
//#endregion
|
|
83
|
+
export { isSupabaseRole, rewriteSchemaDump };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { importState } from "./import-state.js";
|
|
2
|
+
import { runDumpPhase } from "./dump-phase.js";
|
|
3
|
+
import { runLoadPhase } from "./load-phase.js";
|
|
4
|
+
//#region src/supabase/run.ts
|
|
5
|
+
/**
|
|
6
|
+
* `protobase import supabase`, in two runs with the project's migrations between them: the first dumps the source
|
|
7
|
+
* and writes the schema migration, the second loads the data into the migrated database. Which run this is follows
|
|
8
|
+
* from `supabase-import/`: a manifest with its data dump is an import waiting for its load.
|
|
9
|
+
*/
|
|
10
|
+
const runSupabaseImport = async (options, out) => {
|
|
11
|
+
const state = importState(options.projectDir);
|
|
12
|
+
const pending = state.hasManifest() && state.hasData();
|
|
13
|
+
if (pending && options.sourceUrl) throw new Error("An import is waiting in supabase-import/: apply its migration and run `protobase import supabase` without a source to load it, or remove supabase-import/ to start over");
|
|
14
|
+
if (pending) return runLoadPhase(options, out);
|
|
15
|
+
if (state.hasManifest()) throw new Error(`This project imported a Supabase database already (see ${state.report}); remove supabase-import/ to import again`);
|
|
16
|
+
if (!options.sourceUrl) throw new Error("Pass the Supabase database's connection string, or --source-env <VARIABLE>: the session pooler's or the direct one, for the postgres role");
|
|
17
|
+
return runDumpPhase({
|
|
18
|
+
...options,
|
|
19
|
+
sourceUrl: options.sourceUrl
|
|
20
|
+
}, out);
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
export { runSupabaseImport };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { createExtensions } from "./extensions.js";
|
|
2
|
+
import { rewriteSchemaDump } from "./rewrite.js";
|
|
3
|
+
import { resetSettings, sessionSettings } from "./session-settings.js";
|
|
4
|
+
//#region src/supabase/schema-migration.ts
|
|
5
|
+
/**
|
|
6
|
+
* The migration that restores a Supabase database's schemas: the trusted extensions they use, the schema dump as it
|
|
7
|
+
* restores without a superuser, and the session settings the dump changed put back for the migrations after it; and
|
|
8
|
+
* how many of the dump's statements it leaves out.
|
|
9
|
+
*/
|
|
10
|
+
const schemaMigration = (dump, input) => {
|
|
11
|
+
const rewritten = rewriteSchemaDump(dump);
|
|
12
|
+
return {
|
|
13
|
+
text: [
|
|
14
|
+
`-- The schemas ${input.schemas.join(", ")} of a Supabase database, written by \`protobase import supabase\`.\n`,
|
|
15
|
+
"-- Applied with the project's other migrations. Statements naming Supabase's own roles are left out as comments.\n\n",
|
|
16
|
+
createExtensions(input.extensions),
|
|
17
|
+
"\n",
|
|
18
|
+
rewritten.sql,
|
|
19
|
+
"\n",
|
|
20
|
+
resetSettings(sessionSettings(dump))
|
|
21
|
+
].join(""),
|
|
22
|
+
leftOut: rewritten.leftOut
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
//#endregion
|
|
26
|
+
export { schemaMigration };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { splitDump } from "./statements.js";
|
|
2
|
+
import { tokenize, wordsAt } from "./tokens.js";
|
|
3
|
+
//#region src/supabase/session-settings.ts
|
|
4
|
+
/**
|
|
5
|
+
* The settings a dump changes for the rest of its session: each `SET name = …` and `set_config('name', …)`. The
|
|
6
|
+
* project's migrations run one after another on one connection, so a migration made from a dump resets them at its
|
|
7
|
+
* end, and the next file runs as it would have without it.
|
|
8
|
+
*/
|
|
9
|
+
const sessionSettings = (dump) => {
|
|
10
|
+
const names = /* @__PURE__ */ new Set();
|
|
11
|
+
for (const piece of splitDump(dump)) {
|
|
12
|
+
if (piece.kind !== "statement") continue;
|
|
13
|
+
const tokens = tokenize(piece.text);
|
|
14
|
+
if (wordsAt(piece.text, tokens, 0, ["set"]) && !wordsAt(piece.text, tokens, 1, ["local"])) names.add(tokens[1].word);
|
|
15
|
+
const call = wordsAt(piece.text, tokens, 0, ["select"]) ? tokens.findIndex((_, i) => wordsAt(piece.text, tokens, i, ["set_config"])) : -1;
|
|
16
|
+
const name = call === -1 ? void 0 : tokens[call + 2];
|
|
17
|
+
if (name && piece.text[name.start] === "'") names.add(piece.text.slice(name.start + 1, name.end - 1));
|
|
18
|
+
}
|
|
19
|
+
return [...names];
|
|
20
|
+
};
|
|
21
|
+
/** Statements that put back each of `names`. */
|
|
22
|
+
const resetSettings = (names) => names.map((name) => `RESET ${name};\n`).join("");
|
|
23
|
+
//#endregion
|
|
24
|
+
export { resetSettings, sessionSettings };
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
//#region src/supabase/source-facts.ts
|
|
2
|
+
/**
|
|
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. auth and storage are the platform's too, but
|
|
5
|
+
* the app's tables point at them and its triggers and policies live in them, so the import carries them over.
|
|
6
|
+
*/
|
|
7
|
+
const platformSchemas = [
|
|
8
|
+
"extensions",
|
|
9
|
+
"graphql",
|
|
10
|
+
"graphql_public",
|
|
11
|
+
"realtime",
|
|
12
|
+
"_realtime",
|
|
13
|
+
"vault",
|
|
14
|
+
"pgsodium",
|
|
15
|
+
"pgsodium_masks",
|
|
16
|
+
"supabase_functions",
|
|
17
|
+
"supabase_migrations",
|
|
18
|
+
"cron",
|
|
19
|
+
"net",
|
|
20
|
+
"pgbouncer",
|
|
21
|
+
"_analytics",
|
|
22
|
+
"pgtle"
|
|
23
|
+
];
|
|
24
|
+
/** The tables in auth and storage that record the platform's own migrations, which Protobase never runs. */
|
|
25
|
+
const platformMigrationTables = ["auth.schema_migrations", "storage.migrations"];
|
|
26
|
+
/** What marks a database as Supabase's: its auth, storage and migrations schemas and its roles. */
|
|
27
|
+
const databaseMarkers = async (sql) => {
|
|
28
|
+
const [row] = await sql`
|
|
29
|
+
select
|
|
30
|
+
array(select nspname::text from pg_namespace where nspname in ('auth', 'storage', 'supabase_migrations') order by 1) as schemas,
|
|
31
|
+
array(select rolname::text from pg_roles where rolname in ('anon', 'authenticated', 'service_role', 'supabase_admin') order by 1) as roles
|
|
32
|
+
`;
|
|
33
|
+
return row;
|
|
34
|
+
};
|
|
35
|
+
/** auth, storage and every schema the app made, which the dumps take. */
|
|
36
|
+
const appSchemas = async (sql) => {
|
|
37
|
+
return (await sql`
|
|
38
|
+
select n.nspname as name from pg_namespace n
|
|
39
|
+
where not starts_with(n.nspname, 'pg_') and n.nspname <> 'information_schema' and n.nspname <> all(${platformSchemas})
|
|
40
|
+
and not exists (select 1 from pg_depend d where d.classid = 'pg_namespace'::regclass and d.objid = n.oid and d.deptype = 'e')
|
|
41
|
+
order by 1
|
|
42
|
+
`).map((row) => row.name);
|
|
43
|
+
};
|
|
44
|
+
/** The tables of `schemas` the data dump fills, each with its rows counted now. */
|
|
45
|
+
const dumpedTables = async (sql, schemas) => {
|
|
46
|
+
const tables = await sql`
|
|
47
|
+
select n.nspname as schema, c.relname as table from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
48
|
+
where c.relkind = 'r' and n.nspname = any(${schemas}) and n.nspname || '.' || c.relname <> all(${platformMigrationTables})
|
|
49
|
+
and not exists (select 1 from pg_depend d where d.classid = 'pg_class'::regclass and d.objid = c.oid and d.deptype = 'e')
|
|
50
|
+
order by 1, 2
|
|
51
|
+
`;
|
|
52
|
+
const counted = [];
|
|
53
|
+
for (const table of tables) {
|
|
54
|
+
const [row] = await sql`select count(*) as rows from ${sql(table.schema)}.${sql(table.table)}`;
|
|
55
|
+
counted.push({
|
|
56
|
+
...table,
|
|
57
|
+
rows: Number(row.rows)
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return counted;
|
|
61
|
+
};
|
|
62
|
+
/** The size on disk of `tables`, with their indexes and TOAST, in bytes. */
|
|
63
|
+
const tablesSize = async (sql, tables) => {
|
|
64
|
+
const [row] = await sql`
|
|
65
|
+
select sum(pg_total_relation_size(c.oid)) as bytes from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
66
|
+
where n.nspname || '.' || c.relname = any(${tables.map((table) => `${table.schema}.${table.table}`)})
|
|
67
|
+
`;
|
|
68
|
+
return Number(row.bytes ?? 0);
|
|
69
|
+
};
|
|
70
|
+
const extensions = (sql) => sql`
|
|
71
|
+
select e.extname as name, n.nspname as schema, coalesce(v.trusted, false) as trusted
|
|
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
|
|
75
|
+
`;
|
|
76
|
+
/** Whether the importing role may read `table`, which exists only when its feature is on. */
|
|
77
|
+
const readable = async (sql, table) => {
|
|
78
|
+
const [row] = await sql`select to_regclass(${table}) is not null and has_table_privilege(${table}, 'select') as readable`;
|
|
79
|
+
return row.readable;
|
|
80
|
+
};
|
|
81
|
+
/** pg_cron's jobs, which the cron schema holds and the dump leaves out; `undefined` when the role may not read them. */
|
|
82
|
+
const cronJobs = async (sql) => {
|
|
83
|
+
const [row] = await sql`select to_regclass('cron.job') is not null as exists`;
|
|
84
|
+
if (!row.exists) return [];
|
|
85
|
+
if (!await readable(sql, "cron.job")) return void 0;
|
|
86
|
+
return sql`select jobname as name, schedule, command from cron.job order by jobid`;
|
|
87
|
+
};
|
|
88
|
+
/** Vault's secrets by name; their values stay in the source, since a person enters them again. */
|
|
89
|
+
const vaultSecrets = async (sql) => {
|
|
90
|
+
const [row] = await sql`select to_regclass('vault.secrets') is not null as exists`;
|
|
91
|
+
if (!row.exists) return [];
|
|
92
|
+
if (!await readable(sql, "vault.secrets")) return void 0;
|
|
93
|
+
return sql`select name, description from vault.secrets order by name`;
|
|
94
|
+
};
|
|
95
|
+
const realtimeTables = (sql) => sql`
|
|
96
|
+
select schemaname as schema, tablename as table from pg_publication_tables where pubname = 'supabase_realtime' order by 1, 2
|
|
97
|
+
`;
|
|
98
|
+
const httpCall = String.raw`\mnet\.http_(get|post|delete)\M`;
|
|
99
|
+
/** Triggers of `schemas` that call out over HTTP: database webhooks, and functions calling pg_net's `net.http_*`. */
|
|
100
|
+
const httpTriggers = (sql, schemas) => sql`
|
|
101
|
+
select tn.nspname as schema, c.relname as table, t.tgname as trigger, pn.nspname || '.' || p.proname as function
|
|
102
|
+
from pg_trigger t
|
|
103
|
+
join pg_class c on c.oid = t.tgrelid join pg_namespace tn on tn.oid = c.relnamespace
|
|
104
|
+
join pg_proc p on p.oid = t.tgfoid join pg_namespace pn on pn.oid = p.pronamespace
|
|
105
|
+
where not t.tgisinternal and tn.nspname = any(${schemas})
|
|
106
|
+
and (pn.nspname = 'supabase_functions' or p.prosrc ~ ${httpCall})
|
|
107
|
+
order by 1, 2, 3
|
|
108
|
+
`;
|
|
109
|
+
//#endregion
|
|
110
|
+
export { appSchemas, cronJobs, databaseMarkers, dumpedTables, extensions, httpTriggers, platformMigrationTables, realtimeTables, tablesSize, vaultSecrets };
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
//#region src/supabase/statements.ts
|
|
2
|
+
const copyFromStdin = /^COPY\s[\s\S]*\sFROM\s+stdin;$/i;
|
|
3
|
+
/** Where the dollar quote opening at `at` ends, past its closing tag, or `undefined` when `at` opens none. */
|
|
4
|
+
const dollarQuoteEnd = (script, at) => {
|
|
5
|
+
const tag = /^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/.exec(script.slice(at, at + 64))?.[0];
|
|
6
|
+
if (!tag) return void 0;
|
|
7
|
+
const close = script.indexOf(tag, at + tag.length);
|
|
8
|
+
if (close === -1) throw new Error(`Unterminated dollar quote ${tag} in the dump`);
|
|
9
|
+
return close + tag.length;
|
|
10
|
+
};
|
|
11
|
+
/** Where the quoted text opening at `at` with `quote` ends, past its closing quote. */
|
|
12
|
+
const quotedEnd = (script, at, quote, backslashEscapes) => {
|
|
13
|
+
for (let i = at + 1; i < script.length; i++) if (backslashEscapes && script[i] === "\\") i++;
|
|
14
|
+
else if (script[i] === quote && script[i + 1] === quote) i++;
|
|
15
|
+
else if (script[i] === quote) return i + 1;
|
|
16
|
+
throw new Error("Unterminated quoted text in the dump");
|
|
17
|
+
};
|
|
18
|
+
const lineEnd = (script, at) => {
|
|
19
|
+
const newline = script.indexOf("\n", at);
|
|
20
|
+
return newline === -1 ? script.length : newline + 1;
|
|
21
|
+
};
|
|
22
|
+
/** Where the block comment opening at `at` ends; they nest in Postgres. */
|
|
23
|
+
const blockCommentEnd = (script, at) => {
|
|
24
|
+
let depth = 0;
|
|
25
|
+
for (let i = at; i < script.length - 1; i++) if (script[i] === "/" && script[i + 1] === "*") depth++, i++;
|
|
26
|
+
else if (script[i] === "*" && script[i + 1] === "/") {
|
|
27
|
+
i++;
|
|
28
|
+
if (--depth === 0) return i + 1;
|
|
29
|
+
}
|
|
30
|
+
throw new Error("Unterminated block comment in the dump");
|
|
31
|
+
};
|
|
32
|
+
/** Where a statement starting at `at` ends, past its `;`, skipping quoted text and comments. */
|
|
33
|
+
const statementEnd = (script, at) => {
|
|
34
|
+
for (let i = at; i < script.length;) {
|
|
35
|
+
const char = script[i];
|
|
36
|
+
if (char === ";") return i + 1;
|
|
37
|
+
if (char === "'") i = quotedEnd(script, i, "'", /[Ee]/.test(script[i - 1] ?? "") && !/[A-Za-z_0-9]/.test(script[i - 2] ?? ""));
|
|
38
|
+
else if (char === "\"") i = quotedEnd(script, i, "\"", false);
|
|
39
|
+
else if (char === "-" && script[i + 1] === "-") i = lineEnd(script, i);
|
|
40
|
+
else if (char === "/" && script[i + 1] === "*") i = blockCommentEnd(script, i);
|
|
41
|
+
else if (char === "$" && !/[A-Za-z_0-9]/.test(script[i - 1] ?? "")) i = dollarQuoteEnd(script, i) ?? i + 1;
|
|
42
|
+
else i++;
|
|
43
|
+
}
|
|
44
|
+
throw new Error(`Unterminated statement in the dump: ${script.slice(at, at + 80)}`);
|
|
45
|
+
};
|
|
46
|
+
/** Where a COPY statement's data ending at `at` ends, past its `\.` line. */
|
|
47
|
+
const copyDataEnd = (script, at) => {
|
|
48
|
+
const start = lineEnd(script, at);
|
|
49
|
+
const end = script.indexOf("\n\\.\n", start - 1);
|
|
50
|
+
if (end === -1) throw new Error("Unterminated COPY data in the dump");
|
|
51
|
+
return end + 4;
|
|
52
|
+
};
|
|
53
|
+
/** Splits a pg_dump plain-text script into its pieces. */
|
|
54
|
+
const splitDump = (script) => {
|
|
55
|
+
const pieces = [];
|
|
56
|
+
let gapStart = 0;
|
|
57
|
+
const flushGap = (to) => {
|
|
58
|
+
if (to > gapStart) pieces.push({
|
|
59
|
+
kind: "gap",
|
|
60
|
+
text: script.slice(gapStart, to)
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
for (let i = 0; i < script.length;) {
|
|
64
|
+
const char = script[i];
|
|
65
|
+
if (/\s/.test(char)) i++;
|
|
66
|
+
else if (char === "-" && script[i + 1] === "-") i = lineEnd(script, i);
|
|
67
|
+
else if (char === "/" && script[i + 1] === "*") i = blockCommentEnd(script, i);
|
|
68
|
+
else if (char === "\\") {
|
|
69
|
+
flushGap(i);
|
|
70
|
+
gapStart = lineEnd(script, i);
|
|
71
|
+
pieces.push({
|
|
72
|
+
kind: "meta",
|
|
73
|
+
text: script.slice(i, gapStart)
|
|
74
|
+
});
|
|
75
|
+
i = gapStart;
|
|
76
|
+
} else {
|
|
77
|
+
flushGap(i);
|
|
78
|
+
const end = statementEnd(script, i);
|
|
79
|
+
const withData = copyFromStdin.test(script.slice(i, end)) ? copyDataEnd(script, end) : end;
|
|
80
|
+
pieces.push({
|
|
81
|
+
kind: "statement",
|
|
82
|
+
text: script.slice(i, withData)
|
|
83
|
+
});
|
|
84
|
+
gapStart = i = withData;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
flushGap(script.length);
|
|
88
|
+
return pieces;
|
|
89
|
+
};
|
|
90
|
+
//#endregion
|
|
91
|
+
export { splitDump };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { qualified } from "./load-script.js";
|
|
2
|
+
//#region src/supabase/target-checks.ts
|
|
3
|
+
/** The roles Supabase's API switches to, which the imported grants and policies name, as Supabase makes them. */
|
|
4
|
+
const apiRoles = [
|
|
5
|
+
{
|
|
6
|
+
name: "anon",
|
|
7
|
+
create: "CREATE ROLE anon NOLOGIN NOINHERIT"
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
name: "authenticated",
|
|
11
|
+
create: "CREATE ROLE authenticated NOLOGIN NOINHERIT"
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
name: "service_role",
|
|
15
|
+
create: "CREATE ROLE service_role NOLOGIN NOINHERIT BYPASSRLS"
|
|
16
|
+
}
|
|
17
|
+
];
|
|
18
|
+
/**
|
|
19
|
+
* Makes the API roles the target lacks, when the importing role may make them as Supabase does (service_role bypasses
|
|
20
|
+
* row level security, which only a role that does may grant), and returns their names; otherwise fails, naming them
|
|
21
|
+
* and the statements an administrator runs.
|
|
22
|
+
*/
|
|
23
|
+
const ensureApiRoles = async (sql) => {
|
|
24
|
+
const existing = new Set((await sql`select rolname as name from pg_roles where rolname = any(${apiRoles.map((role) => role.name)})`).map((row) => row.name));
|
|
25
|
+
const missing = apiRoles.filter((role) => !existing.has(role.name));
|
|
26
|
+
if (missing.length === 0) return [];
|
|
27
|
+
const [me] = await sql`
|
|
28
|
+
select rolname as name, rolsuper as superuser, rolcreaterole as createrole, rolbypassrls as bypassrls from pg_roles where rolname = current_user
|
|
29
|
+
`;
|
|
30
|
+
if (!(me.superuser || me.createrole && (me.bypassrls || missing.every((role) => role.name !== "service_role")))) throw new Error(`The database lacks the roles ${missing.map((role) => role.name).join(", ")}, which the imported grants and policies name, and ${me.name} may not create them; have an administrator run: ${missing.map((role) => `${role.create};`).join(" ")}`);
|
|
31
|
+
for (const role of missing) await sql.unsafe(role.create);
|
|
32
|
+
return missing.map((role) => role.name);
|
|
33
|
+
};
|
|
34
|
+
/** The dumped tables that `sql`'s database has already, which the schema migration would fail to create. */
|
|
35
|
+
const existingTables = async (sql, tables) => {
|
|
36
|
+
return (await sql`select name from unnest(${tables.map(qualified)}::text[]) as name where to_regclass(name) is not null`).map((row) => row.name);
|
|
37
|
+
};
|
|
38
|
+
/** The dumped tables that hold rows on the target, which a load would add to. */
|
|
39
|
+
const filledTables = async (sql, tables) => {
|
|
40
|
+
const filled = [];
|
|
41
|
+
for (const table of tables) {
|
|
42
|
+
const [row] = await sql`select exists (select 1 from ${sql(table.schema)}.${sql(table.table)}) as filled`;
|
|
43
|
+
if (row.filled) filled.push(qualified(table));
|
|
44
|
+
}
|
|
45
|
+
return filled;
|
|
46
|
+
};
|
|
47
|
+
/** The tables in `schemas` that are not among the imported `tables`, such as the project's own, as `schema.table`. */
|
|
48
|
+
const otherTables = async (sql, schemas, tables) => {
|
|
49
|
+
return (await sql`
|
|
50
|
+
select n.nspname || '.' || c.relname as name from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
51
|
+
where c.relkind in ('r', 'p') and n.nspname = any(${schemas}) and n.nspname || '.' || c.relname <> all(${tables.map((table) => `${table.schema}.${table.table}`)})
|
|
52
|
+
order by 1
|
|
53
|
+
`).map((row) => row.name);
|
|
54
|
+
};
|
|
55
|
+
//#endregion
|
|
56
|
+
export { ensureApiRoles, existingTables, filledTables, otherTables };
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
//#region src/supabase/tokens.ts
|
|
2
|
+
/** The tokens of `statement` outside comments, each with how deep in parentheses it sits. */
|
|
3
|
+
const tokenize = (statement) => {
|
|
4
|
+
const tokens = [];
|
|
5
|
+
let depth = 0;
|
|
6
|
+
for (let i = 0; i < statement.length;) {
|
|
7
|
+
const char = statement[i];
|
|
8
|
+
const rest = statement.slice(i);
|
|
9
|
+
if (/\s/.test(char)) i++;
|
|
10
|
+
else if (rest.startsWith("--")) i = statement.indexOf("\n", i) === -1 ? statement.length : statement.indexOf("\n", i) + 1;
|
|
11
|
+
else if (rest.startsWith("/*")) i = statement.indexOf("*/", i) + 2;
|
|
12
|
+
else if (char === "\"") {
|
|
13
|
+
const end = /^"(?:[^"]|"")*"/.exec(rest)[0].length + i;
|
|
14
|
+
tokens.push({
|
|
15
|
+
start: i,
|
|
16
|
+
end,
|
|
17
|
+
word: statement.slice(i + 1, end - 1).replaceAll("\"\"", "\""),
|
|
18
|
+
depth
|
|
19
|
+
});
|
|
20
|
+
i = end;
|
|
21
|
+
} else if (char === "'") {
|
|
22
|
+
const end = /^'(?:[^']|'')*'/.exec(rest)[0].length + i;
|
|
23
|
+
tokens.push({
|
|
24
|
+
start: i,
|
|
25
|
+
end,
|
|
26
|
+
depth
|
|
27
|
+
});
|
|
28
|
+
i = end;
|
|
29
|
+
} else if (/^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/.test(rest)) {
|
|
30
|
+
const tag = /^\$(?:[A-Za-z_][A-Za-z_0-9]*)?\$/.exec(rest)[0];
|
|
31
|
+
const end = statement.indexOf(tag, i + tag.length) + tag.length;
|
|
32
|
+
tokens.push({
|
|
33
|
+
start: i,
|
|
34
|
+
end,
|
|
35
|
+
depth
|
|
36
|
+
});
|
|
37
|
+
i = end;
|
|
38
|
+
} else if (/[A-Za-z_]/.test(char)) {
|
|
39
|
+
const end = /^[A-Za-z_][A-Za-z_0-9$]*/.exec(rest)[0].length + i;
|
|
40
|
+
if (statement[end] === "'" && /^(?:[EeBbXxNn])$/.test(statement.slice(i, end))) {
|
|
41
|
+
const close = /^'(?:[^'\\]|''|\\.)*'/.exec(statement.slice(end))[0].length + end;
|
|
42
|
+
tokens.push({
|
|
43
|
+
start: i,
|
|
44
|
+
end: close,
|
|
45
|
+
depth
|
|
46
|
+
});
|
|
47
|
+
i = close;
|
|
48
|
+
} else {
|
|
49
|
+
tokens.push({
|
|
50
|
+
start: i,
|
|
51
|
+
end,
|
|
52
|
+
word: statement.slice(i, end).toLowerCase(),
|
|
53
|
+
depth
|
|
54
|
+
});
|
|
55
|
+
i = end;
|
|
56
|
+
}
|
|
57
|
+
} else if (/[0-9]/.test(char)) {
|
|
58
|
+
const end = /^[0-9.]+(?:[eE][+-]?[0-9]+)?/.exec(rest)[0].length + i;
|
|
59
|
+
tokens.push({
|
|
60
|
+
start: i,
|
|
61
|
+
end,
|
|
62
|
+
depth
|
|
63
|
+
});
|
|
64
|
+
i = end;
|
|
65
|
+
} else {
|
|
66
|
+
if (char === ")") depth--;
|
|
67
|
+
tokens.push({
|
|
68
|
+
start: i,
|
|
69
|
+
end: i + 1,
|
|
70
|
+
depth
|
|
71
|
+
});
|
|
72
|
+
if (char === "(") depth++;
|
|
73
|
+
i++;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return tokens;
|
|
77
|
+
};
|
|
78
|
+
/** Whether the tokens from `at` on are the words `words`, outside quotes. */
|
|
79
|
+
const wordsAt = (statement, tokens, at, words) => words.every((word, i) => {
|
|
80
|
+
const token = tokens[at + i];
|
|
81
|
+
return token !== void 0 && token.word === word && statement[token.start] !== "\"";
|
|
82
|
+
});
|
|
83
|
+
//#endregion
|
|
84
|
+
export { tokenize, wordsAt };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.26.0",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -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.
|
|
39
|
-
"@protobase/query": "0.
|
|
40
|
-
"@protobase/schema": "0.
|
|
41
|
-
"@protobase/server": "0.
|
|
42
|
-
"@protobase/ui": "0.
|
|
38
|
+
"@protobase/layout": "0.26.0",
|
|
39
|
+
"@protobase/query": "0.26.0",
|
|
40
|
+
"@protobase/schema": "0.26.0",
|
|
41
|
+
"@protobase/server": "0.26.0",
|
|
42
|
+
"@protobase/ui": "0.26.0",
|
|
43
43
|
"@react-email/render": "^2.1.0",
|
|
44
44
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
45
45
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -58,9 +58,11 @@
|
|
|
58
58
|
"react": "^19.3.0",
|
|
59
59
|
"ts-morph": "^28.0.0",
|
|
60
60
|
"vite": "^8.3.3",
|
|
61
|
+
"ws": "^8.22.0",
|
|
61
62
|
"zod": "^4.6.5"
|
|
62
63
|
},
|
|
63
64
|
"devDependencies": {
|
|
65
|
+
"@types/ws": "^8.18.2",
|
|
64
66
|
"tsx": "^4.23.15"
|
|
65
67
|
}
|
|
66
68
|
}
|
|
@@ -66,6 +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 listens to `postgres_changes` with supabase-js under RLS → read [Supabase Realtime](references/reference/supabase-realtime.md)
|
|
69
70
|
- When filling fields with a model → read [AI fields and actions](references/reference/ai.md)
|
|
70
71
|
- When letting people without an account create records → read [Public forms](references/reference/forms.md)
|
|
71
72
|
- When running background jobs → read [Jobs](references/reference/jobs.md)
|
|
@@ -59,7 +59,7 @@ createAuth({
|
|
|
59
59
|
})
|
|
60
60
|
```
|
|
61
61
|
|
|
62
|
-
- `users.table` names the table, default `user`. `users.columns` maps a column, by the name Protobase gives it (`name`, `email`, `email_verified`, `image`, `created_at`, `updated_at`, `role`, `banned`, `ban_reason`, `ban_expires`, `two_factor_enabled`, `last_role`, `last_organization_id`), to the table's own; here the app's roles go to `app_role`, since Supabase's `role` holds the Postgres role. The other tables keep their names and point at this one.
|
|
62
|
+
- `users.table` names the table, default `user`. `users.columns` maps a column, by the name Protobase gives it (`name`, `email`, `email_verified`, `email_confirmed_at`, `image`, `created_at`, `updated_at`, `role`, `banned`, `ban_reason`, `ban_expires`, `two_factor_enabled`, `last_role`, `last_organization_id`), to the table's own; here the app's roles go to `app_role`, since Supabase's `role` holds the Postgres role. The other tables keep their names and point at this one.
|
|
63
63
|
- `users.metadata` names a JSON column for each user's metadata: `createUser(auth, { ..., metadata: { full_name: 'Carol' } })` writes it, so a trigger that reads `raw_user_meta_data->>'full_name'` sees it.
|
|
64
64
|
- `passwordHashes: ['bcrypt']` also verifies bcrypt hashes (`$2a$`, `$2b$`, `$2y$`), and stores the password again as Better Auth's own scrypt after its first sign-in. The 12-character minimum holds for new passwords only, so a shorter existing one still signs in.
|
|
65
65
|
- `generateUserId: 'uuid'` makes each new user's id a random UUID in the server, for a table whose `id` is a `uuid` without a default, and makes every id column of the other tables a `uuid` too.
|
|
@@ -445,6 +445,17 @@ betterAuthAuthenticator({ auth, apps: [{ issuer: 'https://shop.example.com', rol
|
|
|
445
445
|
|
|
446
446
|
Their tokens are verified against that app's keys at `<issuer>/api/auth/jwks`; a role it does not map is dropped, a role held in one of its organizations never counts, and a user left with none gets `403`; their id here is `<sub>@<that app's host>`. See [Signing in at the source](remote-resources.md#signing-in-at-the-source)).
|
|
447
447
|
|
|
448
|
+
## supabase-js and @supabase/ssr
|
|
449
|
+
|
|
450
|
+
An app moving from Supabase keeps its `supabase.auth` calls and its `@supabase/ssr` session checks: the app serves GoTrue's endpoints at `/auth/v1`, over the same Better Auth sign-in, so `createClient(<the app's origin>, <publishable key>)` signs in, refreshes, reads the user and signs out as on Supabase.
|
|
451
|
+
|
|
452
|
+
- `signInWithPassword`, `signInWithOtp` then `verifyOtp({ email, token, type: 'email' })`, `signInWithOAuth` with one of the app's [sign-in providers](#sign-in-with-github) (PKCE, as `@supabase/ssr` uses, or the implicit flow), `refreshSession`, `getUser`, `getClaims`, `updateUser({ password, data })` and `signOut` work. Each goes through Better Auth's own endpoint, with its rate limits and the [sign-in policy](#sign-in-policy).
|
|
453
|
+
- Addresses are proved with the emailed 6-digit code, never a link. `signUp({ email, password, options: { data } })` needs [open sign-up](#open-sign-up) and mails a sign-up code; `verifyOtp({ email, token, type: 'signup' })` makes the account, with `data` in the [user metadata column](#an-existing-users-table), and signs in. Until then there is no account and `signUp` answers no user. `resetPasswordForEmail` mails a sign-in code; `verifyOtp` with `type: 'recovery'` signs in, and `updateUser({ password })` sets the new password.
|
|
454
|
+
- The access token is ES256, valid for an hour, with Supabase's claims: `sub`, `role: authenticated`, `aud: authenticated`, `email`, `app_metadata`, `user_metadata`, `aal`, `session_id`, issued by `<baseURL>/auth/v1`. Its keys are at `/auth/v1/.well-known/jwks.json`. It is apart from the EdDSA token of [Tokens and roles](#tokens-and-roles): neither is accepted for the other.
|
|
455
|
+
- The refresh token is the Better Auth session's token. Each refresh gives the session a new one, so a refresh token works once, and signing out, a ban or a revoked session ends it.
|
|
456
|
+
- `email_confirmed_at` is the time the address was confirmed, in the user table's `email_confirmed_at` column. An account verified before that column existed has none.
|
|
457
|
+
- Not offered: MFA, passkeys, SSO, phone sign-in, anonymous sign-in, the admin API and changing the address.
|
|
458
|
+
|
|
448
459
|
## Tokens for scripts and curl
|
|
449
460
|
|
|
450
461
|
There is no development login. For scripts, mint a token for an existing user on the host (the CLI exposes it as `protobase token you@example.com`):
|
|
@@ -461,6 +461,20 @@ protobase auth migration [--dir db/migrations] [--name auth]
|
|
|
461
461
|
|
|
462
462
|
Run inside a project whose `protobase.config.ts` exports `auth`, against its database with the project's migrations applied. It compares the database with the tables, columns and indexes Better Auth needs (with Protobase's plugins and the project's own) and writes what is missing as the next migration in `--dir`: `009_auth.sql` after `008_...`. Nothing is written when the schema is current. The file only adds, never drops; apply it with the project's other migrations. For a store with the camelCase names of Protobase 0.6 it writes their rename to snake_case instead, and the startup check asks for that. See [migrations](auth.md#migrations)).
|
|
463
463
|
|
|
464
|
+
## `import supabase`
|
|
465
|
+
|
|
466
|
+
```sh
|
|
467
|
+
protobase import supabase [<connection> | --source-env <variable>] [--env DATABASE_URL] [--dir db/migrations] [--config config]
|
|
468
|
+
```
|
|
469
|
+
|
|
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
|
+
|
|
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`: the trusted extensions they use first, then the dump without what fails on a database without Supabase's own roles, as comments (grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication and database webhooks). 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.
|
|
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, untrusted extensions, triggers that call out over HTTP, Edge Functions, and the indexes [`doctor`](#doctor) finds missing.
|
|
475
|
+
|
|
476
|
+
Remove `supabase-import/` to import again. Signing in Supabase's users with Protobase's auth is not part of this command yet.
|
|
477
|
+
|
|
464
478
|
## `token`
|
|
465
479
|
|
|
466
480
|
```sh
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/supabase-realtime.md: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# Supabase Realtime
|
|
4
|
+
|
|
5
|
+
The Realtime-compatible /realtime/v1 that supabase-js's channel().on('postgres_changes') listens to, each change checked under the subscriber's RLS policies.
|
|
6
|
+
|
|
7
|
+
An app with API keys and [live resources](live.md)) also serves `/realtime/v1/websocket`, the socket that supabase-js's `channel()` joins. An app moved from Supabase keeps its `postgres_changes` listeners: point the client at the app and give it the publishable key.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { createClient } from '@supabase/supabase-js'
|
|
11
|
+
|
|
12
|
+
const supabase = createClient('https://my-app.example.com', 'sb_publishable_...')
|
|
13
|
+
supabase
|
|
14
|
+
.channel('my-todos')
|
|
15
|
+
.on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'todos', filter: 'done=eq.false' }, (payload) => console.log(payload.new))
|
|
16
|
+
.subscribe()
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Keys, roles and tokens
|
|
20
|
+
|
|
21
|
+
The keys are `options.apiKeys` of `createAdmin`, `{ publishable_key, secret_key }`, or else `PROTOBASE_PUBLISHABLE_KEY` and `PROTOBASE_SECRET_KEY`. The socket sends the key in its URL and is refused with `401` without a key of the app. Each channel joins with the client's access token: a signed-in user's token makes it `authenticated` with the token's claims, the publishable key alone `anon`, the secret key alone the app's own role. A token the client refreshes on an open socket replaces the channel's; a channel whose token expires is closed with a `Token has expired` system message, as on Supabase.
|
|
22
|
+
|
|
23
|
+
The server serves the socket when the host gives `createAdmin` its WebSocket upgrade: `protobase serve` does, on Bun and Node. `protobase dev` does not serve it yet.
|
|
24
|
+
|
|
25
|
+
## Which tables
|
|
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; broadcast, presence and private channels neither.
|
|
28
|
+
|
|
29
|
+
## What a subscriber receives
|
|
30
|
+
|
|
31
|
+
Each change is checked for each subscriber before it is sent. The database needs the `anon` and `authenticated` roles, and the app's role must be allowed to `SET ROLE` to them. In one transaction per batch of changes, the server sets the subscriber's role with `SET LOCAL ROLE` and its claims in `request.jwt.claims` and `request.jwt.claim.sub`, so Supabase's `auth.uid()` and `auth.jwt()` work, reads the changed rows by key, and sends an insert or update only when the table's RLS policies let the subscriber select the row, with the columns its role may select. Subscribers with the same role and claims, such as one user's tabs, are checked once. The check holds one pooled connection per serving process, and only while it runs, never one per socket.
|
|
32
|
+
|
|
33
|
+
Unlike Supabase, which reads changes from the write-ahead log, the server reads them from the [live updates' notices](live.md#the-table)), which keep record keys only. So:
|
|
34
|
+
|
|
35
|
+
- An insert or update carries the row as it is when it is checked. Several changes of a row between two checks each carry its latest state, and a row deleted or no longer visible by then is not sent. `old_record` holds the primary key alone, as on Supabase without `replica identity full`.
|
|
36
|
+
- A delete carries the primary key alone and is not checked against RLS, as on Supabase. A filter on a column other than the key does not match a delete.
|
|
37
|
+
- `commit_timestamp` is when the change became a notice, within a second or two of the commit.
|
|
38
|
+
|
|
39
|
+
Changes reach subscribers within a second or two, the notices being read once a second.
|