@protobase/cli 0.26.1 → 0.26.3
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/config-jobs.js +34 -0
- package/dist/supabase/cron-job-file.js +25 -0
- package/dist/supabase/cron-jobs-write.js +33 -0
- package/dist/supabase/cron-plan.js +150 -0
- package/dist/supabase/dump-phase.js +17 -5
- package/dist/supabase/import-state.js +2 -2
- package/dist/supabase/load-phase.js +17 -6
- package/dist/supabase/load-script.js +2 -2
- package/dist/supabase/replay.js +11 -3
- package/dist/supabase/report.js +22 -4
- package/dist/supabase/source-facts.js +13 -3
- 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
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { parseSource } from "../scaffold/project.js";
|
|
2
|
+
import { Node, SyntaxKind } from "ts-morph";
|
|
3
|
+
//#region src/supabase/config-jobs.ts
|
|
4
|
+
const jobsImport = "import * as jobs from './jobs'";
|
|
5
|
+
/** What `protobase.config.ts` says when the import writes it: the jobs of `jobs/`, and the config by its convention. */
|
|
6
|
+
const newConfig = `${jobsImport}\n\nexport default { jobs }\n`;
|
|
7
|
+
/** The object `protobase.config.ts` exports by default, written out or passed to a call such as `defineConfig`. */
|
|
8
|
+
const exportedObject = (text) => {
|
|
9
|
+
const source = parseSource(text, "protobase.config.ts");
|
|
10
|
+
const exported = source.getExportAssignment((assignment) => !assignment.isExportEquals())?.getExpression();
|
|
11
|
+
const object = Node.isCallExpression(exported) ? exported.getArguments()[0] : exported;
|
|
12
|
+
return {
|
|
13
|
+
source,
|
|
14
|
+
object: Node.isObjectLiteralExpression(object) ? object : void 0
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* `protobase.config.ts` passing the jobs of `jobs/` as its `jobs`: `existing`, with an import of them and the property
|
|
19
|
+
* added, or a new file when there is none. It is `existing` itself when it imports `./jobs` already, and `undefined`
|
|
20
|
+
* when the file is not one it can change: it names a `jobs` of its own, or exports no object it can see.
|
|
21
|
+
*/
|
|
22
|
+
const configWithJobs = (existing) => {
|
|
23
|
+
if (existing === void 0) return newConfig;
|
|
24
|
+
const { source, object } = exportedObject(existing);
|
|
25
|
+
if (source.getImportDeclarations().some((declaration) => declaration.getModuleSpecifierValue() === "./jobs")) return existing;
|
|
26
|
+
if (!object || source.getDescendantsOfKind(SyntaxKind.Identifier).some((identifier) => identifier.getText() === "jobs")) return void 0;
|
|
27
|
+
const last = object.getProperties().at(-1);
|
|
28
|
+
const withProperty = last ? `${existing.slice(0, last.getEnd())}, jobs${existing.slice(last.getEnd())}` : `${existing.slice(0, object.getStart())}{ jobs }${existing.slice(object.getEnd())}`;
|
|
29
|
+
const importsEnd = source.getImportDeclarations().at(-1)?.getEnd();
|
|
30
|
+
if (importsEnd === void 0) return `${jobsImport}\n\n${withProperty}`;
|
|
31
|
+
return `${withProperty.slice(0, importsEnd)}\n${jobsImport}${withProperty.slice(importsEnd)}`;
|
|
32
|
+
};
|
|
33
|
+
//#endregion
|
|
34
|
+
export { configWithJobs };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
//#region src/supabase/cron-job-file.ts
|
|
2
|
+
const quoted = (text) => `'${text.replaceAll("\\", "\\\\").replaceAll("'", "\\'").replaceAll("\n", "\\n")}'`;
|
|
3
|
+
const templateLiteral = (text) => `\`${text.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${")}\``;
|
|
4
|
+
/**
|
|
5
|
+
* The module of `jobs/` that runs a pg_cron job's SQL as a Protobase recurring job, on its schedule, as the app's
|
|
6
|
+
* database role. pg_cron ran each time once, without retrying a failed one, so the job tries once too.
|
|
7
|
+
*/
|
|
8
|
+
const cronJobModule = (job) => [
|
|
9
|
+
"import { defineJob } from '@protobase/server'",
|
|
10
|
+
"import { sql } from 'kysely'",
|
|
11
|
+
"",
|
|
12
|
+
`/** pg_cron's job ${job.name}, imported from Supabase: its SQL, on its schedule, tried once each time as pg_cron did. */`,
|
|
13
|
+
`export const ${job.exportName} = defineJob({`,
|
|
14
|
+
` name: ${quoted(job.name)},`,
|
|
15
|
+
` schedule: ${quoted(job.schedule)},`,
|
|
16
|
+
...job.timezone ? [` timezone: ${quoted(job.timezone)},`] : [],
|
|
17
|
+
" maxAttempts: 1,",
|
|
18
|
+
" run: async (_, { db }) => {",
|
|
19
|
+
` await sql.raw(${templateLiteral(job.command)}).execute(db)`,
|
|
20
|
+
" },",
|
|
21
|
+
"})",
|
|
22
|
+
""
|
|
23
|
+
].join("\n");
|
|
24
|
+
//#endregion
|
|
25
|
+
export { cronJobModule };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { ensureExports } from "../scaffold/index-file.js";
|
|
2
|
+
import { configWithJobs } from "./config-jobs.js";
|
|
3
|
+
import { cronJobModule } from "./cron-job-file.js";
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
7
|
+
//#region src/supabase/cron-jobs-write.ts
|
|
8
|
+
const jobFile = (projectDir, job) => path.join(projectDir, "jobs", `${job.file}.ts`);
|
|
9
|
+
/** The files of `jobs` that the project has already, which the import does not overwrite. */
|
|
10
|
+
const cronJobFilesInTheWay = (projectDir, jobs) => jobs.map((job) => jobFile(projectDir, job)).filter((file) => existsSync(file));
|
|
11
|
+
const readIfThere = async (file) => existsSync(file) ? readFile(file, "utf8") : void 0;
|
|
12
|
+
/**
|
|
13
|
+
* Writes each job's module in `jobs/`, exports it from `jobs/index.ts` and passes them as protobase.config.ts's `jobs`;
|
|
14
|
+
* returns whether the config does, `false` when it has a `jobs` of its own for a person to add them to.
|
|
15
|
+
*/
|
|
16
|
+
const writeCronJobs = async (projectDir, jobs) => {
|
|
17
|
+
if (jobs.length === 0) return true;
|
|
18
|
+
await mkdir(path.join(projectDir, "jobs"), { recursive: true });
|
|
19
|
+
for (const job of jobs) await writeFile(jobFile(projectDir, job), cronJobModule(job), { flag: "wx" });
|
|
20
|
+
const index = path.join(projectDir, "jobs", "index.ts");
|
|
21
|
+
await writeFile(index, ensureExports(await readIfThere(index) ?? "", jobs.map((job) => ({
|
|
22
|
+
from: `./${job.file}`,
|
|
23
|
+
names: [job.exportName]
|
|
24
|
+
}))));
|
|
25
|
+
const configFile = path.join(projectDir, "protobase.config.ts");
|
|
26
|
+
const existing = await readIfThere(configFile);
|
|
27
|
+
const config = configWithJobs(existing);
|
|
28
|
+
if (config === void 0) return false;
|
|
29
|
+
if (config !== existing) await writeFile(configFile, config);
|
|
30
|
+
return true;
|
|
31
|
+
};
|
|
32
|
+
//#endregion
|
|
33
|
+
export { cronJobFilesInTheWay, writeCronJobs };
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
//#region src/supabase/cron-plan.ts
|
|
2
|
+
/** Schemas of the platform's services, which no database but Supabase's has, so a job calling them cannot run elsewhere. */
|
|
3
|
+
const platformOnly = [
|
|
4
|
+
"cron",
|
|
5
|
+
"realtime",
|
|
6
|
+
"_realtime",
|
|
7
|
+
"graphql",
|
|
8
|
+
"graphql_public",
|
|
9
|
+
"pgsodium",
|
|
10
|
+
"supabase_migrations",
|
|
11
|
+
"_analytics",
|
|
12
|
+
"pgbouncer"
|
|
13
|
+
];
|
|
14
|
+
/** The schemas a job converted for the project's database cannot call: the platform's, and the extensions it lacks. */
|
|
15
|
+
const unavailableSchemas = (target) => [
|
|
16
|
+
...platformOnly,
|
|
17
|
+
...target.httpSent ? [] : ["net"],
|
|
18
|
+
...target.webhooks ? [] : ["supabase_functions"],
|
|
19
|
+
...target.vault ? [] : ["vault"],
|
|
20
|
+
...target.queues ? [] : ["pgmq"]
|
|
21
|
+
];
|
|
22
|
+
/** The schemas of `schemas` that `command` names an object of, as `schema.name` or `"schema".name`. */
|
|
23
|
+
const calledSchemas = (command, schemas) => schemas.filter((schema) => new RegExp(`(^|[^\\w$."])"?${schema}"?\\s*\\.\\s*["\\w]`, "i").test(command));
|
|
24
|
+
/** Time zones that are pg_cron's default, which a Protobase job reads its schedule in too. */
|
|
25
|
+
const utc = /* @__PURE__ */ new Set([
|
|
26
|
+
"GMT",
|
|
27
|
+
"UTC",
|
|
28
|
+
"Etc/UTC",
|
|
29
|
+
"Etc/GMT"
|
|
30
|
+
]);
|
|
31
|
+
/** A pg_cron job name as a Protobase job name: letters, digits, `_`, `-`, `.` and `/`, the rest made `-`. */
|
|
32
|
+
const jobName = (job) => (job.name ?? `cron-job-${job.id}`).replace(/[^\w.\-/]+/g, "-");
|
|
33
|
+
const fileName = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "cron-job";
|
|
34
|
+
/** Words a module's export may not be named, which a job named so gets `cron` before. */
|
|
35
|
+
const reserved = /* @__PURE__ */ new Set([
|
|
36
|
+
"await",
|
|
37
|
+
"break",
|
|
38
|
+
"case",
|
|
39
|
+
"catch",
|
|
40
|
+
"class",
|
|
41
|
+
"const",
|
|
42
|
+
"continue",
|
|
43
|
+
"debugger",
|
|
44
|
+
"default",
|
|
45
|
+
"delete",
|
|
46
|
+
"do",
|
|
47
|
+
"else",
|
|
48
|
+
"enum",
|
|
49
|
+
"export",
|
|
50
|
+
"extends",
|
|
51
|
+
"false",
|
|
52
|
+
"finally",
|
|
53
|
+
"for",
|
|
54
|
+
"function",
|
|
55
|
+
"if",
|
|
56
|
+
"import",
|
|
57
|
+
"in",
|
|
58
|
+
"instanceof",
|
|
59
|
+
"let",
|
|
60
|
+
"new",
|
|
61
|
+
"null",
|
|
62
|
+
"return",
|
|
63
|
+
"static",
|
|
64
|
+
"super",
|
|
65
|
+
"switch",
|
|
66
|
+
"this",
|
|
67
|
+
"throw",
|
|
68
|
+
"true",
|
|
69
|
+
"try",
|
|
70
|
+
"typeof",
|
|
71
|
+
"var",
|
|
72
|
+
"void",
|
|
73
|
+
"while",
|
|
74
|
+
"with",
|
|
75
|
+
"yield"
|
|
76
|
+
]);
|
|
77
|
+
const exportName = (file) => {
|
|
78
|
+
const camel = file.replace(/-([a-z0-9])/g, (_, letter) => letter.toUpperCase());
|
|
79
|
+
return /^[0-9]/.test(camel) || reserved.has(camel) ? `cron${camel[0].toUpperCase()}${camel.slice(1)}` : camel;
|
|
80
|
+
};
|
|
81
|
+
/** `wanted`, or with `-<id>` after it when `taken` has it already, which it then holds. */
|
|
82
|
+
const unique = (taken, wanted, id, separator = "-") => {
|
|
83
|
+
const name = taken.has(wanted) ? `${wanted}${separator}${id}` : wanted;
|
|
84
|
+
taken.add(name);
|
|
85
|
+
return name;
|
|
86
|
+
};
|
|
87
|
+
/** Why a job is not converted for a database without pg_cron, or `undefined` when it can be. */
|
|
88
|
+
const leftReason = (job, options) => {
|
|
89
|
+
if (!job.active) return "inactive on Supabase, so not converted";
|
|
90
|
+
const called = calledSchemas(job.command, unavailableSchemas(options.target));
|
|
91
|
+
if (called.length > 0) return `calls ${called.join(", ")}, which the project's database lacks: rewrite it as a Protobase job`;
|
|
92
|
+
const zone = utc.has(options.timezone) ? "UTC" : options.timezone;
|
|
93
|
+
if (!options.isSchedule(job.schedule, zone)) return `Protobase's recurring jobs do not take this schedule${zone === "UTC" ? "" : ` in ${zone}`}: give it a cron schedule`;
|
|
94
|
+
};
|
|
95
|
+
/**
|
|
96
|
+
* What the import does with each of pg_cron's jobs: where the project's database has pg_cron, it schedules them there
|
|
97
|
+
* again, as they were; elsewhere it makes each a Protobase recurring job running its SQL, unless the job is inactive,
|
|
98
|
+
* calls what the database lacks, such as pg_net, or has a schedule Protobase's do not take, such as `30 seconds`. A job
|
|
99
|
+
* of another database is left either way, since the import carries over this one alone.
|
|
100
|
+
*/
|
|
101
|
+
const cronPlan = (jobs, options) => {
|
|
102
|
+
const names = /* @__PURE__ */ new Set();
|
|
103
|
+
const files = /* @__PURE__ */ new Set();
|
|
104
|
+
const exports = /* @__PURE__ */ new Set();
|
|
105
|
+
return jobs.map((job) => {
|
|
106
|
+
if (!job.local) return {
|
|
107
|
+
...job,
|
|
108
|
+
outcome: {
|
|
109
|
+
kind: "left",
|
|
110
|
+
reason: `runs in the database ${job.database}, which the import does not carry over`
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
if (options.pgCron) return {
|
|
114
|
+
...job,
|
|
115
|
+
outcome: { kind: "rescheduled" }
|
|
116
|
+
};
|
|
117
|
+
const reason = leftReason(job, options);
|
|
118
|
+
if (reason) return {
|
|
119
|
+
...job,
|
|
120
|
+
outcome: {
|
|
121
|
+
kind: "left",
|
|
122
|
+
reason
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
const name = unique(names, jobName(job), job.id);
|
|
126
|
+
const file = unique(files, fileName(name), job.id);
|
|
127
|
+
return {
|
|
128
|
+
...job,
|
|
129
|
+
outcome: {
|
|
130
|
+
kind: "converted",
|
|
131
|
+
name,
|
|
132
|
+
file,
|
|
133
|
+
exportName: unique(exports, exportName(file), job.id, ""),
|
|
134
|
+
timezone: utc.has(options.timezone) ? void 0 : options.timezone
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
});
|
|
138
|
+
};
|
|
139
|
+
/** The pg_cron jobs the plan made Protobase recurring jobs, with what their files declare. */
|
|
140
|
+
const convertedCronJobs = (jobs) => (jobs ?? []).flatMap((job) => {
|
|
141
|
+
if (job.outcome.kind !== "converted") return [];
|
|
142
|
+
const { kind: _, ...converted } = job.outcome;
|
|
143
|
+
return [{
|
|
144
|
+
...converted,
|
|
145
|
+
schedule: job.schedule,
|
|
146
|
+
command: job.command
|
|
147
|
+
}];
|
|
148
|
+
});
|
|
149
|
+
//#endregion
|
|
150
|
+
export { calledSchemas, convertedCronJobs, cronPlan, unavailableSchemas };
|
|
@@ -1,16 +1,18 @@
|
|
|
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 { cronPlan } from "./cron-plan.js";
|
|
4
5
|
import { importPlan, probedExtensions } from "./import-plan.js";
|
|
5
6
|
import { importState } from "./import-state.js";
|
|
6
7
|
import { runPgTool } from "./pg-tools.js";
|
|
7
8
|
import { replayScript } from "./replay.js";
|
|
8
9
|
import { schemaMigration } from "./schema-migration.js";
|
|
9
|
-
import { appSchemas, cronJobs, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets } from "./source-facts.js";
|
|
10
|
+
import { appSchemas, cronJobs, cronTimezone, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets } from "./source-facts.js";
|
|
10
11
|
import { ensureApiRoles, existingTables } from "./target-checks.js";
|
|
11
12
|
import { creatableExtensions } from "./target-extensions.js";
|
|
12
13
|
import path from "node:path";
|
|
13
14
|
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
15
|
+
import { isSchedule } from "@protobase/server";
|
|
14
16
|
import postgres from "postgres";
|
|
15
17
|
//#region src/supabase/dump-phase.ts
|
|
16
18
|
/** Fails unless the database at `sql` is Supabase's: its auth and storage schemas, and its own admin role. */
|
|
@@ -48,12 +50,21 @@ const readSource = async (sql, targetUrl) => {
|
|
|
48
50
|
const secrets = plan.vault ? await vaultSecretValues(sql) : void 0;
|
|
49
51
|
const queues = await pgmqQueues(sql);
|
|
50
52
|
const replayed = plan.queues ? (queues ?? []).filter((queue) => !queue.partitioned) : [];
|
|
53
|
+
const jobs = await cronJobs(sql);
|
|
54
|
+
const pgCron = plan.extensions.some((extension) => extension.name === "pg_cron");
|
|
55
|
+
const cron = jobs && cronPlan(jobs, {
|
|
56
|
+
pgCron,
|
|
57
|
+
target: plan,
|
|
58
|
+
timezone: await cronTimezone(sql),
|
|
59
|
+
isSchedule
|
|
60
|
+
});
|
|
61
|
+
const rescheduled = (cron ?? []).filter((job) => job.outcome.kind === "rescheduled");
|
|
51
62
|
return {
|
|
52
63
|
manifest: {
|
|
53
64
|
schemas,
|
|
54
65
|
tables,
|
|
55
66
|
bytes: await tablesSize(sql, tables),
|
|
56
|
-
cronJobs:
|
|
67
|
+
cronJobs: cron,
|
|
57
68
|
vaultSecrets: await vaultSecrets(sql),
|
|
58
69
|
vaultReplayed: secrets !== void 0,
|
|
59
70
|
queues: queues?.map((queue) => ({
|
|
@@ -72,7 +83,8 @@ const readSource = async (sql, targetUrl) => {
|
|
|
72
83
|
plan,
|
|
73
84
|
replay: replayScript({
|
|
74
85
|
secrets: secrets ?? [],
|
|
75
|
-
queues: replayed
|
|
86
|
+
queues: replayed,
|
|
87
|
+
cronJobs: rescheduled
|
|
76
88
|
})
|
|
77
89
|
};
|
|
78
90
|
};
|
|
@@ -96,7 +108,7 @@ const pattern = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
|
96
108
|
/**
|
|
97
109
|
* The import's first run: dumps the Supabase database's schemas and data as of one snapshot, writes the schema as
|
|
98
110
|
* 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
|
|
111
|
+
* replay of Vault's secrets, pgmq's queues and pg_cron's jobs and what the report needs in `supabase-import/` for the run that loads
|
|
100
112
|
* it, once the project's migrations are applied.
|
|
101
113
|
*/
|
|
102
114
|
const runDumpPhase = async (options, out) => {
|
|
@@ -150,7 +162,7 @@ const runDumpPhase = async (options, out) => {
|
|
|
150
162
|
});
|
|
151
163
|
out(`wrote ${path.relative(options.projectDir, path.join(options.migrationsDir, file))}, the schemas ${source.schemas.join(", ")}\n`);
|
|
152
164
|
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
|
|
165
|
+
if (replay) out(`kept Vault's secrets, pgmq's queues and pg_cron's jobs to make again in ${path.relative(options.projectDir, state.replay)}, which git ignores\n`);
|
|
154
166
|
out("next: apply the migration with the project's migrations, then run `protobase import supabase` again to load the data\n");
|
|
155
167
|
} finally {
|
|
156
168
|
reserved.release();
|
|
@@ -4,8 +4,8 @@ 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, and the replay of Vault's secrets and
|
|
8
|
-
* readable by its owner only until the load deletes it; the manifest; and the report.
|
|
7
|
+
* hashes and every row, and the replay of Vault's secrets, pgmq's queues and pg_cron's jobs, which holds the secrets'
|
|
8
|
+
* values, each readable by its owner only until the load deletes it; the manifest; and the report.
|
|
9
9
|
*/
|
|
10
10
|
const importState = (projectDir) => {
|
|
11
11
|
const dir = path.join(projectDir, "supabase-import");
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { connect } from "../db/connect.js";
|
|
2
2
|
import { runDoctor } from "../doctor/run.js";
|
|
3
3
|
import { runScaffold } from "../scaffold/run.js";
|
|
4
|
+
import { convertedCronJobs } from "./cron-plan.js";
|
|
4
5
|
import { importState } from "./import-state.js";
|
|
5
6
|
import { runPgTool } from "./pg-tools.js";
|
|
6
7
|
import { loadScript, qualified } from "./load-script.js";
|
|
7
8
|
import { existingTables, filledTables, otherTables } from "./target-checks.js";
|
|
9
|
+
import { cronJobFilesInTheWay, writeCronJobs } from "./cron-jobs-write.js";
|
|
8
10
|
import { importReport } from "./report.js";
|
|
9
11
|
import { existsSync } from "node:fs";
|
|
10
12
|
import path from "node:path";
|
|
@@ -12,8 +14,13 @@ import { rm, writeFile } from "node:fs/promises";
|
|
|
12
14
|
//#region src/supabase/load-phase.ts
|
|
13
15
|
/** Schemas the import restores that scaffolding leaves alone: Supabase Auth's and Storage's own tables are no resources. */
|
|
14
16
|
const platformSchemas = ["auth", "storage"];
|
|
15
|
-
/**
|
|
16
|
-
|
|
17
|
+
/**
|
|
18
|
+
* Fails unless every dumped table exists on the target, created by the applied migration, and holds no rows yet, and
|
|
19
|
+
* the project has none of the files the converted pg_cron jobs go to.
|
|
20
|
+
*/
|
|
21
|
+
const checkReady = async (url, projectDir, manifest) => {
|
|
22
|
+
const inTheWay = cronJobFilesInTheWay(projectDir, convertedCronJobs(manifest.cronJobs));
|
|
23
|
+
if (inTheWay.length > 0) throw new Error(`The project has ${inTheWay.map((file) => path.relative(projectDir, file)).join(", ")} already, where the import writes pg_cron's jobs; move them away first`);
|
|
17
24
|
const sql = connect(url);
|
|
18
25
|
try {
|
|
19
26
|
const existing = new Set(await existingTables(sql, manifest.tables));
|
|
@@ -37,14 +44,15 @@ const doctorOutput = async (url, configDir) => {
|
|
|
37
44
|
};
|
|
38
45
|
/**
|
|
39
46
|
* The import's second run, once the schema migration is applied: loads the data dump, with the replay of Vault's
|
|
40
|
-
* secrets
|
|
41
|
-
* imported tables of the app's schemas, leaving the project's own alone,
|
|
47
|
+
* secrets, pgmq's queues and pg_cron's jobs when the dump made one, in one transaction, deletes both, scaffolds the
|
|
48
|
+
* config from the imported tables of the app's schemas, leaving the project's own alone, writes the pg_cron jobs it
|
|
49
|
+
* converts as the project's recurring jobs, and writes the report.
|
|
42
50
|
*/
|
|
43
51
|
const runLoadPhase = async (options, out) => {
|
|
44
52
|
const state = importState(options.projectDir);
|
|
45
53
|
const manifest = await state.readManifest();
|
|
46
54
|
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);
|
|
55
|
+
await checkReady(options.targetUrl, options.projectDir, manifest);
|
|
48
56
|
const replay = state.hasReplay() ? state.replay : void 0;
|
|
49
57
|
await writeFile(state.load, loadScript(state.data, manifest.tables, replay), { mode: 384 });
|
|
50
58
|
await runPgTool("psql", options.targetUrl, [
|
|
@@ -70,7 +78,10 @@ const runLoadPhase = async (options, out) => {
|
|
|
70
78
|
ui: [],
|
|
71
79
|
excludes
|
|
72
80
|
}, out);
|
|
73
|
-
|
|
81
|
+
const cron = convertedCronJobs(manifest.cronJobs);
|
|
82
|
+
const jobsWired = await writeCronJobs(options.projectDir, cron);
|
|
83
|
+
if (cron.length > 0) out(`wrote ${cron.length} of pg_cron's jobs as recurring jobs in jobs/\n`);
|
|
84
|
+
await writeFile(state.report, importReport(manifest, await doctorOutput(options.targetUrl, options.configDir), jobsWired), { mode: 384 });
|
|
74
85
|
out(`wrote ${path.relative(options.projectDir, state.report)}: what the import could not carry over\n`);
|
|
75
86
|
};
|
|
76
87
|
//#endregion
|
|
@@ -7,8 +7,8 @@ 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; the replay at `replayFile`, when there is one, makes Vault's secrets
|
|
11
|
-
* again; every table's rows are counted against the source's before the transaction commits.
|
|
10
|
+
* their rows, then back on; the replay at `replayFile`, when there is one, makes Vault's secrets, pgmq's queues and
|
|
11
|
+
* pg_cron's jobs again; every table's rows are counted against the source's before the transaction commits.
|
|
12
12
|
*/
|
|
13
13
|
const loadScript = (dataFile, tables, replayFile) => [
|
|
14
14
|
...tables.map((table) => `ALTER TABLE ${qualified(table)} DISABLE TRIGGER USER;\n`),
|
package/dist/supabase/replay.js
CHANGED
|
@@ -6,10 +6,18 @@ const secretsScript = (secrets) => secrets.map((secret) => `SELECT vault.create_
|
|
|
6
6
|
/** A queue, made again as it was, and its messages sent again in order, each with its headers and visibility time. */
|
|
7
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
8
|
/**
|
|
9
|
+
* A pg_cron job, scheduled again as it was, by the importing role, which runs it as Supabase's `postgres` did; an
|
|
10
|
+
* inactive one stays inactive.
|
|
11
|
+
*/
|
|
12
|
+
const cronScript = (job) => {
|
|
13
|
+
const schedule = `cron.schedule(${job.name === null ? "" : `${literal(job.name)}, `}${literal(job.schedule)}, ${literal(job.command)})`;
|
|
14
|
+
return `SELECT ${job.active ? schedule : `cron.alter_job(${schedule}, active => false)`};\n`;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
9
17
|
* 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,
|
|
11
|
-
* secrets' values, so it lives only in `supabase-import/`, readable by its owner, until the load deletes it.
|
|
18
|
+
* whose ciphertext only Supabase's key opens, pgmq's queues, whose tables belong to the extension, and pg_cron's jobs,
|
|
19
|
+
* which live in its own schema. It holds the secrets' values, so it lives only in `supabase-import/`, readable by its owner, until the load deletes it.
|
|
12
20
|
*/
|
|
13
|
-
const replayScript = (input) => secretsScript(input.secrets) + input.queues.map(queueScript).join("");
|
|
21
|
+
const replayScript = (input) => secretsScript(input.secrets) + input.queues.map(queueScript).join("") + input.cronJobs.map(cronScript).join("");
|
|
14
22
|
//#endregion
|
|
15
23
|
export { replayScript };
|
package/dist/supabase/report.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { convertedCronJobs } from "./cron-plan.js";
|
|
1
2
|
//#region src/supabase/report.ts
|
|
2
3
|
/** Protobase Cloud's Starter plan holds this much data; the import reports a larger database, it does not refuse it. */
|
|
3
4
|
const starterBytes = 524288e3;
|
|
@@ -7,8 +8,23 @@ const section = (title, intro, items, unreadable = "The importing role could not
|
|
|
7
8
|
const secretName = (secret) => `${secret.name ?? "unnamed"}${secret.description ? `: ${secret.description}` : ""}`;
|
|
8
9
|
const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
|
|
9
10
|
const trigger = (one) => `${one.trigger} on ${one.schema}.${one.table}, calling ${one.function}`;
|
|
11
|
+
const cronJob = (job) => `${job.name ?? "unnamed"}, ${code(job.schedule)}`;
|
|
12
|
+
/** pg_cron's jobs the import scheduled again or made recurring jobs. */
|
|
13
|
+
const cronCarried = (jobs) => jobs.flatMap((job) => {
|
|
14
|
+
if (job.outcome.kind === "rescheduled") return [`pg_cron job ${cronJob(job)}${job.active ? "" : ", inactive"}`];
|
|
15
|
+
if (job.outcome.kind === "converted") return [`pg_cron job ${cronJob(job)}, as the recurring job ${code(`jobs/${job.outcome.file}.ts`)}`];
|
|
16
|
+
return [];
|
|
17
|
+
});
|
|
18
|
+
/** pg_cron's jobs left for a person, each with why. */
|
|
19
|
+
const cronLeft = (jobs) => jobs?.flatMap((job) => job.outcome.kind === "left" ? [`${cronJob(job)}: ${code(job.command)}, ${job.outcome.reason}`] : []);
|
|
20
|
+
/** What a person does before the converted pg_cron jobs run, or nothing when the import converted none. */
|
|
21
|
+
const recurringJobs = (manifest, jobsWired) => {
|
|
22
|
+
if (convertedCronJobs(manifest.cronJobs).length === 0) return [];
|
|
23
|
+
return [`## Recurring jobs\n\nThe import wrote pg_cron's jobs it could convert in \`jobs/\`, each running its SQL as the app's database role, once per time and without retries, as pg_cron did. ${jobsWired ? "`protobase.config.ts` passes them as its `jobs`." : "`protobase.config.ts` has a `jobs` of its own: add the exports of `jobs/index.ts` to it."} They run once the database has the jobs schema: run \`protobase migration\` and apply it.\n`];
|
|
24
|
+
};
|
|
10
25
|
/** What the import made again through an extension's own API, or kept since the project's database runs the extension. */
|
|
11
26
|
const carried = (manifest) => [
|
|
27
|
+
...cronCarried(manifest.cronJobs ?? []),
|
|
12
28
|
...manifest.vaultReplayed ? (manifest.vaultSecrets ?? []).map((secret) => `Vault secret ${secretName(secret)}`) : [],
|
|
13
29
|
...manifest.queuesReplayed ? (manifest.queues ?? []).filter((queue) => !queue.partitioned).map((queue) => `pgmq queue ${queue.name}, with ${plural(queue.messages, "message")}`) : [],
|
|
14
30
|
...manifest.httpSent ? manifest.httpTriggers.map((one) => `HTTP trigger ${trigger(one)}`) : []
|
|
@@ -19,16 +35,18 @@ const queuesLeft = (manifest) => manifest.queues?.filter((queue) => !manifest.qu
|
|
|
19
35
|
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`)];
|
|
20
36
|
/**
|
|
21
37
|
* The import's report: what it loaded, and what it could not carry over, for a person or their AI assistant to finish.
|
|
22
|
-
* `doctor` is `protobase doctor`'s output on the scaffolded config, or `undefined` when there was no config to check
|
|
38
|
+
* `doctor` is `protobase doctor`'s output on the scaffolded config, or `undefined` when there was no config to check;
|
|
39
|
+
* `jobsWired` whether protobase.config.ts passes the pg_cron jobs the load wrote as its `jobs`.
|
|
23
40
|
*/
|
|
24
|
-
const importReport = (manifest, doctor) => [
|
|
41
|
+
const importReport = (manifest, doctor, jobsWired) => [
|
|
25
42
|
"# Supabase import\n",
|
|
26
43
|
`Schemas ${manifest.schemas.join(", ")}, restored by the migration \`${manifest.migration}\`, and their data, loaded in one transaction.\n`,
|
|
27
44
|
`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`,
|
|
28
45
|
`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`,
|
|
29
46
|
"## 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)),
|
|
31
|
-
|
|
47
|
+
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 scheduled pg_cron's jobs again with `cron.schedule` where the project's database has pg_cron; elsewhere the import made them the app's recurring jobs, on the same schedule. 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)),
|
|
48
|
+
...recurringJobs(manifest, jobsWired),
|
|
49
|
+
section("Cron jobs", "These pg_cron jobs did not come over, each for the reason it gives. Make each a Protobase recurring job, or schedule it where the database has pg_cron.", cronLeft(manifest.cronJobs)),
|
|
32
50
|
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}`)),
|
|
33
51
|
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
52
|
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)),
|
|
@@ -80,12 +80,22 @@ const readable = async (sql, table) => {
|
|
|
80
80
|
const [row] = await sql`select to_regclass(${table}) is not null and has_table_privilege(${table}, 'select') as readable`;
|
|
81
81
|
return row.readable;
|
|
82
82
|
};
|
|
83
|
-
/**
|
|
83
|
+
/**
|
|
84
|
+
* pg_cron's jobs, which the cron schema holds and the dump leaves out, each `local` when it runs in this database;
|
|
85
|
+
* `undefined` when the role may not read them.
|
|
86
|
+
*/
|
|
84
87
|
const cronJobs = async (sql) => {
|
|
85
88
|
const [row] = await sql`select to_regclass('cron.job') is not null as exists`;
|
|
86
89
|
if (!row.exists) return [];
|
|
87
90
|
if (!await readable(sql, "cron.job")) return void 0;
|
|
88
|
-
return sql`
|
|
91
|
+
return [...await sql`
|
|
92
|
+
select jobid::int as id, jobname as name, schedule, command, active, database, database = current_database() as local from cron.job order by jobid
|
|
93
|
+
`];
|
|
94
|
+
};
|
|
95
|
+
/** The time zone pg_cron reads its schedules in, its `cron.timezone` setting: GMT unless the project set another. */
|
|
96
|
+
const cronTimezone = async (sql) => {
|
|
97
|
+
const [row] = await sql`select current_setting('cron.timezone', true) as timezone`;
|
|
98
|
+
return row.timezone ?? "GMT";
|
|
89
99
|
};
|
|
90
100
|
/** Vault's secrets by name, for the report. */
|
|
91
101
|
const vaultSecrets = async (sql) => {
|
|
@@ -168,4 +178,4 @@ const httpTriggers = (sql, schemas) => sql`
|
|
|
168
178
|
order by 1, 2, 3
|
|
169
179
|
`;
|
|
170
180
|
//#endregion
|
|
171
|
-
export { appSchemas, cronJobs, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets };
|
|
181
|
+
export { appSchemas, cronJobs, cronTimezone, databaseMarkers, dumpedTables, extensions, httpTriggers, hypertables, pgmqQueues, platformMigrationTables, realtimeTables, routinesIn, tablesSize, vaultSecretValues, vaultSecrets };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.26.
|
|
3
|
+
"version": "0.26.3",
|
|
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.3",
|
|
39
|
+
"@protobase/query": "0.26.3",
|
|
40
|
+
"@protobase/schema": "0.26.3",
|
|
41
|
+
"@protobase/server": "0.26.3",
|
|
42
|
+
"@protobase/ui": "0.26.3",
|
|
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`. 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
|
|
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, pgmq and pg_cron, `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, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
|
|
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. 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.
|
|
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. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs)) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, exports it from `jobs/index.ts` and adds `jobs` to `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. 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: the pg_cron jobs it could not carry over, each with why, 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
|
|