@rebasepro/server-postgres 0.9.1-canary.f0ac103 → 0.9.1-canary.fd3754b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/PostgresBackendDriver.d.ts +2 -25
  2. package/dist/PostgresBootstrapper.d.ts +0 -10
  3. package/dist/auth/services.d.ts +0 -16
  4. package/dist/chunk-DSJWtz9O.js +40 -0
  5. package/dist/connection.d.ts +0 -21
  6. package/dist/data-transformer.d.ts +2 -9
  7. package/dist/index.es.js +2604 -2007
  8. package/dist/index.es.js.map +1 -1
  9. package/dist/schema/auth-default-policies.d.ts +10 -0
  10. package/dist/security/policy-drift.d.ts +5 -16
  11. package/dist/security/rls-enforcement.d.ts +2 -27
  12. package/dist/services/FetchService.d.ts +24 -4
  13. package/dist/services/PersistService.d.ts +1 -27
  14. package/dist/services/RelationService.d.ts +1 -34
  15. package/dist/services/collection-helpers.d.ts +14 -79
  16. package/dist/services/dataService.d.ts +1 -3
  17. package/dist/services/index.d.ts +1 -1
  18. package/dist/services/realtimeService.d.ts +0 -7
  19. package/dist/src-Eh-CZosp.js +595 -0
  20. package/dist/src-Eh-CZosp.js.map +1 -0
  21. package/package.json +17 -15
  22. package/src/PostgresBackendDriver.ts +13 -127
  23. package/src/PostgresBootstrapper.ts +26 -68
  24. package/src/auth/ensure-tables.ts +11 -73
  25. package/src/auth/services.ts +19 -49
  26. package/src/cli-helpers.ts +20 -2
  27. package/src/connection.ts +1 -61
  28. package/src/data-transformer.ts +9 -11
  29. package/src/databasePoolManager.ts +0 -2
  30. package/src/schema/auth-default-policies.ts +125 -0
  31. package/src/schema/doctor-cli.ts +1 -5
  32. package/src/schema/generate-drizzle-schema-logic.ts +29 -24
  33. package/src/schema/generate-postgres-ddl-logic.ts +28 -76
  34. package/src/schema/introspect-db.ts +2 -19
  35. package/src/security/policy-drift.test.ts +14 -48
  36. package/src/security/policy-drift.ts +10 -72
  37. package/src/security/rls-enforcement.ts +3 -64
  38. package/src/services/BranchService.ts +10 -42
  39. package/src/services/FetchService.ts +270 -65
  40. package/src/services/PersistService.ts +14 -130
  41. package/src/services/RelationService.ts +94 -153
  42. package/src/services/collection-helpers.ts +47 -164
  43. package/src/services/dataService.ts +2 -3
  44. package/src/services/index.ts +0 -1
  45. package/src/services/realtimeService.ts +19 -40
  46. package/src/utils/drizzle-conditions.ts +0 -13
  47. package/src/websocket.ts +1 -4
  48. package/dist/collections/buildRegistry.d.ts +0 -27
  49. package/dist/services/row-pipeline.d.ts +0 -63
  50. package/src/collections/buildRegistry.ts +0 -59
  51. package/src/services/row-pipeline.ts +0 -215
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, it } from "@jest/globals";
2
2
  import type { CollectionConfig } from "@rebasepro/types";
3
3
 
4
- import { checkPolicyDrift, parseExpectedPolicies, formatPolicyDrift, hasDrift, type PolicyRef, type Queryable } from "./policy-drift";
4
+ import { checkPolicyDrift, parseExpectedPolicies, formatPolicyDrift, hasDrift, type Queryable } from "./policy-drift";
5
5
  import { generatePostgresPoliciesDdl } from "../schema/generate-postgres-ddl-logic";
6
6
 
