@rebasepro/cli 0.31.0-canary.g59cd6fd → 0.31.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/{auth-D96QYgFR.js → auth-ofQETpM5.js} +3 -3
- package/dist/{auth-D96QYgFR.js.map → auth-ofQETpM5.js.map} +1 -1
- package/dist/{console-C1d3LwB7.js → console-DjThnr3f.js} +2 -2
- package/dist/{console-C1d3LwB7.js.map → console-DjThnr3f.js.map} +1 -1
- package/dist/{db-DQZK9n9c.js → db-Bz2RFGJj.js} +25 -6
- package/dist/db-Bz2RFGJj.js.map +1 -0
- package/dist/{dev-PY5h4O6u.js → dev-D8TxrE_I.js} +2 -2
- package/dist/{dev-PY5h4O6u.js.map → dev-D8TxrE_I.js.map} +1 -1
- package/dist/dev-db/__fixtures__/unanswering-postgres.d.ts +11 -0
- package/dist/dev-db/attver.d.ts +11 -0
- package/dist/dev-db/local-timeouts.d.ts +25 -0
- package/dist/dev-db/pull.d.ts +24 -8
- package/dist/{doctor-CnUu8kpM.js → doctor-Du-mSxoE.js} +2 -2
- package/dist/{doctor-CnUu8kpM.js.map → doctor-Du-mSxoE.js.map} +1 -1
- package/dist/index.es.js +11 -11
- package/dist/local-timeouts-B1Kwligw.js +30 -0
- package/dist/local-timeouts-B1Kwligw.js.map +1 -0
- package/dist/{pull-DRWqBZp5.js → pull-BMuiUyjb.js} +97 -12
- package/dist/pull-BMuiUyjb.js.map +1 -0
- package/dist/{schema-CdDjv5zI.js → schema-Dv6nHkb0.js} +3 -3
- package/dist/{schema-CdDjv5zI.js.map → schema-Dv6nHkb0.js.map} +1 -1
- package/dist/schema-reconcile-CjxLaRHB.js +2 -0
- package/dist/{status-D7XCGHu2.js → status-BTgTWzlQ.js} +2 -2
- package/dist/{status-D7XCGHu2.js.map → status-BTgTWzlQ.js.map} +1 -1
- package/dist/{verify-5p_vaUG2.js → verify-BkUVGLqo.js} +2 -2
- package/dist/{verify-5p_vaUG2.js.map → verify-BkUVGLqo.js.map} +1 -1
- package/package.json +10 -10
- package/dist/db-DQZK9n9c.js.map +0 -1
- package/dist/pull-DRWqBZp5.js.map +0 -1
- package/dist/schema-reconcile-BAupXfkd.js +0 -2
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { r as PGLITE_EXTENSIONS } from "./constraints-CtiylsGf.js";
|
|
2
|
+
import { n as LOCAL_QUERY_TIMEOUT_MS, t as LOCAL_CONNECT_TIMEOUT_MS } from "./local-timeouts-B1Kwligw.js";
|
|
2
3
|
import { i as hostOf, n as connectionErrorText, t as banner } from "./connection-banner-DbLJzWf4.js";
|
|
3
4
|
import fs from "fs";
|
|
4
5
|
import { execa } from "execa";
|
|
@@ -37,6 +38,10 @@ import { execa } from "execa";
|
|
|
37
38
|
* encodings (SJIS, BIG5, GBK, UHC, GB18030, JOHAB, SHIFT_JIS_2004) are not
|
|
38
39
|
* ASCII-safe; a dump taken in one, through `PGCLIENTENCODING` or a
|
|
39
40
|
* `client_encoding` in the connection string, is left as it was.
|
|
41
|
+
*
|
|
42
|
+
* The same read of the TOC also answers which encoding a dump is written in
|
|
43
|
+
* ({@link archiveEncoding}). A pull into the managed database asks that before
|
|
44
|
+
* it empties anything.
|
|
40
45
|
*/
|
|
41
46
|
var ATTVER_ONLY = /^(ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET )\(pg_attver=\d+\);$/gm;
|
|
42
47
|
var ATTVER_FIRST = /(?<=^ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET \()pg_attver=\d+, (?=.*\);$)/gm;
|
|
@@ -186,11 +191,13 @@ function planPatches(fd, size, blank) {
|
|
|
186
191
|
const reader = new ArchiveReader(fd, size);
|
|
187
192
|
let serverVersion = null;
|
|
188
193
|
let dumpVersion = null;
|
|
194
|
+
let encoding = null;
|
|
189
195
|
const refuse = (reason) => ({
|
|
190
196
|
ok: false,
|
|
191
197
|
reason,
|
|
192
198
|
serverVersion,
|
|
193
|
-
dumpVersion
|
|
199
|
+
dumpVersion,
|
|
200
|
+
encoding
|
|
194
201
|
});
|
|
195
202
|
if (reader.bytes(5).toString("latin1") !== "PGDMP") return refuse(NOT_AN_ARCHIVE);
|
|
196
203
|
const major = reader.byte();
|
|
@@ -209,7 +216,6 @@ function planPatches(fd, size, blank) {
|
|
|
209
216
|
serverVersion = reader.ascii();
|
|
210
217
|
dumpVersion = reader.ascii();
|
|
211
218
|
const patches = [];
|
|
212
|
-
let encoding = null;
|
|
213
219
|
let firstData = Number.POSITIVE_INFINITY;
|
|
214
220
|
const entries = reader.int();
|
|
215
221
|
if (entries < 0) return refuse(NOT_AN_ARCHIVE);
|
|
@@ -251,9 +257,35 @@ function planPatches(fd, size, blank) {
|
|
|
251
257
|
ok: true,
|
|
252
258
|
patches,
|
|
253
259
|
serverVersion,
|
|
254
|
-
dumpVersion
|
|
260
|
+
dumpVersion,
|
|
261
|
+
encoding
|
|
255
262
|
};
|
|
256
263
|
}
|
|
264
|
+
/** Reads every definition as it is: what {@link archiveEncoding} walks the TOC with. */
|
|
265
|
+
function unchanged(definition) {
|
|
266
|
+
return definition;
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* The encoding a custom-format dump is written in, as its ENCODING entry
|
|
270
|
+
* names it (`LATIN1`, `UTF8`, …), or null when this cannot read the file as
|
|
271
|
+
* an archive.
|
|
272
|
+
*
|
|
273
|
+
* That entry is the `SET client_encoding` pg_restore starts every restore
|
|
274
|
+
* with: the source database's encoding, unless pg_dump ran with
|
|
275
|
+
* `PGCLIENTENCODING` naming another. The file is opened read-only and nothing
|
|
276
|
+
* in it changes.
|
|
277
|
+
*/
|
|
278
|
+
function archiveEncoding(dumpFile) {
|
|
279
|
+
const fd = fs.openSync(dumpFile, "r");
|
|
280
|
+
try {
|
|
281
|
+
return planPatches(fd, fs.fstatSync(fd).size, unchanged).encoding;
|
|
282
|
+
} catch (error) {
|
|
283
|
+
if (!(error instanceof RangeError)) throw error;
|
|
284
|
+
return null;
|
|
285
|
+
} finally {
|
|
286
|
+
fs.closeSync(fd);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
257
289
|
/**
|
|
258
290
|
* Blank every `pg_attver` attribute option in a custom-format dump, in place.
|
|
259
291
|
*
|
|
@@ -275,7 +307,8 @@ function stripAttverFromArchive(dumpFile, blank = blankAttverOptions) {
|
|
|
275
307
|
ok: false,
|
|
276
308
|
reason: NOT_AN_ARCHIVE,
|
|
277
309
|
serverVersion: null,
|
|
278
|
-
dumpVersion: null
|
|
310
|
+
dumpVersion: null,
|
|
311
|
+
encoding: null
|
|
279
312
|
};
|
|
280
313
|
}
|
|
281
314
|
const versions = {
|
|
@@ -826,7 +859,8 @@ async function readTargetEngine(target) {
|
|
|
826
859
|
const { Client } = await import("pg");
|
|
827
860
|
const client = new Client({
|
|
828
861
|
connectionString: target,
|
|
829
|
-
connectionTimeoutMillis:
|
|
862
|
+
connectionTimeoutMillis: LOCAL_CONNECT_TIMEOUT_MS,
|
|
863
|
+
query_timeout: LOCAL_QUERY_TIMEOUT_MS
|
|
830
864
|
});
|
|
831
865
|
client.on("error", () => void 0);
|
|
832
866
|
try {
|
|
@@ -1048,6 +1082,47 @@ function clearStatements(schemas) {
|
|
|
1048
1082
|
* a transaction would otherwise make the pull hang without a word.
|
|
1049
1083
|
*/
|
|
1050
1084
|
var CLEAR_LOCK_TIMEOUT = "15s";
|
|
1085
|
+
/**
|
|
1086
|
+
* How long one statement of {@link restoreCopy}'s may take before the pull
|
|
1087
|
+
* stops waiting on the database: twice the short bound, 30s. It has to stay
|
|
1088
|
+
* above {@link CLEAR_LOCK_TIMEOUT}, so that a lock the clear waits on is
|
|
1089
|
+
* reported as the lock it is (`55P03`, "stop `rebase dev`"). This bound is for
|
|
1090
|
+
* a database that answers nothing at all.
|
|
1091
|
+
*/
|
|
1092
|
+
var CLEAR_QUERY_TIMEOUT_MS = 2 * LOCAL_QUERY_TIMEOUT_MS;
|
|
1093
|
+
/**
|
|
1094
|
+
* The one encoding the managed database restores a dump in.
|
|
1095
|
+
*
|
|
1096
|
+
* pg_restore starts every restore with the dump's own `SET client_encoding`.
|
|
1097
|
+
* PGlite cannot convert. Sent `SET client_encoding = 'LATIN1'`, its daemon
|
|
1098
|
+
* closed the connection and then answered nobody, on that connection or any
|
|
1099
|
+
* later one, until `rebase db stop`. A pull from a LATIN1 database had
|
|
1100
|
+
* already emptied the local one by then. Every statement after the SET failed
|
|
1101
|
+
* on "no connection to the server".
|
|
1102
|
+
*/
|
|
1103
|
+
var MANAGED_ENCODING = "UTF8";
|
|
1104
|
+
/**
|
|
1105
|
+
* Why the local database cannot take a dump written in `encoding`, or null
|
|
1106
|
+
* when it can.
|
|
1107
|
+
*
|
|
1108
|
+
* Only the managed database refuses one. A Postgres target converts any
|
|
1109
|
+
* encoding to its own as pg_restore writes, which is how a LATIN1 source has
|
|
1110
|
+
* always pulled into Postgres in Docker. `encoding` is what
|
|
1111
|
+
* {@link archiveEncoding} read from the dump's ENCODING entry. Null means the
|
|
1112
|
+
* dump could not be read, and pg_restore is left to say what it makes of it,
|
|
1113
|
+
* as before. {@link restoreCopy} asks this before it empties anything, so the
|
|
1114
|
+
* outcome says the database is as it was.
|
|
1115
|
+
*/
|
|
1116
|
+
function encodingRefusal(engine, encoding) {
|
|
1117
|
+
if (engine !== "pglite" || encoding === null) return null;
|
|
1118
|
+
if (encoding.replace(/[-_]/g, "").toUpperCase() === MANAGED_ENCODING) return null;
|
|
1119
|
+
return {
|
|
1120
|
+
cleared: false,
|
|
1121
|
+
started: false,
|
|
1122
|
+
failure: `The managed development database cannot take this dump: pg_dump wrote it in the ${encoding} encoding (the source database's, unless PGCLIENTENCODING named another), and PGlite restores UTF8 only. The \`SET client_encoding = '${encoding}'\` a restore starts with leaves it answering nobody.`,
|
|
1123
|
+
advice: "Pull into Postgres in Docker instead, which converts it: `rebase db pull --docker` with the same --from. Or set DATABASE_URL in .env to a Postgres you run, and pull into that."
|
|
1124
|
+
};
|
|
1125
|
+
}
|
|
1051
1126
|
/** Why emptying the local database failed, in the reader's terms, and what fixes it. */
|
|
1052
1127
|
function clearFailure(error) {
|
|
1053
1128
|
const code = typeof error === "object" && error !== null && "code" in error ? String(error.code) : "";
|
|
@@ -1070,17 +1145,24 @@ function clearFailure(error) {
|
|
|
1070
1145
|
* restored, and the database is as it was.
|
|
1071
1146
|
*
|
|
1072
1147
|
* On the managed database the dump must be one {@link dumpSource} took for it,
|
|
1073
|
-
* with its rows as INSERTs
|
|
1074
|
-
*
|
|
1148
|
+
* with its rows as INSERTs, and written in UTF8: a COPY, or any other
|
|
1149
|
+
* encoding, would leave the daemon answering nobody, so either is refused
|
|
1150
|
+
* before anything is emptied. And afterwards its one session —
|
|
1075
1151
|
* every connection's — is given back its own settings: pg_restore leaves
|
|
1076
1152
|
* `search_path` empty and `row_security` off behind it, which a running
|
|
1077
1153
|
* `rebase dev` would otherwise query under.
|
|
1078
1154
|
*/
|
|
1079
1155
|
async function restoreCopy(plan, dumpFile) {
|
|
1156
|
+
const encoding = archiveEncoding(dumpFile);
|
|
1080
1157
|
const { Client } = await import("pg");
|
|
1081
|
-
const client = new Client({
|
|
1158
|
+
const client = new Client({
|
|
1159
|
+
connectionString: plan.target,
|
|
1160
|
+
connectionTimeoutMillis: LOCAL_CONNECT_TIMEOUT_MS,
|
|
1161
|
+
query_timeout: CLEAR_QUERY_TIMEOUT_MS
|
|
1162
|
+
});
|
|
1082
1163
|
client.on("error", () => void 0);
|
|
1083
1164
|
let engine;
|
|
1165
|
+
let begun = false;
|
|
1084
1166
|
try {
|
|
1085
1167
|
await client.connect();
|
|
1086
1168
|
engine = engineOf((await client.query("SELECT version() AS version")).rows[0]?.version ?? "");
|
|
@@ -1090,13 +1172,16 @@ async function restoreCopy(plan, dumpFile) {
|
|
|
1090
1172
|
failure: "The managed development database cannot take this dump: its rows are COPY data, which PGlite's socket server cannot receive.",
|
|
1091
1173
|
advice: "Pull into Postgres in Docker instead: `rebase db pull --docker`."
|
|
1092
1174
|
};
|
|
1175
|
+
const refused = encodingRefusal(engine, encoding);
|
|
1176
|
+
if (refused) return refused;
|
|
1093
1177
|
const { rows } = await client.query("SELECT nspname AS \"schema\" FROM pg_namespace");
|
|
1178
|
+
begun = true;
|
|
1094
1179
|
await client.query("BEGIN");
|
|
1095
1180
|
await client.query(`SET LOCAL lock_timeout = '${CLEAR_LOCK_TIMEOUT}'`);
|
|
1096
1181
|
for (const statement of clearStatements(schemasToClear(rows, plan.schemas))) await client.query(statement);
|
|
1097
1182
|
await client.query("COMMIT");
|
|
1098
1183
|
} catch (error) {
|
|
1099
|
-
await client.query("ROLLBACK").catch(() => void 0);
|
|
1184
|
+
if (begun) await client.query("ROLLBACK").catch(() => void 0);
|
|
1100
1185
|
return clearFailure(error);
|
|
1101
1186
|
} finally {
|
|
1102
1187
|
await client.end().catch(() => void 0);
|
|
@@ -1130,8 +1215,8 @@ async function resetSharedSession(target) {
|
|
|
1130
1215
|
const { Client } = await import("pg");
|
|
1131
1216
|
const client = new Client({
|
|
1132
1217
|
connectionString: target,
|
|
1133
|
-
connectionTimeoutMillis:
|
|
1134
|
-
query_timeout:
|
|
1218
|
+
connectionTimeoutMillis: LOCAL_CONNECT_TIMEOUT_MS,
|
|
1219
|
+
query_timeout: LOCAL_QUERY_TIMEOUT_MS
|
|
1135
1220
|
});
|
|
1136
1221
|
client.on("error", () => void 0);
|
|
1137
1222
|
try {
|
|
@@ -1157,4 +1242,4 @@ function describeRestoreFailure(outcome, source) {
|
|
|
1157
1242
|
//#endregion
|
|
1158
1243
|
export { anonymizeCopy, describeRestoreFailure, describeTarget, dumpSource, findPgTool, provisionableSchemas, restoreCopy, sourceProblem };
|
|
1159
1244
|
|
|
1160
|
-
//# sourceMappingURL=pull-
|
|
1245
|
+
//# sourceMappingURL=pull-BMuiUyjb.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pull-BMuiUyjb.js","names":[],"sources":["../src/dev-db/attver.ts","../src/dev-db/pull.ts"],"sourcesContent":["/**\n * `pg_attver` in a dump, and taking it out before a restore.\n *\n * The November 2026 PostgreSQL minor releases (every branch from 14 up;\n * upstream commit c23382f0a8, \"Introduce attribute versioning to prevent\n * unsafe deforming\") keep a per-column version as an attribute option: a\n * `pg_attver` key in `pg_attribute.attoptions`, set on every column created or\n * altered. A `pg_dump` from before that release, pointed at a server from\n * after it, dumps the key like any other attribute option:\n *\n * ALTER TABLE ONLY public.authors ALTER COLUMN id SET (pg_attver=33846480);\n *\n * and every server without the change — PGlite, which the managed development\n * database runs on, and a local Postgres on an older minor — refuses it with\n * `unrecognized parameter \"pg_attver\"`. The statement sits in the same archive\n * entry as the table's `CREATE TABLE`, so that entry fails whole: no table,\n * and every row, index and constraint of it after. A server with the change\n * ignores the key on input, so it carries nothing a restore needs.\n *\n * pg_dump's own fix leaves the key out, but a pull should not depend on the\n * local client being newer than the source server. So the dump is edited in\n * place before pg_restore reads it: in each TOC entry's definition, the key is\n * overwritten with spaces — the whole statement when it is the only option,\n * the key and its comma when there are others. Byte for byte the same length,\n * because the TOC records the file offset of every data block after it.\n *\n * The definitions are edited as bytes, never decoded: pg_dump writes them in\n * the database's encoding, which need not be UTF-8. Every encoding a server\n * can store is ASCII-safe — a byte below 0x80 is always that ASCII character —\n * so the ASCII statement is found by reading one character per byte, and the\n * bytes around it are written back exactly as they were. The client-only\n * encodings (SJIS, BIG5, GBK, UHC, GB18030, JOHAB, SHIFT_JIS_2004) are not\n * ASCII-safe; a dump taken in one, through `PGCLIENTENCODING` or a\n * `client_encoding` in the connection string, is left as it was.\n *\n * The same read of the TOC also answers which encoding a dump is written in\n * ({@link archiveEncoding}). A pull into the managed database asks that before\n * it empties anything.\n */\nimport fs from \"fs\";\n\nconst ATTVER_ONLY = /^(ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET )\\(pg_attver=\\d+\\);$/gm;\nconst ATTVER_FIRST = /(?<=^ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET \\()pg_attver=\\d+, (?=.*\\);$)/gm;\nconst ATTVER_LATER = /(?<=^ALTER (?:FOREIGN )?TABLE (?:ONLY )?.* ALTER COLUMN .* SET \\(.*), pg_attver=\\d+(?=.*\\);$)/gm;\n\nfunction spaces(text: string): string {\n return \" \".repeat(text.length);\n}\n\n/**\n * A TOC entry's definition, as the bytes pg_dump wrote, without its\n * `pg_attver` options: what was taken out is spaces, and every other byte is\n * as it was. Matched one character per byte (`latin1`), which finds the ASCII\n * statement in any ASCII-safe encoding without decoding anything else.\n */\nexport function blankAttverOptions(definition: Buffer): Buffer {\n const text = definition.toString(\"latin1\");\n if (!text.includes(\"pg_attver=\")) return definition;\n\n const blanked = text\n .replace(ATTVER_ONLY, (statement) => spaces(statement))\n .replace(ATTVER_FIRST, (option) => spaces(option))\n .replace(ATTVER_LATER, (option) => spaces(option));\n\n return blanked === text ? definition : Buffer.from(blanked, \"latin1\");\n}\n\n/**\n * The entries whose definition can hold attribute options: pg_dump's\n * `dumpTableSchema` writes `ALTER … ALTER COLUMN … SET (…)` for every relation\n * but a view, under the entry it describes as one of these.\n */\nconst RELATION_ENTRIES = new Set([\"TABLE\", \"FOREIGN TABLE\", \"MATERIALIZED VIEW\"]);\n\n/**\n * The encodings a server can store (`PG_SQL_ASCII` … `PG_KOI8U` in\n * pg_wchar.h), named as `pg_encoding_to_char` names them in the ENCODING\n * entry. Each is ASCII-safe; the client-only encodings after them are not.\n */\nconst ASCII_SAFE_ENCODINGS = new Set([\n \"SQL_ASCII\", \"EUC_JP\", \"EUC_CN\", \"EUC_KR\", \"EUC_TW\", \"EUC_JIS_2004\", \"UTF8\", \"MULE_INTERNAL\",\n \"LATIN1\", \"LATIN2\", \"LATIN3\", \"LATIN4\", \"LATIN5\", \"LATIN6\", \"LATIN7\", \"LATIN8\", \"LATIN9\", \"LATIN10\",\n \"WIN1256\", \"WIN1258\", \"WIN866\", \"WIN874\", \"KOI8R\", \"WIN1251\", \"WIN1252\",\n \"ISO_8859_5\", \"ISO_8859_6\", \"ISO_8859_7\", \"ISO_8859_8\",\n \"WIN1250\", \"WIN1253\", \"WIN1254\", \"WIN1255\", \"WIN1257\", \"KOI8U\"\n]);\n\n/** `K_VERS_1_12`…`K_VERS_MAX` (1.16 at any revision): the custom-format archives pg_dump 11 to 18 write. */\nconst OLDEST = archiveVersion(1, 12, 0);\nconst NEWEST = archiveVersion(1, 16, 255);\nconst V1_14 = archiveVersion(1, 14, 0);\nconst V1_15 = archiveVersion(1, 15, 0);\nconst V1_16 = archiveVersion(1, 16, 0);\n/** `archCustom` in pg_backup.h. */\nconst CUSTOM_FORMAT = 1;\n/** `K_OFFSET_POS_SET` in pg_backup_custom.c: the entry's data block is at the offset that follows. */\nconst OFFSET_SET = 2;\n\nfunction archiveVersion(major: number, minor: number, revision: number): number {\n return (major << 16) | (minor << 8) | revision;\n}\n\n/** Reads a custom-format archive's header and TOC straight from the file, without loading its data. */\nclass ArchiveReader {\n position = 0;\n intSize = 4;\n offSize = 8;\n\n constructor(private readonly fd: number, private readonly size: number) {}\n\n bytes(length: number): Buffer {\n if (length < 0 || this.position + length > this.size) throw new RangeError(\"past the end of the archive\");\n const buffer = Buffer.alloc(length);\n let read = 0;\n while (read < length) {\n const n = fs.readSync(this.fd, buffer, read, length - read, this.position + read);\n if (n === 0) throw new RangeError(\"past the end of the archive\");\n read += n;\n }\n this.position += length;\n return buffer;\n }\n\n byte(): number {\n return this.bytes(1)[0] ?? 0;\n }\n\n /** `ReadInt`: a sign byte, then `intSize` bytes, least significant first. */\n int(): number {\n const negative = this.byte() !== 0;\n const digits = this.bytes(this.intSize);\n let value = 0;\n for (let i = digits.length - 1; i >= 0; i--) value = value * 256 + (digits[i] ?? 0);\n return negative ? -value : value;\n }\n\n /** `ReadStr`: a length, then that many bytes; a negative length is NULL. Returns the bytes and where they are. */\n str(): { at: number; bytes: Buffer } | null {\n const length = this.int();\n if (length < 0) return null;\n const at = this.position;\n return { at, bytes: this.bytes(length) };\n }\n\n /** `ReadStr` for a field that is ASCII in every dump: a tag, a description, a version. */\n ascii(): string | null {\n return this.str()?.bytes.toString(\"latin1\") ?? null;\n }\n\n /** `ReadOffset`: a flag byte, then `offSize` bytes, least significant first. */\n offset(): { set: boolean; value: number } {\n const flag = this.byte();\n const digits = this.bytes(this.offSize);\n let value = 0;\n for (let i = digits.length - 1; i >= 0; i--) value = value * 256 + (digits[i] ?? 0);\n return { set: flag === OFFSET_SET, value };\n }\n}\n\ninterface Patch {\n at: number;\n bytes: Buffer;\n}\n\n/** What {@link stripAttverFromArchive} did to a dump. */\nexport interface AttverStrip {\n /** How many TOC entries had their `pg_attver` options blanked. */\n entries: number;\n /**\n * Why the dump was left exactly as it was, when it could not be read or\n * edited safely; null when it was read through. A skipped dump that holds\n * `pg_attver` options fails to restore on a server without the change.\n */\n skipped: string | null;\n /** The source server's version, as the archive's header records it; null when it was not read. */\n serverVersion: string | null;\n /** The version of the pg_dump that wrote the archive, from its header; null when it was not read. */\n dumpVersion: string | null;\n}\n\n/** What the archive's header and ENCODING entry say, as far as it was read; null for what was not. */\ninterface ArchiveFacts {\n serverVersion: string | null;\n dumpVersion: string | null;\n encoding: string | null;\n}\n\ntype Plan =\n | ({ ok: true; patches: Patch[] } & ArchiveFacts)\n | ({ ok: false; reason: string } & ArchiveFacts);\n\nconst NOT_AN_ARCHIVE = \"it is not a pg_dump custom-format archive this can read\";\n\n/** The edits that blank `pg_attver` in an archive's TOC, or why there are none to make safely. */\nfunction planPatches(fd: number, size: number, blank: (definition: Buffer) => Buffer): Plan {\n const reader = new ArchiveReader(fd, size);\n let serverVersion: string | null = null;\n let dumpVersion: string | null = null;\n let encoding: string | null = null;\n const refuse = (reason: string): Plan => ({ ok: false, reason, serverVersion, dumpVersion, encoding });\n\n if (reader.bytes(5).toString(\"latin1\") !== \"PGDMP\") return refuse(NOT_AN_ARCHIVE);\n const major = reader.byte();\n const minor = reader.byte();\n const revision = reader.byte();\n const version = archiveVersion(major, minor, revision);\n if (version < OLDEST || version > NEWEST) {\n return refuse(`its archive format is version ${major}.${minor}.${revision}, which this version of Rebase does not read`);\n }\n reader.intSize = reader.byte();\n reader.offSize = reader.byte();\n if (reader.intSize < 1 || reader.intSize > 8 || reader.offSize < 1 || reader.offSize > 8) return refuse(NOT_AN_ARCHIVE);\n if (reader.byte() !== CUSTOM_FORMAT) return refuse(NOT_AN_ARCHIVE);\n\n // ReadHead: compression, creation time, database name, server and pg_dump versions.\n if (version >= V1_15) reader.byte();\n else reader.int();\n for (let i = 0; i < 7; i++) reader.int();\n reader.str();\n serverVersion = reader.ascii();\n dumpVersion = reader.ascii();\n\n // ReadToc, with the custom format's ReadExtraToc after each entry.\n const patches: Patch[] = [];\n let firstData = Number.POSITIVE_INFINITY;\n const entries = reader.int();\n if (entries < 0) return refuse(NOT_AN_ARCHIVE);\n for (let i = 0; i < entries; i++) {\n reader.int(); // dumpId\n reader.int(); // hadDumper\n reader.str(); // tableoid\n reader.str(); // oid\n reader.str(); // tag\n const desc = reader.ascii();\n reader.int(); // section\n const definition = reader.str();\n reader.str(); // dropStmt\n reader.str(); // copyStmt\n reader.str(); // namespace\n reader.str(); // tablespace\n if (version >= V1_14) reader.str(); // tableam\n if (version >= V1_16) reader.int(); // relkind\n reader.str(); // owner\n reader.str(); // \"false\": the old withOids\n while (reader.str() !== null); // dependencies, ended by NULL\n const data = reader.offset();\n if (data.set) firstData = Math.min(firstData, data.value);\n\n if (!definition) continue;\n if (desc === \"ENCODING\") {\n encoding = /client_encoding = '([^']*)'/.exec(definition.bytes.toString(\"latin1\"))?.[1] ?? null;\n } else if (desc !== null && RELATION_ENTRIES.has(desc)) {\n const blanked = blank(definition.bytes);\n if (blanked.equals(definition.bytes)) continue;\n if (blanked.length !== definition.bytes.length) {\n return refuse(`taking pg_attver out of one of its entries would have changed that entry's length (${definition.bytes.length} bytes to ${blanked.length})`);\n }\n patches.push({ at: definition.at, bytes: blanked });\n }\n }\n\n // The data blocks follow the TOC. If they do not start after where this\n // read it to end, the layout was not the one assumed: change nothing.\n if (reader.position > firstData) return refuse(NOT_AN_ARCHIVE);\n\n // Found by matching bytes as ASCII, which only an ASCII-safe encoding\n // makes the statement it looks like.\n if (patches.length > 0 && (encoding === null || !ASCII_SAFE_ENCODINGS.has(encoding))) {\n return refuse(encoding === null\n ? \"it does not say which encoding it is written in\"\n : `it is written in the ${encoding} encoding, which this cannot edit safely; dump in the database's own encoding instead (unset PGCLIENTENCODING)`);\n }\n\n return { ok: true, patches, serverVersion, dumpVersion, encoding };\n}\n\n/** Reads every definition as it is: what {@link archiveEncoding} walks the TOC with. */\nfunction unchanged(definition: Buffer): Buffer {\n return definition;\n}\n\n/**\n * The encoding a custom-format dump is written in, as its ENCODING entry\n * names it (`LATIN1`, `UTF8`, …), or null when this cannot read the file as\n * an archive.\n *\n * That entry is the `SET client_encoding` pg_restore starts every restore\n * with: the source database's encoding, unless pg_dump ran with\n * `PGCLIENTENCODING` naming another. The file is opened read-only and nothing\n * in it changes.\n */\nexport function archiveEncoding(dumpFile: string): string | null {\n const fd = fs.openSync(dumpFile, \"r\");\n try {\n return planPatches(fd, fs.fstatSync(fd).size, unchanged).encoding;\n } catch (error) {\n if (!(error instanceof RangeError)) throw error;\n return null;\n } finally {\n fs.closeSync(fd);\n }\n}\n\n/**\n * Blank every `pg_attver` attribute option in a custom-format dump, in place.\n *\n * A file this does not recognise, or cannot edit safely, is left byte for\n * byte as it was — pg_restore then reads it as it is — and the result says\n * why. `blank` is the edit made to each table's definition: the pull always\n * uses the default, {@link blankAttverOptions}; it is a parameter so that the\n * guard against an edit that changes a definition's length can be tested.\n */\nexport function stripAttverFromArchive(\n dumpFile: string,\n blank: (definition: Buffer) => Buffer = blankAttverOptions\n): AttverStrip {\n const fd = fs.openSync(dumpFile, \"r+\");\n try {\n let plan: Plan;\n try {\n plan = planPatches(fd, fs.fstatSync(fd).size, blank);\n } catch (error) {\n if (!(error instanceof RangeError)) throw error;\n plan = { ok: false, reason: NOT_AN_ARCHIVE, serverVersion: null, dumpVersion: null, encoding: null };\n }\n const versions = { serverVersion: plan.serverVersion, dumpVersion: plan.dumpVersion };\n if (!plan.ok) return { entries: 0, skipped: plan.reason, ...versions };\n for (const patch of plan.patches) fs.writeSync(fd, patch.bytes, 0, patch.bytes.length, patch.at);\n return { entries: plan.patches.length, skipped: null, ...versions };\n } finally {\n fs.closeSync(fd);\n }\n}\n","/**\n * `rebase db pull` — copy a database's contents into local development.\n *\n * The common case is production into local, and the reason it exists is that\n * the alternative is worse: without it people hand-roll a `pg_dump | psql` and\n * get the flags wrong in ways that either fail loudly at 2am or, more often,\n * quietly restore half a schema.\n *\n * Three things this command insists on, because copying a production database\n * onto a laptop is a data-protection event whether or not anyone calls it one:\n *\n * 1. **It says what it is about to do, in full, before doing it** — which\n * database it will read, which one it will overwrite, and where the data will\n * come to rest on disk. The target path matters: people forget that\n * `.rebase/pgdata` is a directory their backup software may be indexing.\n *\n * 2. **It refuses to run unattended without being told to.** The target is\n * destroyed, so a mistyped `--from` with no confirmation would take the\n * developer's working database with it.\n *\n * 3. **It will not write to a remote database.** The target is always the local\n * development database; there is no flag that makes this push. A tool that\n * can copy in both directions eventually copies in the wrong one.\n *\n * Anonymization is opt-in (`--anonymize`), which is a deliberate choice and not\n * an obviously safe one — the flag nobody types is the flag nobody gets. It is\n * a best-effort pass over columns whose *names* look like personal data, and\n * {@link ANONYMIZE_PATTERNS} says exactly which. It cannot find personal data in\n * a column called `notes`, and this file says so rather than implying a\n * guarantee it cannot keep.\n *\n * What it does guarantee is that it never half-happens: {@link anonymizeCopy}\n * runs the pass in one transaction, and when the pass fails it empties the\n * tables it would have rewritten rather than leave their real values behind.\n */\n\nimport { execa } from \"execa\";\nimport fs from \"fs\";\nimport type { Client } from \"pg\";\n\nimport { archiveEncoding, type AttverStrip, stripAttverFromArchive } from \"./attver\";\nimport { banner, connectionErrorText, hostOf } from \"./connection-banner\";\nimport { PGLITE_EXTENSIONS } from \"./constraints\";\nimport { LOCAL_CONNECT_TIMEOUT_MS, LOCAL_QUERY_TIMEOUT_MS } from \"./local-timeouts\";\n\n/**\n * How one kind of personal-looking column is overwritten.\n *\n * Two forms, because a constant is the most readable replacement and is wrong\n * for exactly one kind of column: a unique one. Every `token_hash` becoming\n * `'REDACTED'` is what `UNIQUE(token_hash)` refused on the second row of\n * `rebase.refresh_tokens` — so on any project where someone had signed in twice.\n */\nexport interface AnonymizeRule {\n pattern: RegExp;\n /**\n * Only on a table of people (see {@link isPeopleTable}), when set. For a\n * column name that is personal on one table and not on another: a user's\n * `name` is a person's, a tag's is not.\n */\n peopleOnly?: true;\n /** The value for a column no unique index covers, or null to always use the unique form. */\n value: string | null;\n /** The unique form is `prefix` + random hex + `suffix`, cut to fit the column. */\n prefix: string;\n suffix: string;\n}\n\n/**\n * Tables whose rows are people, by name: `rebase.users`, the blog scaffold's\n * `authors`, and the usual spellings of a project's own. Singular or plural.\n */\nconst PERSON_TABLES = /^(users?|user_profiles?|profiles?|people|persons?|members?|customers?|contacts?|employees?|authors?)$/i;\n\n/** An email address column, by name: the email rule's own pattern. */\nconst EMAIL_COLUMN = /^(.*_)?e?mail(_.*)?$/i;\n\n/** The column types a replacement string fits. */\nconst TEXTUAL_TYPES = new Set([\"text\", \"character varying\", \"varchar\", \"character\", \"char\", \"citext\"]);\n\nfunction isTextual(column: ColumnRef): boolean {\n return TEXTUAL_TYPES.has(column.dataType.toLowerCase());\n}\n\n/** `\"schema\".\"table\"`, the key a column's table is known by. */\nfunction tableKey(column: ColumnRef): string {\n return `${quoteIdentifier(column.schema)}.${quoteIdentifier(column.table)}`;\n}\n\n/**\n * The tables whose rows are people: those {@link PERSON_TABLES} names, and any\n * that holds an email address column.\n *\n * The second is what reaches the tables no list of names could: a row with an\n * address of its own is a person's, so its `name` is one too. The blog\n * scaffold's `authors` (`name`, `email`, `picture`) arrived with every name\n * as it was. A table of organisations with a contact address gets its `name`\n * redacted too, which costs a local copy little.\n */\nexport function peopleTables(columns: readonly ColumnRef[]): Set<string> {\n const people = new Set<string>();\n for (const column of columns) {\n if (PERSON_TABLES.test(column.table) || (EMAIL_COLUMN.test(column.column) && isTextual(column))) {\n people.add(tableKey(column));\n }\n }\n return people;\n}\n\n/**\n * Column-name patterns the anonymizer overwrites.\n *\n * Names, not contents: inspecting values would be slower, and would still miss\n * the same things. This is a reasonable-effort measure for making a local copy\n * less dangerous, and it is not a compliance control.\n */\nexport const ANONYMIZE_PATTERNS: readonly AnonymizeRule[] = [\n // Emails are unique in practice even where nothing enforces it, so they\n // always get a value of their own.\n { pattern: EMAIL_COLUMN, value: null, prefix: \"user-\", suffix: \"@example.invalid\" },\n { pattern: /^(.*_)?(phone|mobile|tel|telephone)(_.*)?$/i, value: \"+10000000000\", prefix: \"+1-\", suffix: \"\" },\n // `display_name` is how `rebase.users` holds every user's name.\n {\n pattern: /^(.*_)?(display_name|first_name|last_name|full_name|middle_name|family_name|surname|given_name)(_.*)?$/i,\n value: \"Redacted\",\n prefix: \"Redacted-\",\n suffix: \"\"\n },\n // A bare `name` is a person's only on a table of people.\n { pattern: /^name$/i, peopleOnly: true, value: \"Redacted\", prefix: \"Redacted-\", suffix: \"\" },\n { pattern: /^(.*_)?(address|street|postcode|zip|zipcode)(_.*)?$/i, value: \"Redacted\", prefix: \"Redacted-\", suffix: \"\" },\n { pattern: /^(.*_)?(ssn|tax_id|national_id|passport)(_.*)?$/i, value: \"REDACTED\", prefix: \"REDACTED-\", suffix: \"\" },\n { pattern: /^(.*_)?(password|password_hash|secret|token|api_key|access_token|refresh_token)(_.*)?$/i, value: \"REDACTED\", prefix: \"REDACTED-\", suffix: \"\" },\n { pattern: /^(.*_)?(ip|ip_address|user_agent)(_.*)?$/i, value: \"REDACTED\", prefix: \"REDACTED-\", suffix: \"\" }\n];\n\n/** The rule that overwrites this column, if any. A people-only rule applies only on a table of people. */\nfunction ruleFor(columnName: string, onPeopleTable: boolean): AnonymizeRule | undefined {\n return ANONYMIZE_PATTERNS.find((rule) => rule.pattern.test(columnName) && (!rule.peopleOnly || onPeopleTable));\n}\n\n/**\n * Whether a column of this name is overwritten. A table is judged a table of\n * people by its name here; {@link anonymizableColumns}, which sees the\n * table's other columns, also counts one that holds an email address.\n */\nexport function shouldAnonymize(columnName: string, table?: string): boolean {\n return ruleFor(columnName, table !== undefined && PERSON_TABLES.test(table)) !== undefined;\n}\n\n/** A text-ish column the anonymizer can overwrite without a type error. */\nexport interface ColumnRef {\n schema: string;\n table: string;\n column: string;\n dataType: string;\n /** `character_maximum_length`: null or absent for an unbounded type. */\n maxLength?: number | null;\n /** Covered by a unique index — a primary key, a UNIQUE constraint, or a unique expression index. */\n unique?: boolean;\n}\n\n/** Random hex of this length, per row. `gen_random_uuid()` is core since PostgreSQL 13. */\nfunction randomHex(length: number): string {\n return `left(replace(gen_random_uuid()::text, '-', ''), ${length})`;\n}\n\nfunction sqlLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\n/**\n * Fewest random hex digits a unique replacement keeps. Twelve is 16^12 values:\n * a collision needs millions of rows, where eight would need tens of thousands.\n */\nconst MIN_UNIQUE_HEX = 12;\n\n/**\n * The SQL expression that overwrites one column, or null when no rule names it.\n *\n * Unique per row when an index makes the column unique, and always cut to the\n * column's declared length — `zip char(5)` refused `'Redacted'` outright, and a\n * failed statement now empties the tables rather than skip one. To fit a short\n * unique column the prefix goes first, then the suffix, and the random part is\n * kept to at least {@link MIN_UNIQUE_HEX} digits while there is room for them.\n * A NULL stays NULL: an empty optional field is not personal data.\n */\nexport function replacementFor(column: ColumnRef, onPeopleTable = PERSON_TABLES.test(column.table)): string | null {\n const rule = ruleFor(column.column, onPeopleTable);\n if (!rule) return null;\n const limit = typeof column.maxLength === \"number\" && column.maxLength > 0 ? column.maxLength : null;\n\n let value: string;\n if (rule.value !== null && !column.unique) {\n value = sqlLiteral(limit === null ? rule.value : rule.value.slice(0, limit));\n } else {\n const shapes = [[rule.prefix, rule.suffix], [\"\", rule.suffix], [\"\", \"\"]];\n const fitting = shapes.find(([prefix, suffix]) =>\n limit === null || limit - prefix.length - suffix.length >= MIN_UNIQUE_HEX);\n const [prefix, suffix] = fitting ?? [\"\", \"\"];\n const hex = Math.min(32, limit === null ? 32 : limit - prefix.length - suffix.length);\n value = `concat(${sqlLiteral(prefix)}, ${randomHex(Math.max(1, hex))}, ${sqlLiteral(suffix)})`;\n }\n\n const name = quoteIdentifier(column.column);\n return `CASE WHEN ${name} IS NULL THEN NULL ELSE ${value} END`;\n}\n\n/** A double-quoted identifier, with any `\"` in it doubled — a table called `order` or `a\"b` still works. */\nexport function quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * Anonymizable columns: name looks personal, and the type can hold the\n * replacement.\n *\n * The type check is what stops this generating `UPDATE … SET user_id =\n * 'Redacted'` for an integer column called `user_id_email_seq` and failing the\n * whole pass on a technicality.\n */\nexport function anonymizableColumns(columns: readonly ColumnRef[]): ColumnRef[] {\n const people = peopleTables(columns);\n\n return columns.filter((column) =>\n isTextual(column) && ruleFor(column.column, people.has(tableKey(column))) !== undefined);\n}\n\n/** `\"schema\".\"table\"` for each table the pass rewrites, sorted. */\nexport function anonymizedTables(columns: readonly ColumnRef[]): string[] {\n return [...new Set(anonymizableColumns(columns).map(tableKey))].sort();\n}\n\n/** `UPDATE` statements for one anonymization pass, in a stable order. */\nexport function anonymizeStatements(columns: readonly ColumnRef[]): string[] {\n const people = peopleTables(columns);\n const byTable = new Map<string, ColumnRef[]>();\n for (const column of anonymizableColumns(columns)) {\n const key = tableKey(column);\n byTable.set(key, [...(byTable.get(key) ?? []), column]);\n }\n\n return [...byTable.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([table, cols]) => {\n const assignments = [...cols]\n .sort((a, b) => a.column.localeCompare(b.column))\n .map((column) => `${quoteIdentifier(column.column)} = ${replacementFor(column, people.has(table))}`)\n .join(\", \");\n\n return `UPDATE ${table} SET ${assignments};`;\n });\n}\n\n/**\n * Every column the pass could overwrite, with what decides how.\n *\n * Base tables only — a view has an `email` column too, and is not something to\n * UPDATE. Generated columns are skipped for the same reason: `email_domain\n * GENERATED ALWAYS AS (…)` matches by name and refuses any value but DEFAULT,\n * and it follows the column it is generated from anyway. An extension type such\n * as `citext` reports `USER-DEFINED`, so its own name is what is compared.\n *\n * `unique` comes from the indexes, through `pg_depend` as well as `indkey`: a\n * unique index on `lower(email)` names no column in `indkey`, and is exactly\n * what a constant replacement would violate.\n */\nexport const ANONYMIZE_COLUMNS_SQL = `\nWITH unique_columns AS (\n SELECT DISTINCT i.indrelid AS relid, a.attname AS column_name\n FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum > 0 AND NOT a.attisdropped\n WHERE i.indisunique\n AND (a.attnum = ANY (i.indkey)\n OR EXISTS (SELECT 1 FROM pg_depend d\n WHERE d.classid = 'pg_class'::regclass AND d.objid = i.indexrelid\n AND d.refclassid = 'pg_class'::regclass AND d.refobjid = i.indrelid\n AND d.refobjsubid = a.attnum))\n)\nSELECT c.table_schema AS \"schema\",\n c.table_name AS \"table\",\n c.column_name AS \"column\",\n CASE WHEN c.data_type = 'USER-DEFINED' THEN c.udt_name ELSE c.data_type END AS \"dataType\",\n c.character_maximum_length AS \"maxLength\",\n (u.column_name IS NOT NULL) AS \"unique\"\n FROM information_schema.columns c\n JOIN information_schema.tables t ON t.table_schema = c.table_schema AND t.table_name = c.table_name\n LEFT JOIN unique_columns u\n ON u.relid = format('%I.%I', c.table_schema, c.table_name)::regclass AND u.column_name = c.column_name\n WHERE t.table_type = 'BASE TABLE'\n AND c.is_generated = 'NEVER'\n AND c.table_schema NOT IN ('pg_catalog', 'information_schema')`;\n\n/** How {@link anonymizeCopy} ended. */\nexport type AnonymizeOutcome =\n | { ok: true; tables: string[] }\n | {\n ok: false;\n /** Why the pass failed. Nothing it wrote was kept. */\n error: string;\n /** The tables emptied instead, so none of their real values are left. */\n emptied: string[];\n /** Why they could not be emptied, when they could not: the copy then holds real data. */\n emptyError: string | null;\n };\n\nfunction errorText(error: unknown): string {\n return error instanceof Error && error.message ? error.message : String(error);\n}\n\n/**\n * Overwrite the personal-looking columns of a restored copy, all or nothing.\n *\n * One transaction, so a failure part-way leaves no table half done — the old\n * pass ran its UPDATEs one by one, so a failure on `rebase.refresh_tokens` left\n * `public.authors` anonymized and `rebase.users` holding every real email.\n *\n * A rollback alone would be worse than that, though: it puts back the real\n * value of every column, in a copy the developer asked to be anonymized. So on\n * failure the tables the pass would have rewritten are emptied (`TRUNCATE …\n * CASCADE`, which takes the rows that reference them too), and the outcome\n * says which — or, if even that failed, says the copy holds real data, so the\n * caller can say it louder.\n *\n * `row_security = off` makes a role that RLS would filter fail the pass instead\n * of rewriting only the rows its policies show it, which looked like success.\n */\nexport async function anonymizeCopy(client: Client): Promise<AnonymizeOutcome> {\n let listed = false;\n let tables: string[] = [];\n try {\n const { rows } = await client.query<ColumnRef>(ANONYMIZE_COLUMNS_SQL);\n tables = anonymizedTables(rows);\n listed = true;\n await client.query(\"BEGIN\");\n await client.query(\"SET LOCAL row_security = off\");\n for (const statement of anonymizeStatements(rows)) await client.query(statement);\n await client.query(\"COMMIT\");\n\n return { ok: true, tables };\n } catch (error) {\n const reason = errorText(error);\n await client.query(\"ROLLBACK\").catch(() => undefined);\n if (!listed) {\n return { ok: false, error: reason, emptied: [], emptyError: \"the tables to empty could not be listed\" };\n }\n if (tables.length === 0) return { ok: false, error: reason, emptied: [], emptyError: null };\n try {\n await client.query(`TRUNCATE TABLE ${tables.join(\", \")} CASCADE`);\n\n return { ok: false, error: reason, emptied: tables, emptyError: null };\n } catch (emptyError) {\n return { ok: false, error: reason, emptied: [], emptyError: errorText(emptyError) };\n }\n }\n}\n\n/**\n * Schemas the restored copy needs the app role provisioned on.\n *\n * `pg_dump --no-privileges` strips every GRANT, so a pulled database arrives\n * with its RLS policies and its `FORCE ROW LEVEL SECURITY` intact and no\n * privileges behind them. Measured on a 30-table project: 68 policies restored,\n * 14 tables with RLS on, and **0** grants to `rebase_user` — where the source\n * had 60. Reading one table as the role Rebase serves every request through:\n *\n * source: 6\n * copy: ERROR: permission denied for table leads\n *\n * The dump flags are right and stay: without `--no-owner`/`--no-privileges`\n * every `ALTER … OWNER TO` and `GRANT … TO <prod role>` in the dump fails\n * against roles that do not exist on a laptop, and buries the real output. The\n * repair belongs after the restore, and belongs to `ensureAppRole` — the same\n * routine boot and `rebase db push` call — rather than to a second list of\n * grants written here.\n *\n * Which schemas: every non-system schema the restored database actually has.\n * Boot knows its `managedSchemas` from the collections; a restore knows only\n * what arrived, and a source may carry schemas this project does not declare.\n * `pg_catalog`, `information_schema` and the `pg_*` internals are never ours to\n * grant on and PostgreSQL would refuse anyway.\n */\nexport function provisionableSchemas(rows: readonly { schema: string }[]): string[] {\n const skip = (name: string) => name === \"information_schema\" || name.startsWith(\"pg_\");\n\n return [...new Set(rows.map((row) => row.schema))].filter((name) => !skip(name)).sort();\n}\n\n/**\n * libpq's `keyword=value` form (`host=db.example.com port=5432 dbname=app`):\n * one or more pairs, a value bare or single-quoted with `\\'` and `\\\\` escapes.\n */\nconst KEYWORD_VALUE_DSN = /^\\s*[a-z_]+\\s*=\\s*(?:'(?:[^'\\\\]|\\\\.)*'|[^\\s']+)(?:\\s+[a-z_]+\\s*=\\s*(?:'(?:[^'\\\\]|\\\\.)*'|[^\\s']+))*\\s*$/i;\n\n/** One keyword's value in a `keyword=value` connection string, unquoted. */\nfunction keywordValue(dsn: string, keyword: string): string | null {\n const match = new RegExp(`(?:^|\\\\s)${keyword}\\\\s*=\\\\s*('(?:[^'\\\\\\\\]|\\\\\\\\.)*'|[^\\\\s']+)`, \"i\").exec(dsn);\n if (!match) return null;\n const value = match[1];\n return value.startsWith(\"'\") ? value.slice(1, -1).replace(/\\\\(.)/g, \"$1\") : value;\n}\n\n/**\n * Why a `--from` value is not a connection string pg_dump reads, or null\n * when it is one: a `postgres://` or `postgresql://` URL, or libpq's\n * `keyword=value` pairs.\n *\n * Asked before anything else, because the answer is known from the string:\n * `--from garbage --yes` printed \"This will replace your local database.\n * From (unparseable connection string)\" and started dumping before pg_dump\n * refused it. The value is never quoted back: it may carry a password in a\n * shape no redaction recognises.\n */\nexport function sourceProblem(source: string): string | null {\n const scheme = /^([a-z][a-z0-9+.-]*):\\/\\//i.exec(source)?.[1]?.toLowerCase();\n if (scheme !== undefined) {\n if (scheme !== \"postgres\" && scheme !== \"postgresql\") {\n return `it is a ${scheme}:// URL, and a pull copies from PostgreSQL (postgres:// or postgresql://)`;\n }\n try {\n new URL(source);\n return null;\n } catch {\n return \"it starts like a postgres:// URL but is not a valid one\";\n }\n }\n if (KEYWORD_VALUE_DSN.test(source)) return null;\n return \"it is neither a postgres:// URL nor libpq keyword=value pairs\";\n}\n\n/** Host and database of a connection string, with no credentials in it. */\nexport function describeTarget(connectionString: string): string {\n try {\n const url = new URL(connectionString);\n const database = url.pathname.replace(/^\\//, \"\") || \"(default)\";\n\n return `${url.hostname}${url.port ? `:${url.port}` : \"\"}/${database}`;\n } catch {\n if (KEYWORD_VALUE_DSN.test(connectionString)) {\n const host = keywordValue(connectionString, \"host\") ?? keywordValue(connectionString, \"hostaddr\") ?? \"(local socket)\";\n const port = keywordValue(connectionString, \"port\");\n return `${host}${port ? `:${port}` : \"\"}/${keywordValue(connectionString, \"dbname\") ?? \"(default)\"}`;\n }\n // Never echo the raw string: it carries a password, and this line is\n // printed to a terminal people paste into issues.\n return \"(unparseable connection string)\";\n }\n}\n\n/**\n * What the local database runs on.\n *\n * `pglite` is the managed development database: one PGlite session behind a\n * socket server. Three things a restore relies on are not there. The server\n * runs each protocol message on its own, so the `CopyData` that follows a\n * `COPY … FROM stdin` never reaches the backend waiting for it: the COPY fails\n * on \"unexpected EOF\", and the session stops answering anyone until the daemon\n * is killed. It cannot convert between encodings, so a dump in any encoding\n * but UTF8 does the same at its first statement (see {@link encodingRefusal}).\n * And every connection shares that one session, so what pg_restore `SET`s for\n * itself stays set for everyone after it disconnects.\n */\nexport type PullTargetEngine = \"postgres\" | \"pglite\";\n\nexport interface PullPlan {\n /** Where the data comes from. */\n source: string;\n /** Where it lands. Always local. */\n target: string;\n anonymize: boolean;\n /** Schemas to copy. Empty means every non-system schema. */\n schemas: string[];\n /**\n * What the target runs on, which decides how the dump carries its rows.\n * Absent means `postgres`. {@link dumpSource} reads it off the target.\n */\n targetEngine?: PullTargetEngine;\n}\n\n/**\n * Rows per `INSERT` in a dump for the managed database.\n *\n * One per statement restored 100k rows in 8s; a hundred took 0.8s. A hundred\n * 512KB rows, a 100MB statement, still went in.\n */\nconst ROWS_PER_INSERT = 100;\n\n/**\n * `pg_dump` arguments for the source.\n *\n * `--no-owner` and `--no-acl` because the roles on a production server do not\n * exist locally, and without them every `ALTER … OWNER TO` in the dump fails and\n * buries the real output in noise. `--format=custom` so `pg_restore` can be told\n * to continue past errors selectively rather than all-or-nothing.\n *\n * For the managed database the rows travel as `INSERT`s, which PGlite takes\n * like any other statement, instead of `COPY` data, which it cannot take at\n * all — see {@link PullTargetEngine}. The copy is the same; only how the rows\n * are written in the dump differs.\n */\nexport function dumpArgs(plan: PullPlan): string[] {\n const args = [\"--format=custom\", \"--no-owner\", \"--no-acl\", \"--no-privileges\"];\n if (plan.targetEngine === \"pglite\") args.push(`--rows-per-insert=${ROWS_PER_INSERT}`);\n for (const schema of plan.schemas) args.push(\"--schema\", schema);\n args.push(\"--dbname\", splitPassword(plan.source).connectionString);\n\n return args;\n}\n\n/** The environment `pg_dump` runs with: the source's password, if it has one. */\nexport function dumpEnv(plan: PullPlan): Record<string, string> {\n return passwordEnv(plan.source);\n}\n\n/** The environment `pg_restore` runs with: the target's password, if it has one. */\nexport function restoreEnv(plan: PullPlan): Record<string, string> {\n return passwordEnv(plan.target);\n}\n\nfunction passwordEnv(connectionString: string): Record<string, string> {\n const { password } = splitPassword(connectionString);\n return password === null ? {} : { PGPASSWORD: password };\n}\n\n/**\n * A libpq connection string without its password, and the password.\n *\n * The password goes in `PGPASSWORD`, never on a command line, where every\n * process listing can read it and every failure prints it back (execa's error\n * repeats the command). The same rule `db backup` follows; this mirrors\n * `splitPassword` in `@rebasepro/server-postgres`'s connection-string utils,\n * which is not exported. Covers the user-info password and a `password=`\n * parameter; anything that does not parse as a postgres URL is left alone.\n */\nfunction splitPassword(connectionString: string): { connectionString: string; password: string | null } {\n let url: URL;\n try {\n url = new URL(connectionString);\n } catch {\n return { connectionString, password: null };\n }\n if (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") return { connectionString, password: null };\n\n const fromUserInfo = url.password ? decodePercent(url.password) : null;\n const fromParameter = url.searchParams.get(\"password\");\n if (fromUserInfo === null && fromParameter === null) return { connectionString, password: null };\n\n url.password = \"\";\n if (fromParameter !== null) {\n url.searchParams.delete(\"password\");\n // By hand: URLSearchParams writes a space as `+`, which libpq reads literally.\n url.search = Array.from(url.searchParams.entries())\n .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)\n .join(\"&\");\n }\n return { connectionString: url.toString(), password: fromUserInfo ?? fromParameter };\n}\n\nfunction decodePercent(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\n/**\n * `pg_restore` arguments for the target.\n *\n * It restores into schemas {@link restoreCopy} has already emptied, so\n * `--clean --if-exists` drops nothing that is there; it stays for whatever a\n * dump holds outside them — an extension, say — which would otherwise fail as\n * already existing. `--no-owner` for the same reason as the dump.\n */\nexport function restoreArgs(plan: PullPlan, dumpFile: string): string[] {\n return [\"--clean\", \"--if-exists\", \"--no-owner\", \"--no-privileges\", \"--dbname\", splitPassword(plan.target).connectionString, dumpFile];\n}\n\n/**\n * Is this PostgreSQL client tool on PATH, and what version? Both are checked\n * before anything destructive: discovering `pg_restore` is missing after the\n * dump has been taken — or after `--clean` has emptied the target — is the\n * worst possible ordering.\n */\nexport async function findPgTool(tool: \"pg_dump\" | \"pg_restore\"): Promise<string | null> {\n try {\n const { stdout } = await execa(tool, [\"--version\"]);\n\n return stdout.trim();\n } catch {\n return null;\n }\n}\n\n/** PGlite names itself in `version()`: `PostgreSQL 18.3 (PGlite 0.5.6) on wasm32-…`. */\nfunction engineOf(version: string): PullTargetEngine {\n return /\\bPGlite\\b/i.test(version) ? \"pglite\" : \"postgres\";\n}\n\nconst NOTHING_CHANGED = \"Nothing was changed: the local database is as it was.\";\n\n/** What the target database runs on, or why it could not be asked. */\nasync function readTargetEngine(target: string): Promise<{ engine: PullTargetEngine } | { error: unknown }> {\n const { Client } = await import(\"pg\");\n const client = new Client({\n connectionString: target,\n connectionTimeoutMillis: LOCAL_CONNECT_TIMEOUT_MS,\n query_timeout: LOCAL_QUERY_TIMEOUT_MS\n });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n const { rows } = await client.query<{ version: string }>(\"SELECT version() AS version\");\n\n return { engine: engineOf(rows[0]?.version ?? \"\") };\n } catch (error) {\n return { error };\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/** How {@link dumpSource} ended. */\nexport type DumpOutcome =\n | {\n ok: true;\n /** The plan the dump was taken for, with its target's engine read: what {@link restoreCopy} takes. */\n plan: PullPlan;\n }\n | {\n ok: false;\n /** What failed and what to do, as plain lines for the caller to print. Nothing was changed. */\n lines: string[];\n };\n\n/**\n * `pg_dump` the source into `dumpFile`, in the form the target can restore.\n *\n * It asks the target what it runs on first — the managed database cannot take\n * `COPY` data, see {@link PullTargetEngine} — which also finds a local\n * database that is not there before anything is read from the source.\n *\n * pg_dump's stderr is kept rather than shown as it arrives, so a failure is\n * reported once, in the reader's terms: an unreachable source, or credentials\n * it refused, get the banner every database command prints for a connection\n * that failed, and anything else is pg_dump's own words with a line saying\n * nothing was changed. A dump that succeeds with warnings still shows them.\n * A dump that fails leaves no file behind.\n */\nexport async function dumpSource(plan: PullPlan, dumpFile: string): Promise<DumpOutcome> {\n try {\n const outcome = await dumpInto(plan, dumpFile);\n if (!outcome.ok) fs.rmSync(dumpFile, { force: true });\n\n return outcome;\n } catch (error) {\n fs.rmSync(dumpFile, { force: true });\n throw error;\n }\n}\n\nasync function dumpInto(plan: PullPlan, dumpFile: string): Promise<DumpOutcome> {\n let targetEngine = plan.targetEngine;\n if (!targetEngine) {\n const read = await readTargetEngine(plan.target);\n if (\"error\" in read) {\n return {\n ok: false,\n lines: banner(`Cannot connect to PostgreSQL at ${hostOf(plan.target)}`,\n `The driver said: ${connectionErrorText(read.error)}`, [\n \"That is the local database the pull would replace, and nothing\",\n \"was read from the source.\",\n \"Start it — `rebase dev` starts the managed one, `rebase dev --docker`\",\n \"Postgres in Docker — or check DATABASE_URL in .env, then pull again.\"\n ])\n };\n }\n targetEngine = read.engine;\n }\n\n const planned: PullPlan = { ...plan, targetEngine };\n const run = await execa(\"pg_dump\", [...dumpArgs(planned), \"--file\", dumpFile], {\n env: dumpEnv(planned),\n stdin: \"ignore\",\n stdout: \"inherit\",\n stderr: \"pipe\",\n reject: false\n });\n if (run.exitCode === 0) {\n if (run.stderr.trim()) process.stderr.write(`${run.stderr.trimEnd()}\\n`);\n\n return { ok: true, plan: planned };\n }\n\n return { ok: false, lines: describeDumpFailure(plan.source, run) };\n}\n\n/**\n * Why `pg_dump` could not read the source, as plain lines for the caller to\n * print. The dump is taken before anything local is touched, so every one of\n * them ends the same way: nothing was changed.\n */\nexport function describeDumpFailure(source: string, run: RestoreRun): string[] {\n if (run.signal) return [`✗ pg_dump was stopped by ${run.signal} before it finished.`, NOTHING_CHANGED];\n if (run.exitCode === undefined) {\n return [\n `✗ pg_dump could not be started (${run.code ?? \"unknown error\"}).`,\n NOTHING_CHANGED,\n \"Check that the PostgreSQL client tools are installed (`pg_dump --version`).\"\n ];\n }\n\n const stderr = (run.stderr ?? \"\").trim();\n const host = hostOf(source);\n const error = /pg_dump: error: (.+)/.exec(stderr)?.[1]?.trim() ?? null;\n const said = error ? `pg_dump said: ${error}` : null;\n\n if (/could not translate host name|could not connect to server|connection to server .* failed: (?:Connection refused|timeout expired|No route to host|Network is unreachable|Operation timed out|Host is down)/i.test(stderr)) {\n return banner(`Cannot connect to PostgreSQL at ${host}`, said, [\n \"That is the database --from names, which the pull reads.\",\n NOTHING_CHANGED,\n \"Check the host and port in --from, and that this machine can reach\",\n \"that server: a VPN, an allow-list, or an SSH tunnel.\"\n ]);\n }\n if (/password authentication failed|no pg_hba\\.conf entry|role \"[^\"]+\" does not exist/i.test(stderr)) {\n let user = \"unknown\";\n try {\n user = decodePercent(new URL(source).username) || \"unknown\";\n } catch { /* named as unknown */ }\n return banner(`Authentication failed for user \"${user}\" at ${host}`, said, [\n \"PostgreSQL rejected the credentials --from carries.\",\n NOTHING_CHANGED,\n \"Check the user and password in --from.\"\n ]);\n }\n // The server answered and has no database of that name: a typo in\n // --from, usually, or a database not created yet.\n const missing = /database \"([^\"]+)\" does not exist/i.exec(stderr)?.[1];\n if (missing) {\n return banner(`Database \"${missing}\" does not exist at ${host}`, said, [\n \"That is the database --from names, which the pull reads.\",\n NOTHING_CHANGED,\n \"Check the database name in --from.\"\n ]);\n }\n\n const versions = /server version mismatch/i.test(stderr)\n ? [\"pg_dump is older than the server: install client tools at least as new as it (`brew install libpq`).\"]\n : [];\n return [\n ...(stderr ? stderr.split(\"\\n\") : []),\n `✗ pg_dump could not dump ${describeTarget(source)} (exit code ${run.exitCode}).`,\n NOTHING_CHANGED,\n ...versions\n ];\n}\n\n/** The fields of a finished `pg_restore` (or `pg_dump`) run that decide {@link restoreOutcome}. */\nexport interface RestoreRun {\n exitCode?: number;\n signal?: string;\n /** A spawn failure's code — `ENOENT` when the binary vanished. */\n code?: string;\n stderr?: string;\n}\n\n/** What a `pg_restore` run says about the copy. */\nexport interface RestoreRunOutcome {\n /** Whether anything can have arrived — what decides whether an anonymization pass has data to redact. */\n started: boolean;\n /** Null when the copy is complete. */\n failure: string | null;\n /**\n * What to do about the failure. \"Pull again\" only where a second pull is\n * what finishes the job: everything else repeats until its cause is fixed.\n */\n advice: string | null;\n}\n\n/**\n * What a finished `pg_restore` says about the copy.\n *\n * The target was emptied before anything was written, so every way this can\n * end short of exit 0 leaves a partial or empty local database, and none of\n * them may be reported as a copy. A non-zero exit is pg_restore saying it\n * skipped statements — \"errors ignored on restore: N\" — and whatever those\n * statements created (a table, its rows, an RLS policy) is missing locally.\n *\n * Restoring into an emptied database, those errors come from what the source\n * holds that this Postgres cannot create — an extension it does not have, a\n * feature of a newer server — and a second pull meets them again. So the\n * advice names that, rather than \"pull again\", which sent people in a loop.\n * On the managed database an extension cannot be installed at all, so the\n * advice there is Postgres in Docker.\n *\n * One cause is named for what it is: a target refusing `pg_attver`, which\n * means the local pg_dump is older than the source server and the dump could\n * not be edited to drop the key (`attver`, what {@link stripAttverFromArchive}\n * said, tells why).\n */\nexport function restoreOutcome(\n run: RestoreRun,\n engine: PullTargetEngine = \"postgres\",\n attver: AttverStrip | null = null\n): RestoreRunOutcome {\n if (run.signal) {\n return {\n started: true,\n failure: `pg_restore was stopped by ${run.signal} before it finished.`,\n advice: \"It was interrupted, not refused: pull again to finish the copy.\"\n };\n }\n if (run.exitCode === undefined) {\n return {\n started: false,\n failure: `pg_restore could not be started (${run.code ?? \"unknown error\"}).`,\n advice: \"Check that the PostgreSQL client tools are installed (`pg_restore --version`), then pull again.\"\n };\n }\n if (run.exitCode === 0) return { started: true, failure: null, advice: null };\n\n const ignored = /errors ignored on restore: (\\d+)/.exec(run.stderr ?? \"\");\n const refusedAttver = (run.stderr ?? \"\").includes(\"unrecognized parameter \\\"pg_attver\\\"\");\n const repeats = refusedAttver\n ? attverAdvice(attver)\n : engine === \"pglite\"\n ? \"Pulling again repeats these errors until what they name is fixed — most often an extension the \"\n + `source uses that the managed database does not have (it has ${PGLITE_EXTENSIONS.map(extension => extension.name).join(\", \")}). `\n + \"Pull into Postgres in Docker instead (`rebase db pull --docker`), or pull only the schemas that do \"\n + \"not need it (--schema).\"\n : \"Pulling again repeats these errors until what they name is fixed — most often an extension \"\n + \"the source uses that this Postgres does not have installed. Install it here, or pull only the schemas \"\n + \"that do not need it (--schema).\";\n\n return {\n started: true,\n failure: ignored\n ? `pg_restore could not restore ${ignored[1]} object(s) — the errors are above.`\n : `pg_restore exited with code ${run.exitCode} — the errors are above.`,\n advice: repeats\n };\n}\n\n/**\n * What to do when the target refused the dump's `pg_attver` options: they are\n * there because the local pg_dump is older than the server it dumped from,\n * and a pg_dump at least as new leaves them out.\n */\nfunction attverAdvice(attver: AttverStrip | null): string {\n const older = attver?.dumpVersion && attver.serverVersion\n ? `Your pg_dump (${attver.dumpVersion}) is older than the server it dumped from (${attver.serverVersion})`\n : \"Your pg_dump is older than the server it dumped from\";\n const skipped = attver?.skipped ? `, and Rebase could not take them out of this dump: ${attver.skipped}` : \"\";\n const atLeast = attver?.serverVersion ? `at least ${attver.serverVersion}` : \"at least the server's minor version\";\n\n return `${older}: it wrote pg_attver column options, which this database refuses${skipped}. `\n + `Upgrade the PostgreSQL client tools to ${atLeast} (check with \\`pg_dump --version\\`), then pull again.`;\n}\n\n/**\n * The line a pull prints when it took `pg_attver` out of the dump: the copy is\n * whole, but the local pg_dump is older than the source server, which is what\n * to fix. Null when nothing was taken out.\n */\nexport function attverNotice(attver: AttverStrip): string | null {\n if (attver.entries === 0) return null;\n const older = attver.dumpVersion && attver.serverVersion\n ? `Your pg_dump (${attver.dumpVersion}) is older than the server it dumped from (${attver.serverVersion})`\n : \"Your pg_dump is older than the server it dumped from\";\n const atLeast = attver.serverVersion ? `at least ${attver.serverVersion}` : \"at least the server's minor version\";\n\n return `${older}: its dump carried pg_attver column options this database would refuse, so they were taken `\n + `out of ${attver.entries} table(s) before restoring. Upgrading the PostgreSQL client tools to ${atLeast} is the supported fix.`;\n}\n\n/** How {@link restoreCopy} ended. */\nexport interface RestoreOutcome extends RestoreRunOutcome {\n /** Whether the local database was emptied first. False means it is exactly as it was. */\n cleared: boolean;\n /** Something the copy did that is worth one line, whether or not it succeeded — see {@link attverNotice}. */\n notice?: string;\n}\n\n/**\n * The local schemas a pull empties before it restores: every one of the local\n * database's own for a whole-database pull, and those it copies for a\n * `--schema` pull. `pg_catalog`, `information_schema` and the `pg_*` internals\n * never — see {@link provisionableSchemas}.\n */\nexport function schemasToClear(present: readonly { schema: string }[], planned: readonly string[]): string[] {\n const local = provisionableSchemas(present);\n\n return planned.length === 0 ? local : local.filter((schema) => planned.includes(schema));\n}\n\n/**\n * The statements that empty those schemas, in one transaction.\n *\n * `CASCADE`, which `pg_restore --clean` never uses: a table the source lacks —\n * `rebase.atlas_schema_revisions` from `rebase db migrate`, a collection added\n * locally that references a pulled table — is exactly what blocked its plain\n * `DROP SCHEMA` and `DROP TABLE`. `public` is put back empty, with the access\n * every role has to it by default, because a dump does not create a default\n * `public` and every table in it would otherwise have nowhere to go.\n */\nexport function clearStatements(schemas: readonly string[]): string[] {\n const statements = schemas.map((schema) => `DROP SCHEMA IF EXISTS ${quoteIdentifier(schema)} CASCADE`);\n if (schemas.includes(\"public\")) statements.push(\"CREATE SCHEMA public\", \"GRANT USAGE ON SCHEMA public TO PUBLIC\");\n\n return statements;\n}\n\n/**\n * How long emptying the local database waits for a lock before giving up.\n *\n * A `rebase dev` serving from the database holds connections, and one inside\n * a transaction would otherwise make the pull hang without a word.\n */\nconst CLEAR_LOCK_TIMEOUT = \"15s\";\n\n/**\n * How long one statement of {@link restoreCopy}'s may take before the pull\n * stops waiting on the database: twice the short bound, 30s. It has to stay\n * above {@link CLEAR_LOCK_TIMEOUT}, so that a lock the clear waits on is\n * reported as the lock it is (`55P03`, \"stop `rebase dev`\"). This bound is for\n * a database that answers nothing at all.\n */\nconst CLEAR_QUERY_TIMEOUT_MS = 2 * LOCAL_QUERY_TIMEOUT_MS;\n\n/**\n * The one encoding the managed database restores a dump in.\n *\n * pg_restore starts every restore with the dump's own `SET client_encoding`.\n * PGlite cannot convert. Sent `SET client_encoding = 'LATIN1'`, its daemon\n * closed the connection and then answered nobody, on that connection or any\n * later one, until `rebase db stop`. A pull from a LATIN1 database had\n * already emptied the local one by then. Every statement after the SET failed\n * on \"no connection to the server\".\n */\nconst MANAGED_ENCODING = \"UTF8\";\n\n/**\n * Why the local database cannot take a dump written in `encoding`, or null\n * when it can.\n *\n * Only the managed database refuses one. A Postgres target converts any\n * encoding to its own as pg_restore writes, which is how a LATIN1 source has\n * always pulled into Postgres in Docker. `encoding` is what\n * {@link archiveEncoding} read from the dump's ENCODING entry. Null means the\n * dump could not be read, and pg_restore is left to say what it makes of it,\n * as before. {@link restoreCopy} asks this before it empties anything, so the\n * outcome says the database is as it was.\n */\nexport function encodingRefusal(engine: PullTargetEngine, encoding: string | null): RestoreOutcome | null {\n if (engine !== \"pglite\" || encoding === null) return null;\n if (encoding.replace(/[-_]/g, \"\").toUpperCase() === MANAGED_ENCODING) return null;\n\n return {\n cleared: false,\n started: false,\n failure: `The managed development database cannot take this dump: pg_dump wrote it in the ${encoding} encoding `\n + \"(the source database's, unless PGCLIENTENCODING named another), and PGlite restores UTF8 only. \"\n + `The \\`SET client_encoding = '${encoding}'\\` a restore starts with leaves it answering nobody.`,\n advice: \"Pull into Postgres in Docker instead, which converts it: `rebase db pull --docker` with the same --from. \"\n + \"Or set DATABASE_URL in .env to a Postgres you run, and pull into that.\"\n };\n}\n\n/** Why emptying the local database failed, in the reader's terms, and what fixes it. */\nfunction clearFailure(error: unknown): RestoreOutcome {\n const code = typeof error === \"object\" && error !== null && \"code\" in error ? String(error.code) : \"\";\n const reason = errorText(error);\n const advice = code === \"55P03\"\n ? \"Something holds a lock on it — usually `rebase dev` serving from it. Stop that, then pull again.\"\n : code === \"42501\"\n ? \"This connection may not drop those schemas. Connect as the role that owns them — the one \"\n + \"that created them — and pull with that.\"\n : \"Fix what the error names; pulling again before that repeats it.\";\n\n return {\n cleared: false,\n started: false,\n failure: `Could not empty the local database before restoring: ${reason}`,\n advice\n };\n}\n\n/**\n * Replace the local database's contents with a dump: empty the schemas it\n * holds, then `pg_restore` into them.\n *\n * Only ever `plan.target`, the local development database the command\n * resolved — the pull's one destination, which no flag can change. Emptying it\n * is one transaction: if any schema cannot be dropped, none is, nothing is\n * restored, and the database is as it was.\n *\n * On the managed database the dump must be one {@link dumpSource} took for it,\n * with its rows as INSERTs, and written in UTF8: a COPY, or any other\n * encoding, would leave the daemon answering nobody, so either is refused\n * before anything is emptied. And afterwards its one session —\n * every connection's — is given back its own settings: pg_restore leaves\n * `search_path` empty and `row_security` off behind it, which a running\n * `rebase dev` would otherwise query under.\n */\nexport async function restoreCopy(plan: PullPlan, dumpFile: string): Promise<RestoreOutcome> {\n // Read from the dump, which is not the database: an encoding the managed\n // database cannot take is refused while the database is still as it was.\n const encoding = archiveEncoding(dumpFile);\n const { Client } = await import(\"pg\");\n // Bounded, because a wedged managed database accepts the socket and then\n // never answers (see local-timeouts.ts).\n const client = new Client({\n connectionString: plan.target,\n connectionTimeoutMillis: LOCAL_CONNECT_TIMEOUT_MS,\n query_timeout: CLEAR_QUERY_TIMEOUT_MS\n });\n client.on(\"error\", () => undefined);\n let engine: PullTargetEngine;\n // ROLLBACK only once BEGIN has been sent. Before that there is nothing to\n // roll back, and after a statement that timed out a ROLLBACK only waits\n // out a second bound.\n let begun = false;\n try {\n await client.connect();\n engine = engineOf((await client.query<{ version: string }>(\"SELECT version() AS version\")).rows[0]?.version ?? \"\");\n if (engine === \"pglite\" && plan.targetEngine !== \"pglite\") {\n return {\n cleared: false,\n started: false,\n failure: \"The managed development database cannot take this dump: its rows are COPY data, which PGlite's socket server cannot receive.\",\n advice: \"Pull into Postgres in Docker instead: `rebase db pull --docker`.\"\n };\n }\n const refused = encodingRefusal(engine, encoding);\n if (refused) return refused;\n const { rows } = await client.query<{ schema: string }>(\"SELECT nspname AS \\\"schema\\\" FROM pg_namespace\");\n begun = true;\n await client.query(\"BEGIN\");\n await client.query(`SET LOCAL lock_timeout = '${CLEAR_LOCK_TIMEOUT}'`);\n for (const statement of clearStatements(schemasToClear(rows, plan.schemas))) await client.query(statement);\n await client.query(\"COMMIT\");\n } catch (error) {\n if (begun) await client.query(\"ROLLBACK\").catch(() => undefined);\n return clearFailure(error);\n } finally {\n await client.end().catch(() => undefined);\n }\n\n // A pg_dump older than the source server's minor writes its `pg_attver`\n // attribute options, which the target may refuse — see attver.ts. A dump\n // it could not edit is restored as it is; if the target then refuses the\n // key, the advice says why (`restoreOutcome`).\n const attver = stripAttverFromArchive(dumpFile);\n\n // stderr is shown as it arrives and kept, for the count in its summary\n // line. Not rejected: every way this ends is judged by `restoreOutcome`.\n const run = await execa(\"pg_restore\", restoreArgs(plan, dumpFile), {\n env: restoreEnv(plan),\n stdin: \"ignore\",\n stdout: \"inherit\",\n stderr: [\"pipe\", \"inherit\"],\n reject: false\n });\n\n if (engine === \"pglite\") await resetSharedSession(plan.target);\n\n const notice = attverNotice(attver);\n\n return { cleared: true, ...restoreOutcome(run, engine, attver), ...(notice ? { notice } : {}) };\n}\n\n/**\n * Put the managed database's one session back to its own settings.\n *\n * `RESET ALL` and `DEALLOCATE ALL`, not `DISCARD ALL`: the session is every\n * connection's, and `DISCARD` would also drop the `LISTEN` a running\n * `rebase dev`'s realtime holds on it. The same pair the backup service runs\n * after its tools (`resetSharedSession` in server-postgres' backup-service). Best effort: a daemon that cannot take this cannot take the\n * re-grant that follows either, and that step reports it.\n */\nasync function resetSharedSession(target: string): Promise<void> {\n const { Client } = await import(\"pg\");\n const client = new Client({\n connectionString: target,\n connectionTimeoutMillis: LOCAL_CONNECT_TIMEOUT_MS,\n query_timeout: LOCAL_QUERY_TIMEOUT_MS\n });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n await client.query(\"RESET ALL\");\n await client.query(\"DEALLOCATE ALL\");\n } catch {\n // Reported by the next step that connects; see above.\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\n/**\n * The lines that report a failed restore: what failed, what state the local\n * database is in now, and what to do. Plain text, for the caller to colour.\n */\nexport function describeRestoreFailure(outcome: RestoreOutcome, source: string): string[] {\n const state = outcome.started\n ? `The local database holds an incomplete copy of ${source}.`\n : outcome.cleared\n ? \"The local database was emptied, and nothing was restored into it.\"\n : \"Nothing was restored, and the local database is as it was.\";\n\n return [outcome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;CACZ,CAAC;CAED,IAAI,WAAW,UAAU,MAAM,mBAAmB,KAAK,MAAM;CAE7D,MAAM,SAAS,aAAa,MAAM;CAElC,OAAO;EAAE,SAAS;EAAM,GAAG,eAAe,KAAK,QAAQ,MAAM;EAAG,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;CAAG;AAClG;;;;;;;;;;AAWA,eAAe,mBAAmB,QAA+B;CAC7D,MAAM,EAAE,WAAW,MAAM,OAAO;CAChC,MAAM,SAAS,IAAI,OAAO;EACtB,kBAAkB;EAClB,yBAAyB;EACzB,eAAe;CACnB,CAAC;CACD,OAAO,GAAG,eAAe,KAAA,CAAS;CAClC,IAAI;EACA,MAAM,OAAO,QAAQ;EACrB,MAAM,OAAO,MAAM,WAAW;EAC9B,MAAM,OAAO,MAAM,gBAAgB;CACvC,QAAQ,CAER,UAAU;EACN,MAAM,OAAO,IAAI,CAAC,CAAC,YAAY,KAAA,CAAS;CAC5C;AACJ;;;;;AAMA,SAAgB,uBAAuB,SAAyB,QAA0B;CACtF,MAAM,QAAQ,QAAQ,UAChB,kDAAkD,OAAO,KACzD,QAAQ,UACJ,sEACA;CAEV,OAAO;EAAC,QAAQ,WAAW;EAAiC;EAAO,GAAI,QAAQ,SAAS,CAAC,QAAQ,MAAM,IAAI,CAAC;CAAE;AAClH"}
|
|
@@ -6,7 +6,7 @@ import { a as refuseRemovedCollectionsFlag, i as refuseMissingSchemaDir, n as SC
|
|
|
6
6
|
import { t as cliUserAgent } from "./version-Buyyo1ut.js";
|
|
7
7
|
import { i as requireBackendUrl, r as describeFailure } from "./api-keys-eIUjMqWn.js";
|
|
8
8
|
import { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from "./prepare-Ccxspoj-.js";
|
|
9
|
-
import { absolutizeLocalPathArgs, ensureDockerDatabase, n as argsFromCommand, spawnDriverCli, t as reportSpawnFailure } from "./db-
|
|
9
|
+
import { absolutizeLocalPathArgs, ensureDockerDatabase, n as argsFromCommand, spawnDriverCli, t as reportSpawnFailure } from "./db-Bz2RFGJj.js";
|
|
10
10
|
import chalk from "chalk";
|
|
11
11
|
import arg from "arg";
|
|
12
12
|
import { RebaseApiError } from "@rebasepro/client";
|
|
@@ -188,7 +188,7 @@ async function schemaCommand(subcommand, rawArgs) {
|
|
|
188
188
|
const projectRoot = requireProjectRoot();
|
|
189
189
|
if (subcommand === "reconcile") {
|
|
190
190
|
recordEvent("cli.schema", { subcommand }, { projectRoot });
|
|
191
|
-
const { schemaReconcileCommand } = await import("./schema-reconcile-
|
|
191
|
+
const { schemaReconcileCommand } = await import("./schema-reconcile-CjxLaRHB.js");
|
|
192
192
|
await schemaReconcileCommand(rawArgs);
|
|
193
193
|
return;
|
|
194
194
|
}
|
|
@@ -321,4 +321,4 @@ ${chalk.green.bold("stale Options")}
|
|
|
321
321
|
//#endregion
|
|
322
322
|
export { SCHEMA_SUBCOMMANDS, schemaReconcileCommand as i, describeReconcilePlan as n, parseReconcileArgs as r, schemaCommand, RECONCILE_USAGE as t };
|
|
323
323
|
|
|
324
|
-
//# sourceMappingURL=schema-
|
|
324
|
+
//# sourceMappingURL=schema-Dv6nHkb0.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-CdDjv5zI.js","names":[],"sources":["../src/commands/schema-reconcile.ts","../src/commands/schema.ts"],"sourcesContent":["/**\n * CLI command: rebase schema reconcile\n *\n * The reviewed step for what boot will not do. Boot only ever adds, so a\n * column made nullable keeps its NOT NULL, and a column removed from a table\n * leaves it behind, with its data, and blocking inserts if it was\n * required. This asks the running backend for the plan that fixes both, prints\n * it, and applies it only once confirmed.\n *\n * Through the backend rather than a database URL, because on Rebase Cloud the\n * backend is the one thing that can reach the database — and because it plans\n * against the tables it actually runs, not the ones in this checkout.\n * Columns are dropped only when named with `--drop`; the confirmation sends\n * the plan's digest, so the server runs exactly the statements printed here.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport readline from \"node:readline/promises\";\nimport { RebaseApiError } from \"@rebasepro/client\";\nimport type { SchemaReconcilePlan } from \"@rebasepro/types\";\nimport { requireProjectRoot, readEnvFile } from \"../utils/project\";\nimport { UsageError } from \"../utils/args\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { describeFailure, requireBackendUrl } from \"./api-keys\";\n\nexport const RECONCILE_USAGE = \"rebase schema reconcile [--drop <table>.<column>]... [--yes]\";\n\nexport function parseReconcileArgs(rawArgs: string[]): { drop: string[]; yes: boolean } {\n const flags = arg({ \"--drop\": [String], \"--yes\": Boolean, \"-y\": \"--yes\" }, { argv: rawArgs.slice(2) });\n if (flags._.length > 0) throw new UsageError(`Unexpected argument \"${flags._[0]}\". Usage: ${RECONCILE_USAGE}`);\n return { drop: flags[\"--drop\"] ?? [], yes: flags[\"--yes\"] === true };\n}\n\n/** The plan, as a person reviews it. Returned as lines so it can be tested. */\nexport function describeReconcilePlan(plan: SchemaReconcilePlan): string[] {\n const lines: string[] = [];\n for (const r of plan.relaxed) {\n const why = r.undeclared\n ? `\"${r.collection}\" does not declare it, and every insert fails on it; its data stays`\n : `nullable in \"${r.collection}\", NOT NULL in the database`;\n lines.push(` ${chalk.cyan(\"relax\")} ${r.table}.${r.column} ${chalk.gray(why)}`);\n }\n for (const d of plan.dropped) {\n const rows = d.rowsWithValue === undefined ? \"\" : `${d.rowsWithValue.toLocaleString(\"en-US\")} row(s) hold a value`;\n lines.push(` ${chalk.red(\"drop\")} ${d.table}.${d.column} ${chalk.red(rows)}`);\n }\n const kept = plan.undeclared.filter(u =>\n !plan.dropped.some(d => d.table === u.table && d.column === u.column)\n && !plan.relaxed.some(r => r.undeclared && r.table === u.table && r.column === u.column));\n for (const u of kept) {\n const note = u.blocksInserts\n ? chalk.yellow(\"NOT NULL with no default: every insert fails until it is dropped or relaxed\")\n : chalk.gray(\"no table declares it; kept\");\n lines.push(` ${chalk.gray(\"keep\")} ${u.table}.${u.column} ${note}`);\n }\n return lines;\n}\n\ninterface Backend {\n baseUrl: string;\n post<T>(path: string, body: unknown): Promise<T>;\n}\n\n/** The project's backend, holding the service key. */\nfunction connect(): Backend {\n const projectRoot = requireProjectRoot();\n const env = readEnvFile(projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n if (!serviceKey) {\n console.error(chalk.red(\"✗ REBASE_SERVICE_KEY not found in .env — required to change the database's schema.\"));\n process.exit(1);\n }\n const baseUrl = requireBackendUrl(env, projectRoot).replace(/\\/+$/, \"\");\n return {\n baseUrl,\n async post<T>(path: string, body: unknown): Promise<T> {\n let response: Response;\n try {\n response = await fetch(`${baseUrl}/api/admin/schema/reconcile${path}`, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": cliUserAgent()\n },\n body: JSON.stringify(body)\n });\n } catch (error: unknown) {\n throw new RebaseApiError(error instanceof Error ? error.message : String(error), { status: 0, code: \"NETWORK_ERROR\" });\n }\n const answer: unknown = await response.json().catch(() => undefined);\n if (!response.ok) {\n const error = answer && typeof answer === \"object\" && \"error\" in answer && answer.error && typeof answer.error === \"object\"\n ? answer.error as { message?: unknown; code?: unknown; details?: unknown }\n : undefined;\n throw new RebaseApiError(\n typeof error?.message === \"string\" ? error.message : `The server answered ${response.status}.`,\n { status: response.status, code: typeof error?.code === \"string\" ? error.code : undefined, details: error?.details }\n );\n }\n return answer as T;\n }\n };\n}\n\nfunction fail(action: string, error: unknown, baseUrl: string): never {\n for (const line of describeFailure(action, error, baseUrl)) {\n console.error(line.startsWith(\"✗\") ? chalk.red(line) : chalk.gray(line));\n }\n if (error instanceof RebaseApiError && error.status === 404) {\n console.error(chalk.gray(\" This backend has no reconcile route: it needs a runtime that has `rebase schema reconcile`.\"));\n }\n process.exit(1);\n}\n\nexport async function schemaReconcileCommand(rawArgs: string[]): Promise<void> {\n const { drop, yes } = parseReconcileArgs(rawArgs);\n const backend = connect();\n\n let plan: SchemaReconcilePlan;\n try {\n plan = await backend.post<SchemaReconcilePlan>(\"/plan\", { drop });\n } catch (error) {\n fail(\"Failed to plan the reconcile\", error, backend.baseUrl);\n }\n\n console.log(chalk.bold(`\\nSchema reconcile for ${backend.baseUrl}\\n`));\n const described = describeReconcilePlan(plan);\n if (described.length > 0) console.log(described.join(\"\\n\"));\n\n if (plan.problems.length > 0) {\n console.error(chalk.red(\"\\n✗ This plan cannot be applied:\"));\n for (const problem of plan.problems) console.error(chalk.red(` • ${problem}`));\n process.exit(1);\n }\n if (plan.statements.length === 0) {\n console.log(chalk.green(\"✓ Nothing to do: the database already matches what the tables declare.\"));\n }\n if (plan.undeclared.length > plan.dropped.length) {\n console.log(chalk.gray(\" To drop a column no table declares, name it: --drop <table>.<column>\"));\n }\n if (plan.statements.length === 0) return;\n\n console.log(chalk.bold(\"\\nStatements\"));\n for (const statement of plan.statements) console.log(` ${statement}`);\n if (plan.dropped.length > 0) {\n console.log(chalk.red(\"\\n Dropping a column destroys its data. Back the database up first if you may want it back.\"));\n }\n\n if (!yes) {\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"\\n✗ Not applied: confirming needs a terminal. Re-run with --yes once you have read the plan.\"));\n process.exit(1);\n }\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const answer = (await rl.question(`\\nApply ${plan.statements.length} statement(s)? Type \"yes\" to continue: `)).trim();\n rl.close();\n if (answer !== \"yes\") {\n console.log(chalk.gray(\"Aborted. Nothing was changed.\"));\n return;\n }\n }\n\n try {\n const result = await backend.post<{ applied: string[] }>(\"/apply\", { drop, confirm: plan.digest });\n console.log(chalk.green(`✓ Applied ${result.applied.length} statement(s).`));\n } catch (error) {\n if (error instanceof RebaseApiError && error.code === \"SCHEMA_RECONCILE_STALE\") {\n console.error(chalk.red(\"✗ Not applied: the database or the tables changed since this plan was made. Run it again to review the new plan.\"));\n process.exit(1);\n }\n fail(\"Failed to apply the reconcile\", error, backend.baseUrl);\n }\n}\n","/**\n * CLI command: rebase schema <action>\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { ensureDockerDatabase, spawnDriverCli } from \"./db\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile,\n exitDependenciesNotInstalled\n} from \"../utils/project\";\nimport { recordEvent } from \"../telemetry\";\nimport { wantsHelp } from \"../utils/args\";\nimport { reportSpawnFailure } from \"../utils/spawn-error\";\nimport { argsFromCommand } from \"../utils/command-words\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from \"../dev-db/prepare\";\nimport { absolutizeLocalPathArgs } from \"./db\";\nimport { SCHEMA_DIR_FLAG_HELP, refuseMissingSchemaDir, refuseRemovedCollectionsFlag } from \"../utils/path-flags\";\nimport { schemaDirArgs } from \"../utils/schema-dir\";\nimport { RECONCILE_USAGE } from \"./schema-reconcile\";\n\n/**\n * The line handed to the driver, its paths resolved from where the command was\n * run (the driver runs in `backend/`). `--schema` is left alone: on\n * `introspect` it names a Postgres schema, not a file.\n */\nexport function schemaDriverArgs(rawArgs: string[], cwd: string): string[] {\n return absolutizeLocalPathArgs(argsFromCommand(rawArgs, \"schema\"), cwd, [\"--schema-dir\", \"--output\", \"-o\", \"--out\"]);\n}\n\nexport async function schemaCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered here, before `requireProjectRoot` and before the\n // driver is spawned — the same shape `db.ts` already uses, and for the same\n // reason.\n //\n // `cli.ts` rewrites the subcommand to `\"--help\"` only when the user named\n // none, so `rebase schema --help` was covered and `rebase schema generate\n // --help` was not: the flag travelled into `rawArgs.slice(2)` and reached\n // the driver, whose own `schemaCommand` has no `--help` case. It *ran the\n // generator* — overwriting `src/schema.generated.ts` — for a flag whose\n // entire job is to print text. Worse, the first thing it hit outside a\n // project was `requireProjectRoot`, so `rebase schema introspect --help` in\n // an empty directory exited 1 with \"Could not find a Rebase project root\":\n // help you cannot read until you already have a project is help for nobody.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printSchemaHelp(subcommand === \"--help\" ? undefined : subcommand);\n return;\n }\n\n // A typo is answered here, in the same words every other family uses.\n //\n // It used to travel to the driver, which said the bare line `Unknown schema\n // command.` — no list, no pointer, no did-you-mean, for a family with three\n // subcommands. The set comes from the help table, so what a typo is measured\n // against and what `--help` prints cannot drift apart.\n if (!SCHEMA_ACTION_HELP[subcommand]) {\n unknownCommand(subcommand, Object.keys(SCHEMA_ACTION_HELP), \"schema\");\n }\n\n // Before anything else runs.\n refuseRemovedCollectionsFlag(rawArgs.slice(2), `schema ${subcommand}`);\n\n const projectRoot = requireProjectRoot();\n\n // Talks to the running backend, not the driver: on Rebase Cloud the\n // backend is the only thing that reaches the database.\n if (subcommand === \"reconcile\") {\n void recordEvent(\"cli.schema\", { subcommand }, { projectRoot });\n const { schemaReconcileCommand } = await import(\"./schema-reconcile\");\n await schemaReconcileCommand(rawArgs);\n return;\n }\n\n // Fire-and-forget, and a no-op unless the developer opted in. Never awaited:\n // the command is what the user is waiting for, and a slow collector must not\n // sit in front of it.\n void recordEvent(\"cli.schema\", { subcommand: subcommand ?? \"none\" }, { projectRoot });\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n exitDependenciesNotInstalled(projectRoot);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n // Which database this project is on, so the driver's closing line does not\n // recommend a command that database refuses. A pure decision — nothing is\n // started, which matters here above all: `schema generate` reads the\n // schema directory and writes one file, and booting a database to run it would be a\n // side effect nobody asked for.\n env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? \"\";\n\n refuseMissingSchemaDir(rawArgs, process.cwd(), backendDir);\n\n // `introspect` is the one schema command that reads a database, and it\n // reads the project's — resolved the way every `db` command resolves it,\n // started if that is what it takes. It used to pass `.env` and nothing\n // else, so on the managed database or after `rebase dev --docker` (with\n // the scaffold's DATABASE_URL commented out, on purpose) it said\n // \"DATABASE_URL is not set\", and `--docker` and `--database-url` passed the\n // flag check only to be ignored.\n if (subcommand === \"introspect\") {\n const flags = arg(\n { \"--database-url\": String, \"--docker\": Boolean },\n { argv: rawArgs.slice(2), permissive: true }\n );\n await ensureDockerDatabase(projectRoot, rawArgs);\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: flags[\"--database-url\"] ?? null,\n flagDocker: flags[\"--docker\"] === true,\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n Object.assign(env, prepared.env);\n env[DEV_DATABASE_KIND_ENV] = prepared.database.kind;\n for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));\n }\n\n try {\n // The one spawn, shared with `db`. This file used to carry its own copy\n // of the tsx-or-node decision; three copies of that rule existed and two\n // were fixed while the third went on spawning plain node.\n const driverArgs = schemaDriverArgs(rawArgs, process.cwd());\n await spawnDriverCli(\n { projectRoot, backendDir, pluginCli, env },\n [...driverArgs, ...schemaDirArgs(projectRoot, driverArgs)]\n );\n } catch (error) {\n // A child that ran and exited non-zero already printed its diagnostics\n // through inherited stdio; a child that never started (ENOENT on tsx,\n // EACCES on the script) printed nothing at all, and this used to exit 1\n // in silence.\n reportSpawnFailure(error);\n process.exit(1);\n }\n}\n\n/** One page per subcommand, so `rebase schema <action> --help` says something. */\nconst SCHEMA_ACTION_HELP: Record<string, { usage: string; summary: string; notes?: string[] }> = {\n generate: {\n usage: \"rebase schema generate [--schema-dir <dir>] [--output <file>] [--watch]\",\n summary: \"Generate the Drizzle schema from the tables in backend/schema.\",\n notes: [\"--watch regenerates on every change to a schema file.\", `--schema-dir <dir>: ${SCHEMA_DIR_FLAG_HELP}.`]\n },\n introspect: {\n usage: \"rebase schema introspect [--schema-dir <dir>] [--schema <name>] [--force] [--data-inference | --no-data-inference]\",\n summary: \"Read an existing database and write its tables as defineTable modules into backend/schema.\",\n notes: [\n \"--force overwrites table modules that are already there.\",\n `--schema-dir <dir>: where the tables are written — ${SCHEMA_DIR_FLAG_HELP}.`,\n \"--data-inference samples up to 100 rows per table to detect formats, constraints and UI settings; \"\n + \"--no-data-inference reads the structure only. Without either it asks, and without a terminal \"\n + \"it reads the structure only.\",\n \"Reads this project's database, the one `rebase db url` prints: --database-url <url> names another; \"\n + \"--docker uses the compose one, starting it if needed.\"\n ]\n },\n reconcile: {\n usage: RECONCILE_USAGE,\n summary: \"Relax and drop what boot will not: NOT NULL on columns made nullable, and columns no table declares.\",\n notes: [\n \"Plans on the running backend (the one `.env` and the cloud link point at), prints the plan, and applies it once you type yes.\",\n \"A column is dropped only when named: --drop voice_cache.wav. Each drop shows how many rows hold a value.\",\n \"--yes skips the prompt, for a plan already read. Needs REBASE_SERVICE_KEY in .env.\"\n ]\n },\n stale: {\n usage: \"rebase schema stale [--schema-dir <dir>] [--output <file>] [--fix]\",\n summary: \"Report generated schema files that no longer match the tables.\",\n notes: [\"--fix regenerates them instead of only reporting.\"]\n }\n};\n\n/** Every subcommand the family dispatches — the help table's keys. */\nexport const SCHEMA_SUBCOMMANDS = Object.keys(SCHEMA_ACTION_HELP);\n\nfunction printSchemaHelp(action?: string) {\n const entry = action ? SCHEMA_ACTION_HELP[action] : undefined;\n if (entry) {\n console.log(`\n${chalk.bold(`rebase schema ${action}`)}\n\n ${entry.summary}\n\n${chalk.green.bold(\"Usage\")}\n ${chalk.blue(entry.usage)}\n${entry.notes?.length ? `\\n${chalk.green.bold(\"Notes\")}\\n${entry.notes.map(n => ` ${chalk.gray(`• ${n}`)}`).join(\"\\n\")}\\n` : \"\"}\n${chalk.gray(\"Run `rebase schema --help` for every subcommand.\")}\n`);\n return;\n }\n\n console.log(`\n${chalk.bold(\"rebase schema\")} — Schema management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase schema ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"generate\")} Generate the Drizzle schema from the tables in backend/schema\n ${chalk.blue.bold(\"introspect\")} Introspect an existing database into defineTable modules in backend/schema\n ${chalk.blue.bold(\"stale\")} Report generated schema files that no longer match the tables\n ${chalk.blue.bold(\"reconcile\")} Relax NOT NULL and drop columns the tables no longer declare, after review\n\n${chalk.green.bold(\"generate / stale Options\")}\n ${chalk.blue(\"--schema-dir\")} ${SCHEMA_DIR_FLAG_HELP}\n ${chalk.blue(\"--output, -o\")} Output path for generated schema\n ${chalk.blue(\"--watch, -w\")} Watch for changes and regenerate automatically\n\n${chalk.green.bold(\"introspect Options\")}\n ${chalk.blue(\"--schema-dir\")} Where the tables are written ${chalk.gray(\"(default: backend/schema)\")}\n ${chalk.blue(\"--schema\")} Postgres schema to read (default: public)\n ${chalk.blue(\"--force, -f\")} Overwrite table modules that already exist\n ${chalk.blue(\"--database-url\")} Read this database instead of the project's own\n ${chalk.blue(\"--docker\")} Read the compose database, starting it if needed\n ${chalk.blue(\"--data-inference\")} Sample rows to detect formats and constraints ${chalk.gray(\"(asked when omitted)\")}\n ${chalk.blue(\"--no-data-inference\")} Read the structure only, without asking\n\n${chalk.green.bold(\"stale Options\")}\n ${chalk.blue(\"--fix\")} Regenerate the stale files instead of only reporting them\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,kBAAkB;AAE/B,SAAgB,mBAAmB,SAAqD;CACpF,MAAM,QAAQ,IAAI;EAAE,UAAU,CAAC,MAAM;EAAG,SAAS;EAAS,MAAM;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EAAE;IAC5B,MAAM,KAAK,KAAK,YAAY,EAAE;IAC9B,MAAM,KAAK,KAAK,OAAO,EAAE;IACzB,MAAM,KAAK,KAAK,WAAW,EAAE;;EAE/B,MAAM,MAAM,KAAK,0BAA0B,EAAE;IAC3C,MAAM,KAAK,cAAc,EAAE,SAAS,qBAAqB;IACzD,MAAM,KAAK,cAAc,EAAE;IAC3B,MAAM,KAAK,aAAa,EAAE;;EAE5B,MAAM,MAAM,KAAK,oBAAoB,EAAE;IACrC,MAAM,KAAK,cAAc,EAAE,sCAAsC,MAAM,KAAK,2BAA2B,EAAE;IACzG,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,aAAa,EAAE;IAC1B,MAAM,KAAK,gBAAgB,EAAE;IAC7B,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,kBAAkB,EAAE,mDAAmD,MAAM,KAAK,sBAAsB,EAAE;IACrH,MAAM,KAAK,qBAAqB,EAAE;;EAEpC,MAAM,MAAM,KAAK,eAAe,EAAE;IAChC,MAAM,KAAK,OAAO,EAAE;CACvB;AACD"}
|
|
1
|
+
{"version":3,"file":"schema-Dv6nHkb0.js","names":[],"sources":["../src/commands/schema-reconcile.ts","../src/commands/schema.ts"],"sourcesContent":["/**\n * CLI command: rebase schema reconcile\n *\n * The reviewed step for what boot will not do. Boot only ever adds, so a\n * column made nullable keeps its NOT NULL, and a column removed from a table\n * leaves it behind, with its data, and blocking inserts if it was\n * required. This asks the running backend for the plan that fixes both, prints\n * it, and applies it only once confirmed.\n *\n * Through the backend rather than a database URL, because on Rebase Cloud the\n * backend is the one thing that can reach the database — and because it plans\n * against the tables it actually runs, not the ones in this checkout.\n * Columns are dropped only when named with `--drop`; the confirmation sends\n * the plan's digest, so the server runs exactly the statements printed here.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport readline from \"node:readline/promises\";\nimport { RebaseApiError } from \"@rebasepro/client\";\nimport type { SchemaReconcilePlan } from \"@rebasepro/types\";\nimport { requireProjectRoot, readEnvFile } from \"../utils/project\";\nimport { UsageError } from \"../utils/args\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { describeFailure, requireBackendUrl } from \"./api-keys\";\n\nexport const RECONCILE_USAGE = \"rebase schema reconcile [--drop <table>.<column>]... [--yes]\";\n\nexport function parseReconcileArgs(rawArgs: string[]): { drop: string[]; yes: boolean } {\n const flags = arg({ \"--drop\": [String], \"--yes\": Boolean, \"-y\": \"--yes\" }, { argv: rawArgs.slice(2) });\n if (flags._.length > 0) throw new UsageError(`Unexpected argument \"${flags._[0]}\". Usage: ${RECONCILE_USAGE}`);\n return { drop: flags[\"--drop\"] ?? [], yes: flags[\"--yes\"] === true };\n}\n\n/** The plan, as a person reviews it. Returned as lines so it can be tested. */\nexport function describeReconcilePlan(plan: SchemaReconcilePlan): string[] {\n const lines: string[] = [];\n for (const r of plan.relaxed) {\n const why = r.undeclared\n ? `\"${r.collection}\" does not declare it, and every insert fails on it; its data stays`\n : `nullable in \"${r.collection}\", NOT NULL in the database`;\n lines.push(` ${chalk.cyan(\"relax\")} ${r.table}.${r.column} ${chalk.gray(why)}`);\n }\n for (const d of plan.dropped) {\n const rows = d.rowsWithValue === undefined ? \"\" : `${d.rowsWithValue.toLocaleString(\"en-US\")} row(s) hold a value`;\n lines.push(` ${chalk.red(\"drop\")} ${d.table}.${d.column} ${chalk.red(rows)}`);\n }\n const kept = plan.undeclared.filter(u =>\n !plan.dropped.some(d => d.table === u.table && d.column === u.column)\n && !plan.relaxed.some(r => r.undeclared && r.table === u.table && r.column === u.column));\n for (const u of kept) {\n const note = u.blocksInserts\n ? chalk.yellow(\"NOT NULL with no default: every insert fails until it is dropped or relaxed\")\n : chalk.gray(\"no table declares it; kept\");\n lines.push(` ${chalk.gray(\"keep\")} ${u.table}.${u.column} ${note}`);\n }\n return lines;\n}\n\ninterface Backend {\n baseUrl: string;\n post<T>(path: string, body: unknown): Promise<T>;\n}\n\n/** The project's backend, holding the service key. */\nfunction connect(): Backend {\n const projectRoot = requireProjectRoot();\n const env = readEnvFile(projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n if (!serviceKey) {\n console.error(chalk.red(\"✗ REBASE_SERVICE_KEY not found in .env — required to change the database's schema.\"));\n process.exit(1);\n }\n const baseUrl = requireBackendUrl(env, projectRoot).replace(/\\/+$/, \"\");\n return {\n baseUrl,\n async post<T>(path: string, body: unknown): Promise<T> {\n let response: Response;\n try {\n response = await fetch(`${baseUrl}/api/admin/schema/reconcile${path}`, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": cliUserAgent()\n },\n body: JSON.stringify(body)\n });\n } catch (error: unknown) {\n throw new RebaseApiError(error instanceof Error ? error.message : String(error), { status: 0, code: \"NETWORK_ERROR\" });\n }\n const answer: unknown = await response.json().catch(() => undefined);\n if (!response.ok) {\n const error = answer && typeof answer === \"object\" && \"error\" in answer && answer.error && typeof answer.error === \"object\"\n ? answer.error as { message?: unknown; code?: unknown; details?: unknown }\n : undefined;\n throw new RebaseApiError(\n typeof error?.message === \"string\" ? error.message : `The server answered ${response.status}.`,\n { status: response.status, code: typeof error?.code === \"string\" ? error.code : undefined, details: error?.details }\n );\n }\n return answer as T;\n }\n };\n}\n\nfunction fail(action: string, error: unknown, baseUrl: string): never {\n for (const line of describeFailure(action, error, baseUrl)) {\n console.error(line.startsWith(\"✗\") ? chalk.red(line) : chalk.gray(line));\n }\n if (error instanceof RebaseApiError && error.status === 404) {\n console.error(chalk.gray(\" This backend has no reconcile route: it needs a runtime that has `rebase schema reconcile`.\"));\n }\n process.exit(1);\n}\n\nexport async function schemaReconcileCommand(rawArgs: string[]): Promise<void> {\n const { drop, yes } = parseReconcileArgs(rawArgs);\n const backend = connect();\n\n let plan: SchemaReconcilePlan;\n try {\n plan = await backend.post<SchemaReconcilePlan>(\"/plan\", { drop });\n } catch (error) {\n fail(\"Failed to plan the reconcile\", error, backend.baseUrl);\n }\n\n console.log(chalk.bold(`\\nSchema reconcile for ${backend.baseUrl}\\n`));\n const described = describeReconcilePlan(plan);\n if (described.length > 0) console.log(described.join(\"\\n\"));\n\n if (plan.problems.length > 0) {\n console.error(chalk.red(\"\\n✗ This plan cannot be applied:\"));\n for (const problem of plan.problems) console.error(chalk.red(` • ${problem}`));\n process.exit(1);\n }\n if (plan.statements.length === 0) {\n console.log(chalk.green(\"✓ Nothing to do: the database already matches what the tables declare.\"));\n }\n if (plan.undeclared.length > plan.dropped.length) {\n console.log(chalk.gray(\" To drop a column no table declares, name it: --drop <table>.<column>\"));\n }\n if (plan.statements.length === 0) return;\n\n console.log(chalk.bold(\"\\nStatements\"));\n for (const statement of plan.statements) console.log(` ${statement}`);\n if (plan.dropped.length > 0) {\n console.log(chalk.red(\"\\n Dropping a column destroys its data. Back the database up first if you may want it back.\"));\n }\n\n if (!yes) {\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"\\n✗ Not applied: confirming needs a terminal. Re-run with --yes once you have read the plan.\"));\n process.exit(1);\n }\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const answer = (await rl.question(`\\nApply ${plan.statements.length} statement(s)? Type \"yes\" to continue: `)).trim();\n rl.close();\n if (answer !== \"yes\") {\n console.log(chalk.gray(\"Aborted. Nothing was changed.\"));\n return;\n }\n }\n\n try {\n const result = await backend.post<{ applied: string[] }>(\"/apply\", { drop, confirm: plan.digest });\n console.log(chalk.green(`✓ Applied ${result.applied.length} statement(s).`));\n } catch (error) {\n if (error instanceof RebaseApiError && error.code === \"SCHEMA_RECONCILE_STALE\") {\n console.error(chalk.red(\"✗ Not applied: the database or the tables changed since this plan was made. Run it again to review the new plan.\"));\n process.exit(1);\n }\n fail(\"Failed to apply the reconcile\", error, backend.baseUrl);\n }\n}\n","/**\n * CLI command: rebase schema <action>\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { ensureDockerDatabase, spawnDriverCli } from \"./db\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile,\n exitDependenciesNotInstalled\n} from \"../utils/project\";\nimport { recordEvent } from \"../telemetry\";\nimport { wantsHelp } from \"../utils/args\";\nimport { reportSpawnFailure } from \"../utils/spawn-error\";\nimport { argsFromCommand } from \"../utils/command-words\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from \"../dev-db/prepare\";\nimport { absolutizeLocalPathArgs } from \"./db\";\nimport { SCHEMA_DIR_FLAG_HELP, refuseMissingSchemaDir, refuseRemovedCollectionsFlag } from \"../utils/path-flags\";\nimport { schemaDirArgs } from \"../utils/schema-dir\";\nimport { RECONCILE_USAGE } from \"./schema-reconcile\";\n\n/**\n * The line handed to the driver, its paths resolved from where the command was\n * run (the driver runs in `backend/`). `--schema` is left alone: on\n * `introspect` it names a Postgres schema, not a file.\n */\nexport function schemaDriverArgs(rawArgs: string[], cwd: string): string[] {\n return absolutizeLocalPathArgs(argsFromCommand(rawArgs, \"schema\"), cwd, [\"--schema-dir\", \"--output\", \"-o\", \"--out\"]);\n}\n\nexport async function schemaCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered here, before `requireProjectRoot` and before the\n // driver is spawned — the same shape `db.ts` already uses, and for the same\n // reason.\n //\n // `cli.ts` rewrites the subcommand to `\"--help\"` only when the user named\n // none, so `rebase schema --help` was covered and `rebase schema generate\n // --help` was not: the flag travelled into `rawArgs.slice(2)` and reached\n // the driver, whose own `schemaCommand` has no `--help` case. It *ran the\n // generator* — overwriting `src/schema.generated.ts` — for a flag whose\n // entire job is to print text. Worse, the first thing it hit outside a\n // project was `requireProjectRoot`, so `rebase schema introspect --help` in\n // an empty directory exited 1 with \"Could not find a Rebase project root\":\n // help you cannot read until you already have a project is help for nobody.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printSchemaHelp(subcommand === \"--help\" ? undefined : subcommand);\n return;\n }\n\n // A typo is answered here, in the same words every other family uses.\n //\n // It used to travel to the driver, which said the bare line `Unknown schema\n // command.` — no list, no pointer, no did-you-mean, for a family with three\n // subcommands. The set comes from the help table, so what a typo is measured\n // against and what `--help` prints cannot drift apart.\n if (!SCHEMA_ACTION_HELP[subcommand]) {\n unknownCommand(subcommand, Object.keys(SCHEMA_ACTION_HELP), \"schema\");\n }\n\n // Before anything else runs.\n refuseRemovedCollectionsFlag(rawArgs.slice(2), `schema ${subcommand}`);\n\n const projectRoot = requireProjectRoot();\n\n // Talks to the running backend, not the driver: on Rebase Cloud the\n // backend is the only thing that reaches the database.\n if (subcommand === \"reconcile\") {\n void recordEvent(\"cli.schema\", { subcommand }, { projectRoot });\n const { schemaReconcileCommand } = await import(\"./schema-reconcile\");\n await schemaReconcileCommand(rawArgs);\n return;\n }\n\n // Fire-and-forget, and a no-op unless the developer opted in. Never awaited:\n // the command is what the user is waiting for, and a slow collector must not\n // sit in front of it.\n void recordEvent(\"cli.schema\", { subcommand: subcommand ?? \"none\" }, { projectRoot });\n const backendDir = requireBackendDir(projectRoot);\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n exitDependenciesNotInstalled(projectRoot);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n // Which database this project is on, so the driver's closing line does not\n // recommend a command that database refuses. A pure decision — nothing is\n // started, which matters here above all: `schema generate` reads the\n // schema directory and writes one file, and booting a database to run it would be a\n // side effect nobody asked for.\n env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? \"\";\n\n refuseMissingSchemaDir(rawArgs, process.cwd(), backendDir);\n\n // `introspect` is the one schema command that reads a database, and it\n // reads the project's — resolved the way every `db` command resolves it,\n // started if that is what it takes. It used to pass `.env` and nothing\n // else, so on the managed database or after `rebase dev --docker` (with\n // the scaffold's DATABASE_URL commented out, on purpose) it said\n // \"DATABASE_URL is not set\", and `--docker` and `--database-url` passed the\n // flag check only to be ignored.\n if (subcommand === \"introspect\") {\n const flags = arg(\n { \"--database-url\": String, \"--docker\": Boolean },\n { argv: rawArgs.slice(2), permissive: true }\n );\n await ensureDockerDatabase(projectRoot, rawArgs);\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: flags[\"--database-url\"] ?? null,\n flagDocker: flags[\"--docker\"] === true,\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n Object.assign(env, prepared.env);\n env[DEV_DATABASE_KIND_ENV] = prepared.database.kind;\n for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));\n }\n\n try {\n // The one spawn, shared with `db`. This file used to carry its own copy\n // of the tsx-or-node decision; three copies of that rule existed and two\n // were fixed while the third went on spawning plain node.\n const driverArgs = schemaDriverArgs(rawArgs, process.cwd());\n await spawnDriverCli(\n { projectRoot, backendDir, pluginCli, env },\n [...driverArgs, ...schemaDirArgs(projectRoot, driverArgs)]\n );\n } catch (error) {\n // A child that ran and exited non-zero already printed its diagnostics\n // through inherited stdio; a child that never started (ENOENT on tsx,\n // EACCES on the script) printed nothing at all, and this used to exit 1\n // in silence.\n reportSpawnFailure(error);\n process.exit(1);\n }\n}\n\n/** One page per subcommand, so `rebase schema <action> --help` says something. */\nconst SCHEMA_ACTION_HELP: Record<string, { usage: string; summary: string; notes?: string[] }> = {\n generate: {\n usage: \"rebase schema generate [--schema-dir <dir>] [--output <file>] [--watch]\",\n summary: \"Generate the Drizzle schema from the tables in backend/schema.\",\n notes: [\"--watch regenerates on every change to a schema file.\", `--schema-dir <dir>: ${SCHEMA_DIR_FLAG_HELP}.`]\n },\n introspect: {\n usage: \"rebase schema introspect [--schema-dir <dir>] [--schema <name>] [--force] [--data-inference | --no-data-inference]\",\n summary: \"Read an existing database and write its tables as defineTable modules into backend/schema.\",\n notes: [\n \"--force overwrites table modules that are already there.\",\n `--schema-dir <dir>: where the tables are written — ${SCHEMA_DIR_FLAG_HELP}.`,\n \"--data-inference samples up to 100 rows per table to detect formats, constraints and UI settings; \"\n + \"--no-data-inference reads the structure only. Without either it asks, and without a terminal \"\n + \"it reads the structure only.\",\n \"Reads this project's database, the one `rebase db url` prints: --database-url <url> names another; \"\n + \"--docker uses the compose one, starting it if needed.\"\n ]\n },\n reconcile: {\n usage: RECONCILE_USAGE,\n summary: \"Relax and drop what boot will not: NOT NULL on columns made nullable, and columns no table declares.\",\n notes: [\n \"Plans on the running backend (the one `.env` and the cloud link point at), prints the plan, and applies it once you type yes.\",\n \"A column is dropped only when named: --drop voice_cache.wav. Each drop shows how many rows hold a value.\",\n \"--yes skips the prompt, for a plan already read. Needs REBASE_SERVICE_KEY in .env.\"\n ]\n },\n stale: {\n usage: \"rebase schema stale [--schema-dir <dir>] [--output <file>] [--fix]\",\n summary: \"Report generated schema files that no longer match the tables.\",\n notes: [\"--fix regenerates them instead of only reporting.\"]\n }\n};\n\n/** Every subcommand the family dispatches — the help table's keys. */\nexport const SCHEMA_SUBCOMMANDS = Object.keys(SCHEMA_ACTION_HELP);\n\nfunction printSchemaHelp(action?: string) {\n const entry = action ? SCHEMA_ACTION_HELP[action] : undefined;\n if (entry) {\n console.log(`\n${chalk.bold(`rebase schema ${action}`)}\n\n ${entry.summary}\n\n${chalk.green.bold(\"Usage\")}\n ${chalk.blue(entry.usage)}\n${entry.notes?.length ? `\\n${chalk.green.bold(\"Notes\")}\\n${entry.notes.map(n => ` ${chalk.gray(`• ${n}`)}`).join(\"\\n\")}\\n` : \"\"}\n${chalk.gray(\"Run `rebase schema --help` for every subcommand.\")}\n`);\n return;\n }\n\n console.log(`\n${chalk.bold(\"rebase schema\")} — Schema management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase schema ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"generate\")} Generate the Drizzle schema from the tables in backend/schema\n ${chalk.blue.bold(\"introspect\")} Introspect an existing database into defineTable modules in backend/schema\n ${chalk.blue.bold(\"stale\")} Report generated schema files that no longer match the tables\n ${chalk.blue.bold(\"reconcile\")} Relax NOT NULL and drop columns the tables no longer declare, after review\n\n${chalk.green.bold(\"generate / stale Options\")}\n ${chalk.blue(\"--schema-dir\")} ${SCHEMA_DIR_FLAG_HELP}\n ${chalk.blue(\"--output, -o\")} Output path for generated schema\n ${chalk.blue(\"--watch, -w\")} Watch for changes and regenerate automatically\n\n${chalk.green.bold(\"introspect Options\")}\n ${chalk.blue(\"--schema-dir\")} Where the tables are written ${chalk.gray(\"(default: backend/schema)\")}\n ${chalk.blue(\"--schema\")} Postgres schema to read (default: public)\n ${chalk.blue(\"--force, -f\")} Overwrite table modules that already exist\n ${chalk.blue(\"--database-url\")} Read this database instead of the project's own\n ${chalk.blue(\"--docker\")} Read the compose database, starting it if needed\n ${chalk.blue(\"--data-inference\")} Sample rows to detect formats and constraints ${chalk.gray(\"(asked when omitted)\")}\n ${chalk.blue(\"--no-data-inference\")} Read the structure only, without asking\n\n${chalk.green.bold(\"stale Options\")}\n ${chalk.blue(\"--fix\")} Regenerate the stale files instead of only reporting them\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,kBAAkB;AAE/B,SAAgB,mBAAmB,SAAqD;CACpF,MAAM,QAAQ,IAAI;EAAE,UAAU,CAAC,MAAM;EAAG,SAAS;EAAS,MAAM;CAAQ,GAAG,EAAE,MAAM,QAAQ,MAAM,CAAC,EAAE,CAAC;CACrG,IAAI,MA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AO,EAAE;IACzB,MAAM,KAAK,KAAK,WAAW,EAAE;;EAE/B,MAAM,MAAM,KAAK,0BAA0B,EAAE;IAC3C,MAAM,KAAK,cAAc,EAAE,SAAS,qBAAqB;IACzD,MAAM,KAAK,cAAc,EAAE;IAC3B,MAAM,KAAK,aAAa,EAAE;;EAE5B,MAAM,MAAM,KAAK,oBAAoB,EAAE;IACrC,MAAM,KAAK,cAAc,EAAE,sCAAsC,MAAM,KAAK,2BAA2B,EAAE;IACzG,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,aAAa,EAAE;IAC1B,MAAM,KAAK,gBAAgB,EAAE;IAC7B,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,kBAAkB,EAAE,mDAAmD,MAAM,KAAK,sBAAsB,EAAE;IACrH,MAAM,KAAK,qBAAqB,EAAE;;EAEpC,MAAM,MAAM,KAAK,eAAe,EAAE;IAChC,MAAM,KAAK,OAAO,EAAE;CACvB;AACD"}
|
|
@@ -5,7 +5,7 @@ import { c as withImplicitDefaults, n as deriveOptionsFor, o as readResourceGrap
|
|
|
5
5
|
import { a as parseLoopbackDsn, o as probeTcp } from "./dev-preflight-DjvcV6SK.js";
|
|
6
6
|
import { i as managedUrl, r as findRunningDaemon } from "./daemon-w30PsdwV.js";
|
|
7
7
|
import { resolveProjectDatabaseAndBranch } from "./prepare-Ccxspoj-.js";
|
|
8
|
-
import { describeTarget } from "./pull-
|
|
8
|
+
import { describeTarget } from "./pull-BMuiUyjb.js";
|
|
9
9
|
import chalk from "chalk";
|
|
10
10
|
import fs from "fs";
|
|
11
11
|
import path from "path";
|
|
@@ -427,4 +427,4 @@ async function statusCommand(rawArgs) {
|
|
|
427
427
|
//#endregion
|
|
428
428
|
export { statusCommand };
|
|
429
429
|
|
|
430
|
-
//# sourceMappingURL=status-
|
|
430
|
+
//# sourceMappingURL=status-BTgTWzlQ.js.map
|