7
7
  function collection(slug: string): CollectionConfig {
@@ -23,17 +23,6 @@ function dbWith(rows: Record<string, unknown>[]): Queryable {
23
23
  return { query: async () => ({ rows: rows as never[] }) };
24
24
  }
25
25
 
26
- /** A pg_policies row matching an expected policy, clauses and all. */
27
- function liveRow(p: PolicyRef, overrides: Record<string, unknown> = {}) {
28
- return {
29
- schemaname: p.schema, tablename: p.table, policyname: p.name, roles: p.roles, cmd: p.command,
30
- // Postgres rewrites the text it stores; only presence is compared.
31
- qual: p.hasUsing ? "(rewritten by postgres)" : null,
32
- with_check: p.hasWithCheck ? "(rewritten by postgres)" : null,
33
- ...overrides
34
- };
35
- }
36
-
37
26
  describe("parseExpectedPolicies", () => {
38
27
  it("reads the DDL that db push actually applies", () => {
39
28
  const ddl = generatePostgresPoliciesDdl([collection("authors")]);
@@ -49,8 +38,11 @@ describe("checkPolicyDrift", () => {
49
38
  it("reports nothing when the database matches the collections", async () => {
50
39
  const cols = [collection("authors")];
51
40
  const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
41
+ const live = expected.map((p) => ({
42
+ schemaname: p.schema, tablename: p.table, policyname: p.name, roles: p.roles, cmd: p.command
43
+ }));
52
44
 
53
- const drift = await checkPolicyDrift(dbWith(expected.map((p) => liveRow(p))), cols);
45
+ const drift = await checkPolicyDrift(dbWith(live), cols);
54
46
 
55
47
  expect(hasDrift(drift)).toBe(false);
56
48
  expect(formatPolicyDrift(drift)).toBe("");
@@ -70,8 +62,8 @@ describe("checkPolicyDrift", () => {
70
62
  const cols = [collection("customers")];
71
63
  const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
72
64
  const live = [
73
- ...expected.map((p) => liveRow(p)),
74
- { schemaname: "public", tablename: "customers", policyname: "test_policy", roles: ["authenticated"], cmd: "ALL", qual: "true", with_check: null }
65
+ ...expected.map((p) => ({ schemaname: p.schema, tablename: p.table, policyname: p.name, roles: p.roles, cmd: p.command })),
66
+ { schemaname: "public", tablename: "customers", policyname: "test_policy", roles: ["authenticated"], cmd: "ALL" }
75
67
  ];
76
68
 
77
69
  const drift = await checkPolicyDrift(dbWith(live), cols);
@@ -84,8 +76,11 @@ describe("checkPolicyDrift", () => {
84
76
  it("flags a policy whose roles were changed underneath it as diverged", async () => {
85
77
  const cols = [collection("orders")];
86
78
  const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
87
- // Someone re-granted it to a role requests never run as.
88
- const live = expected.map((p) => liveRow(p, { roles: ["authenticated"] }));
79
+ const live = expected.map((p) => ({
80
+ schemaname: p.schema, tablename: p.table, policyname: p.name,
81
+ // Someone re-granted it to a role requests never run as.
82
+ roles: ["authenticated"], cmd: p.command
83
+ }));
89
84
 
90
85
  const drift = await checkPolicyDrift(dbWith(live), cols);
91
86
 
@@ -94,38 +89,9 @@ describe("checkPolicyDrift", () => {
94
89
  expect(formatPolicyDrift(drift)).toContain("Diverged");
95
90
  });
96
91
 
97
- it("flags a policy whose expression the database is missing entirely", async () => {
98
- // A real production database had jobs.public_read_published stored as
99
- // SELECT / {public} / USING NULL: every field this used to compare
100
- // matched, drift reported zero, and the policy denied 100% of reads.
101
- const cols = [collection("jobs")];
102
- const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
103
- const select = expected.find((p) => p.command === "SELECT" && p.roles.includes("public"))!;
104
- const live = expected.map((p) => (p === select ? liveRow(p, { qual: null }) : liveRow(p)));
105
-
106
- const drift = await checkPolicyDrift(dbWith(live), cols);
107
-
108
- expect(drift.diverged).toHaveLength(1);
109
- expect(drift.diverged[0].differences.join(" ")).toContain("USING: expected an expression, database has none");
110
- });
111
-
112
- it("does not mistake an expression Postgres rewrote for a missing one", async () => {
113
- // The reason expression text is not compared: what comes back out of
114
- // pg_policies never matches what went in.
115
- const cols = [collection("posts")];
116
- const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(cols));
117
- const live = expected.map((p) => liveRow(p, {
118
- qual: p.hasUsing ? "((auth.uid() IS NOT NULL) AND ((auth.uid())::text <> 'anonymous'::text))" : null
119
- }));
120
-
121
- const drift = await checkPolicyDrift(dbWith(live), cols);
122
-
123
- expect(hasDrift(drift)).toBe(false);
124
- });
125
-
126
92
  it("parses roles when the driver returns the raw {a,b} text form", async () => {
127
93
  const cols = [collection("tags")];
128
- const live = [{ schemaname: "public", tablename: "tags", policyname: "test_policy", roles: "{authenticated,anon}", cmd: "ALL", qual: "true", with_check: null }];
94
+ const live = [{ schemaname: "public", tablename: "tags", policyname: "test_policy", roles: "{authenticated,anon}", cmd: "ALL" }];
129
95
 
130
96
  const drift = await checkPolicyDrift(dbWith(live), cols);
131
97
 
@@ -138,7 +104,7 @@ describe("checkPolicyDrift", () => {
138
104
  // Note a collection with no securityRules is NOT this case — it still
139
105
  // generates default (admin-only) policies.
140
106
  const drift = await checkPolicyDrift(
141
- dbWith([{ schemaname: "public", tablename: "x", policyname: "p", roles: ["public"], cmd: "ALL", qual: "true", with_check: null }]),
107
+ dbWith([{ schemaname: "public", tablename: "x", policyname: "p", roles: ["public"], cmd: "ALL" }]),
142
108
  []
143
109
  );
144
110
 
@@ -25,10 +25,6 @@ export interface PolicyRef {
25
25
  roles: string[];
26
26
  /** SELECT / INSERT / UPDATE / DELETE / ALL. */
27
27
  command: string;
28
- /** Whether a USING clause is present at all (not what it says). */
29
- hasUsing: boolean;
30
- /** Whether a WITH CHECK clause is present at all (not what it says). */
31
- hasWithCheck: boolean;
32
28
  }
33
29
 
34
30
  export interface PolicyDrift {
@@ -44,57 +40,18 @@ export interface Queryable {
44
40
  query<R>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;
45
41
  }
46
42
 
47
- // The trailing group captures whichever clause follows the TO list, which is
48
- // what tells us the clause is present.
49
- const CREATE_POLICY = /CREATE POLICY "([^"]+)" ON "([^"]+)"\."([^"]+)"\s+AS (\w+)\s+FOR (\w+)\s+TO ([^\n]+?)(\s+USING\s*\(|\s+WITH CHECK\s*\(|;)/gi;
50
-
51
- const WITH_CHECK_NEXT = /^\s+WITH CHECK\s*\(/i;
52
-
53
- /**
54
- * Index just past the `)` closing a clause whose `(` ends at `open`.
55
- *
56
- * Needed because a policy expression nests parens and can contain a quoted
57
- * literal holding either character, so "find the next `)`" would stop early and
58
- * miss the `WITH CHECK` that follows.
59
- */
60
- function clauseEnd(ddl: string, open: number): number {
61
- let depth = 1;
62
- let inQuote = false;
63
- for (let i = open; i < ddl.length; i++) {
64
- const c = ddl[i];
65
- if (inQuote) {
66
- // '' is an escaped quote inside a string, not a close.
67
- if (c === "'") {
68
- if (ddl[i + 1] === "'") i++;
69
- else inQuote = false;
70
- }
71
- continue;
72
- }
73
- if (c === "'") inQuote = true;
74
- else if (c === "(") depth++;
75
- else if (c === ")" && --depth === 0) return i + 1;
76
- }
77
- return ddl.length;
78
- }
43
+ const CREATE_POLICY = /CREATE POLICY "([^"]+)" ON "([^"]+)"\."([^"]+)"\s+AS (\w+)\s+FOR (\w+)\s+TO ([^\n]+?)(?:\s+USING|\s+WITH CHECK|;)/gi;
79
44
 
80
45
  /** Parse the generated DDL rather than rebuilding the shape by hand. */
81
46
  export function parseExpectedPolicies(ddl: string): PolicyRef[] {
82
47
  const found: PolicyRef[] = [];
83
48
  for (const m of ddl.matchAll(CREATE_POLICY)) {
84
- const [, name, schema, table, , command, rolesRaw, clause] = m;
49
+ const [, name, schema, table, , command, rolesRaw] = m;
85
50
  const roles = rolesRaw
86
51
  .split(",")
87
52
  .map((r) => r.trim().replace(/^"|"$/g, ""))
88
53
  .filter(Boolean);
89
-
90
- // The generator emits USING before WITH CHECK, so what follows the TO
91
- // list settles USING; WITH CHECK is then whatever follows that clause.
92
- const hasUsing = /USING/i.test(clause);
93
- const hasWithCheck = hasUsing
94
- ? WITH_CHECK_NEXT.test(ddl.slice(clauseEnd(ddl, m.index + m[0].length)))
95
- : /WITH CHECK/i.test(clause);
96
-
97
- found.push({ schema, table, name, roles, command: command.toUpperCase(), hasUsing, hasWithCheck });
54
+ found.push({ schema, table, name, roles, command: command.toUpperCase() });
98
55
  }
99
56
  return found;
100
57
  }
@@ -102,9 +59,8 @@ export function parseExpectedPolicies(ddl: string): PolicyRef[] {
102
59
  async function readLivePolicies(client: Queryable, schemas: string[]): Promise<PolicyRef[]> {
103
60
  const { rows } = await client.query<{
104
61
  schemaname: string; tablename: string; policyname: string; roles: string[] | string; cmd: string;
105
- qual: string | null; with_check: string | null;
106
62
  }>(
107
- `SELECT schemaname, tablename, policyname, roles, cmd, qual, with_check
63
+ `SELECT schemaname, tablename, policyname, roles, cmd
108
64
  FROM pg_policies
109
65
  WHERE schemaname = ANY($1)`,
110
66
  [schemas]
@@ -118,11 +74,7 @@ async function readLivePolicies(client: Queryable, schemas: string[]): Promise<P
118
74
  roles: Array.isArray(r.roles)
119
75
  ? r.roles
120
76
  : String(r.roles ?? "").replace(/^\{|\}$/g, "").split(",").filter(Boolean),
121
- command: (r.cmd ?? "ALL").toUpperCase(),
122
- // Presence only. Postgres rewrites the text, but it does not invent or
123
- // drop a clause: NULL here means the policy genuinely has none.
124
- hasUsing: r.qual != null,
125
- hasWithCheck: r.with_check != null
77
+ command: (r.cmd ?? "ALL").toUpperCase()
126
78
  }));
127
79
  }
128
80
 
@@ -133,18 +85,11 @@ const sameRoles = (a: string[], b: string[]) =>
133
85
  /**
134
86
  * Diff expected against live.
135
87
  *
136
- * Compares names, roles, command, and whether each clause exists — all exact
137
- * values. Policy expression *text* is deliberately not compared: Postgres
138
- * rewrites `qual`/`with_check` when storing them (parenthesising, casting,
139
- * schema-qualifying), so text comparison reports drift that does not exist, and
140
- * a check that cries wolf gets ignored.
141
- *
142
- * Presence is not text, though. A NULL `qual` is not a rewrite of an
143
- * expression, it is the absence of one, and absence has no false-positive risk:
144
- * either the generator emitted a clause or it did not. That distinction is worth
145
- * the extra comparison — a production database was found with a SELECT policy
146
- * whose `qual` was NULL, matching on every field this checked and denying 100%
147
- * of reads. The same blindness would hide a policy that fails open.
88
+ * Compares names, roles and command only — all exact values. Policy
89
+ * *expressions* are deliberately not compared: Postgres rewrites `qual`/
90
+ * `with_check` when storing them (parenthesising, casting, schema-qualifying),
91
+ * so text comparison reports drift that does not exist, and a check that cries
92
+ * wolf gets ignored. Roles alone catch the failure this exists for.
148
93
  */
149
94
  export async function checkPolicyDrift(
150
95
  client: Queryable,
@@ -175,13 +120,6 @@ export async function checkPolicyDrift(
175
120
  if (want.command !== got.command) {
176
121
  differences.push(`command: expected ${want.command}, database has ${got.command}`);
177
122
  }
178
- for (const clause of ["USING", "WITH CHECK"] as const) {
179
- const key = clause === "USING" ? "hasUsing" : "hasWithCheck";
180
- if (want[key] === got[key]) continue;
181
- differences.push(want[key]
182
- ? `${clause}: expected an expression, database has none — this policy matches no rows`
183
- : `${clause}: expected none, database has an expression`);
184
- }
185
123
  if (differences.length > 0) drift.diverged.push({ expected: want, actual: got, differences });
186
124
  }
187
125
 
@@ -1,6 +1,4 @@
1
1
  import { sql as drizzleSql, SQL } from "drizzle-orm";
2
- import { ANONYMOUS_USER_ID, PolicyExpression, SecurityRule } from "@rebasepro/types";
3
- import { AnonymousGrantRisk, findAnonymousGrants, securityRuleToConditions } from "@rebasepro/common";
4
2
  import { logger } from "@rebasepro/server";
5
3
 
6
4
  /**
@@ -202,13 +200,11 @@ export async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promi
202
200
  * treat `auth.uid() IS NULL` as the trusted server context, and `auth.uid()`
203
201
  * is `NULLIF(current_setting('app.user_id'), '')` — so an EMPTY user id would
204
202
  * be read as NULL and silently escalate a user request to server privileges.
205
- * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,
206
- * rather than trusting every caller (e.g. realtime subscription auth) to do it.
207
- * That sentinel is exported from `@rebasepro/types` because it leaks into rule
208
- * semantics: it is why `auth.uid() IS NOT NULL` is true for anonymous requests.
203
+ * Coerce empty/blank ids to a sentinel here, at the single chokepoint, rather
204
+ * than trusting every caller (e.g. realtime subscription auth) to do it.
209
205
  */
210
206
  export async function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void> {
211
- const userId = typeof auth.userId === "string" && auth.userId.trim() !== "" ? auth.userId : ANONYMOUS_USER_ID;
207
+ const userId = typeof auth.userId === "string" && auth.userId.trim() !== "" ? auth.userId : "anonymous";
212
208
  const normalizedRoles = auth.roles.map((r: unknown) =>
213
209
  typeof r === "string" ? r : (r as Record<string, unknown>)?.id ?? String(r)
214
210
  );
@@ -230,63 +226,6 @@ const FOREIGN_CONVENTION_ROLES: Record<string, string> = {
230
226
  service_role: "Supabase"
231
227
  };
232
228
 
233
- /**
234
- * Warn about rules that read as "signed-in users only" but admit anonymous
235
- * callers — `auth.uid() IS NOT NULL`, or a comparison against another
236
- * platform's magic user id such as `'anon'`.
237
- *
238
- * The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling
239
- * of the same habit. A foreign `pgRoles` value makes a policy unreachable and
240
- * the table reads empty — loud, and that guard throws. These do the opposite:
241
- * the rule compiles to a grant, and nothing looks wrong until the data is
242
- * already public.
243
- *
244
- * Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are
245
- * serving traffic today: refusing to boot would take an app offline to report a
246
- * problem it already has, and on the read path it would take it offline
247
- * *because* its data was exposed. Rewriting the author's SQL is not an option
248
- * either — this is the escape hatch whose whole promise is that it means what it
249
- * says. So: say so, loudly, and leave the rule alone.
250
- */
251
- export function warnOnAnonymousGrants(
252
- collections: { slug?: string; securityRules?: readonly SecurityRule[] }[]
253
- ): void {
254
- // Grouped by the mistake, not by the rule: one habit typically repeats
255
- // across every collection an author wrote, and a per-rule list would repeat
256
- // the same paragraph dozens of times and get skimmed.
257
- const byRisk = new Map<string, { risk: AnonymousGrantRisk; sites: string[] }>();
258
-
259
- for (const collection of collections) {
260
- for (const rule of collection.securityRules ?? []) {
261
- const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
262
- const risks = [usingExpr, withCheckExpr]
263
- .filter((e): e is PolicyExpression => e !== null)
264
- .flatMap(findAnonymousGrants);
265
-
266
- for (const risk of risks) {
267
- const key = `${risk.pattern}:${risk.detail}`;
268
- const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
269
- const entry = byRisk.get(key) ?? { risk, sites: [] };
270
- if (!entry.sites.includes(site)) entry.sites.push(site);
271
- byRisk.set(key, entry);
272
- }
273
- }
274
- }
275
-
276
- if (byRisk.size === 0) return;
277
-
278
- const problems = [...byRisk.values()].map(({ risk, sites }) =>
279
- ` • ${risk.explanation}\n ${sites.length} rule(s): ${sites.join(", ")}`
280
- );
281
-
282
- logger.warn(
283
- `Security rules that read as a lockdown but grant access to anonymous requests. Every caller from a ` +
284
- `client carries a user id ('${ANONYMOUS_USER_ID}' when nobody is signed in), so these clauses are ` +
285
- `true for everyone:\n\n` +
286
- problems.join("\n\n") + "\n"
287
- );
288
- }
289
-
290
229
  /**
291
230
  * Reject `pgRoles` that this server can never satisfy.
292
231
  *
@@ -11,45 +11,10 @@ import { sql } from "drizzle-orm";
11
11
  import { BranchInfo } from "@rebasepro/types";
12
12
  import { DrizzleClient } from "../interfaces";
13
13
  import { DatabasePoolManager } from "../databasePoolManager";
14
- import { extractPgError, extractCauseMessage } from "../utils/pg-error-utils";
15
14
 
16
15
  /** Internal prefix applied to branch database names to avoid collisions. */
17
16
  const BRANCH_DB_PREFIX = "rb_";
18
17
 
19
- /** `duplicate_database` — the target database name is already taken. */
20
- const PG_DUPLICATE_DATABASE = "42P04";
21
-
22
- /** `object_in_use` — the database still has connections attached. */
23
- const PG_OBJECT_IN_USE = "55006";
24
-
25
- /**
26
- * Describe a failed branch DDL statement in terms a user can act on.
27
- *
28
- * Drizzle reports failures as `Failed query: <sql> params:` and hides the real
29
- * PostgreSQL error in the `cause` chain, so matching on `err.message` never sees
30
- * the actual problem. Match on the PG error code instead — it survives wrapping
31
- * and, unlike the message text, is not locale-dependent.
32
- */
33
- function describeBranchDdlError(err: unknown, fallbackContext: string): Error {
34
- const pgError = extractPgError(err);
35
-
36
- if (pgError?.code === PG_DUPLICATE_DATABASE) {
37
- return new Error(`Database "${fallbackContext}" already exists on the server. Choose a different branch name.`);
38
- }
39
- if (pgError?.code === PG_OBJECT_IN_USE) {
40
- return new Error(
41
- `Cannot complete the operation: the database "${fallbackContext}" has active connections. ` +
42
- "Close other clients or connections and try again."
43
- );
44
- }
45
-
46
- // Unknown failure: surface the real PG message rather than the Drizzle
47
- // wrapper, which would otherwise show the raw SQL and no reason at all.
48
- const detail = pgError?.message ?? extractCauseMessage(err);
49
- if (detail) return new Error(detail);
50
- return err instanceof Error ? err : new Error(String(err));
51
- }
52
-
53
18
  /** Fully-qualified metadata table in the rebase schema. */
54
19
  const BRANCHES_TABLE = "rebase.branches";
55
20
 
@@ -144,15 +109,18 @@ export class BranchService {
144
109
  sql.raw(`CREATE DATABASE "${safeDbName}" TEMPLATE "${safeSourceDb}"`)
145
110
  );
146
111
  } catch (err) {
147
- const pgError = extractPgError(err);
148
- if (pgError?.code === PG_OBJECT_IN_USE) {
149
- // The template not the new database is the one still in use.
112
+ const msg = err instanceof Error ? err.message : String(err);
113
+ if (msg.includes("already exists")) {
114
+ throw new Error(`Database "${dbName}" already exists on the server. Choose a different branch name.`);
115
+ }
116
+ // If template fails due to active connections, provide a helpful error
117
+ if (msg.includes("being accessed by other users")) {
150
118
  throw new Error(
151
119
  `Cannot create branch: the source database "${sourceDb}" has active connections. ` +
152
120
  "Close other clients or connections and try again."
153
121
  );
154
122
  }
155
- throw describeBranchDdlError(err, dbName);
123
+ throw err;
156
124
  }
157
125
 
158
126
  // Record metadata in the default database
@@ -198,14 +166,14 @@ export class BranchService {
198
166
  try {
199
167
  await this.db.execute(sql.raw(`DROP DATABASE "${safeDbName}"`));
200
168
  } catch (err) {
201
- const pgError = extractPgError(err);
202
- if (pgError?.code === PG_OBJECT_IN_USE) {
169
+ const msg = err instanceof Error ? err.message : String(err);
170
+ if (msg.includes("being accessed by other users")) {
203
171
  throw new Error(
204
172
  `Cannot delete branch "${sanitizedName}": the database has active connections. ` +
205
173
  "Close other clients and try again."
206
174
  );
207
175
  }
208
- throw describeBranchDdlError(err, dbName);
176
+ throw err;
209
177
  }
210
178
 
211
179
  // Remove metadata