@supabase/pg-delta 1.0.0-alpha.13 → 1.0.0-alpha.15

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 (37) hide show
  1. package/README.md +7 -1
  2. package/dist/core/catalog.diff.js +7 -1
  3. package/dist/core/connection-url.d.ts +32 -0
  4. package/dist/core/connection-url.js +77 -0
  5. package/dist/core/expand-replace-dependencies.d.ts +8 -2
  6. package/dist/core/expand-replace-dependencies.js +24 -10
  7. package/dist/core/integrations/supabase.js +1 -0
  8. package/dist/core/objects/procedure/procedure.diff.js +8 -0
  9. package/dist/core/objects/sequence/sequence.diff.js +14 -6
  10. package/dist/core/objects/table/changes/table.alter.js +4 -1
  11. package/dist/core/objects/table/changes/table.drop.d.ts +12 -0
  12. package/dist/core/objects/table/changes/table.drop.js +20 -3
  13. package/dist/core/objects/table/table.diff.js +7 -2
  14. package/dist/core/post-diff-cycle-breaking.d.ts +22 -0
  15. package/dist/core/post-diff-cycle-breaking.js +143 -0
  16. package/dist/core/postgres-config.d.ts +27 -0
  17. package/dist/core/postgres-config.js +99 -7
  18. package/package.json +2 -1
  19. package/src/core/catalog.diff.ts +7 -1
  20. package/src/core/connection-url.test.ts +142 -0
  21. package/src/core/connection-url.ts +82 -0
  22. package/src/core/expand-replace-dependencies.test.ts +247 -8
  23. package/src/core/expand-replace-dependencies.ts +33 -5
  24. package/src/core/integrations/supabase.ts +1 -0
  25. package/src/core/objects/procedure/procedure.diff.test.ts +25 -0
  26. package/src/core/objects/procedure/procedure.diff.ts +12 -0
  27. package/src/core/objects/sequence/sequence.diff.test.ts +110 -8
  28. package/src/core/objects/sequence/sequence.diff.ts +16 -6
  29. package/src/core/objects/table/changes/table.alter.test.ts +14 -0
  30. package/src/core/objects/table/changes/table.alter.ts +4 -1
  31. package/src/core/objects/table/changes/table.drop.ts +27 -4
  32. package/src/core/objects/table/table.diff.test.ts +55 -0
  33. package/src/core/objects/table/table.diff.ts +10 -2
  34. package/src/core/post-diff-cycle-breaking.test.ts +317 -0
  35. package/src/core/post-diff-cycle-breaking.ts +236 -0
  36. package/src/core/postgres-config.test.ts +241 -0
  37. package/src/core/postgres-config.ts +127 -16
@@ -2,6 +2,7 @@
2
2
  * PostgreSQL connection configuration with custom type handlers.
3
3
  */
4
4
  import { escapeIdentifier, Pool, types } from "pg";
5
+ import { normalizeConnectionUrl } from "./connection-url.js";
5
6
  import { parseSslConfig } from "./plan/ssl-config.js";
6
7
  // ============================================================================
7
8
  // Array Parser
@@ -96,6 +97,89 @@ types.setTypeParser(1016, (val) => parseArray(val, parseIntElement)); // int8[]
96
97
  const DEFAULT_POOL_MAX = Number(process.env.PGDELTA_POOL_MAX) || 5;
97
98
  const DEFAULT_CONNECTION_TIMEOUT_MS = Number(process.env.PGDELTA_CONNECTION_TIMEOUT_MS) || 3_000;
98
99
  const DEFAULT_CONNECT_TIMEOUT_MS = Number(process.env.PGDELTA_CONNECT_TIMEOUT_MS) || 2_500;
100
+ const DEFAULT_CONNECT_MAX_ATTEMPTS = Number(process.env.PGDELTA_CONNECT_MAX_ATTEMPTS) || 3;
101
+ const DEFAULT_CONNECT_BASE_BACKOFF_MS = Number(process.env.PGDELTA_CONNECT_BASE_BACKOFF_MS) || 250;
102
+ const DEFAULT_CONNECT_MAX_BACKOFF_MS = Number(process.env.PGDELTA_CONNECT_MAX_BACKOFF_MS) || 1_000;
103
+ // PostgreSQL auth-class SQLSTATE codes: not retryable.
104
+ const NON_RETRYABLE_PG_CODES = new Set([
105
+ "28000", // invalid_authorization_specification
106
+ "28P01", // invalid_password
107
+ "28P02", // pgdelta: alias reserved here to future-proof against new auth codes
108
+ ]);
109
+ // Non-retryable TLS/SSL markers. The `pg` driver surfaces TLS failures as
110
+ // either plain Node `Error` instances with a code on `ERR_TLS_*` or error
111
+ // messages that include well-known cert/TLS terminology; we match both
112
+ // because node-pg normalises some of these.
113
+ const TLS_MESSAGE_MARKERS = [
114
+ "self-signed certificate",
115
+ "self signed certificate",
116
+ "unable to verify the first certificate",
117
+ "certificate has expired",
118
+ "tls",
119
+ "ssl",
120
+ ];
121
+ /**
122
+ * Return true when `err` represents a transient connect failure that makes
123
+ * sense to retry with backoff (e.g. refused connections, DNS blips, our own
124
+ * eager-connect timeout wrapper). Returns false for permanent failures such
125
+ * as authentication errors, TLS negotiation errors, and `ENOTFOUND`.
126
+ *
127
+ * Unknown errors are treated as retryable on purpose: transient-by-default
128
+ * is safer here because a duplicated retry is strictly cheaper than a spurious
129
+ * hard failure during catalog extraction.
130
+ */
131
+ export function isRetryableConnectError(err) {
132
+ if (!(err instanceof Error))
133
+ return true;
134
+ const code = err.code;
135
+ if (code && NON_RETRYABLE_PG_CODES.has(code))
136
+ return false;
137
+ if (code === "ENOTFOUND")
138
+ return false;
139
+ if (code && typeof code === "string" && code.startsWith("ERR_TLS")) {
140
+ return false;
141
+ }
142
+ const message = err.message?.toLowerCase() ?? "";
143
+ // Our own eager-connect timeout wrapper is retryable (flaky network).
144
+ if (message.includes("timed out after"))
145
+ return true;
146
+ for (const marker of TLS_MESSAGE_MARKERS) {
147
+ if (message.includes(marker))
148
+ return false;
149
+ }
150
+ return true;
151
+ }
152
+ /**
153
+ * Retry an async `connect` operation with bounded exponential backoff.
154
+ * Stops immediately on a non-retryable error. On exhausted attempts, throws
155
+ * the last observed error.
156
+ *
157
+ * Exposed for testing — production call sites always go through
158
+ * {@link createManagedPool}.
159
+ */
160
+ export async function connectWithRetry(opts) {
161
+ const maxAttempts = opts.maxAttempts ?? DEFAULT_CONNECT_MAX_ATTEMPTS;
162
+ const baseBackoffMs = opts.baseBackoffMs ?? DEFAULT_CONNECT_BASE_BACKOFF_MS;
163
+ const maxBackoffMs = opts.maxBackoffMs ?? DEFAULT_CONNECT_MAX_BACKOFF_MS;
164
+ const isRetryable = opts.isRetryable ?? isRetryableConnectError;
165
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
166
+ let lastError;
167
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
168
+ try {
169
+ return await opts.connect(attempt);
170
+ }
171
+ catch (err) {
172
+ lastError = err;
173
+ if (attempt >= maxAttempts || !isRetryable(err)) {
174
+ throw err;
175
+ }
176
+ const backoff = Math.min(baseBackoffMs * 2 ** (attempt - 1), maxBackoffMs);
177
+ await sleep(backoff);
178
+ }
179
+ }
180
+ // Unreachable: loop either returns or throws.
181
+ throw lastError;
182
+ }
99
183
  /**
100
184
  * Create a Pool with custom type handlers and optional event listeners.
101
185
  */
@@ -180,7 +264,11 @@ export function createPool(connectionString, options) {
180
264
  * to close (via {@link endPool}).
181
265
  */
182
266
  export async function createManagedPool(url, options) {
183
- const sslConfig = await parseSslConfig(url, options?.label ?? "target");
267
+ // Normalize percent-encoded IPv6 hosts (e.g. `2406%3A...%3Ab3c9`) into the
268
+ // canonical bracketed form before the URL reaches `parseSslConfig` or pg.
269
+ // Non-IPv6 hosts are returned unchanged.
270
+ const normalizedUrl = normalizeConnectionUrl(url);
271
+ const sslConfig = await parseSslConfig(normalizedUrl, options?.label ?? "target");
184
272
  const pool = createPool(sslConfig.cleanedUrl, {
185
273
  ...(sslConfig.ssl !== undefined ? { ssl: sslConfig.ssl } : {}),
186
274
  onError: (err) => {
@@ -197,15 +285,19 @@ export async function createManagedPool(url, options) {
197
285
  });
198
286
  // Eagerly validate connectivity so SSL/auth failures surface immediately
199
287
  // instead of hanging on the first real query. node-pg's connectionTimeoutMillis
200
- // is not reliably enforced under Bun when SSL negotiation hangs.
288
+ // is not reliably enforced under Bun when SSL negotiation hangs. Transient
289
+ // failures (refused connections, flaky DNS, our own timeout wrapper) are
290
+ // retried with bounded exponential backoff; auth/TLS/ENOTFOUND fail fast.
201
291
  const label = options?.label ?? "target";
202
292
  const timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS;
203
293
  try {
204
- const client = await Promise.race([
205
- pool.connect(),
206
- new Promise((_, reject) => setTimeout(() => reject(new Error(`Connection to ${label} database timed out after ${timeoutMs}ms. ` +
207
- `The server may require SSL, use an invalid certificate, or be unreachable.`)), timeoutMs)),
208
- ]);
294
+ const client = await connectWithRetry({
295
+ connect: () => Promise.race([
296
+ pool.connect(),
297
+ new Promise((_, reject) => setTimeout(() => reject(new Error(`Connection to ${label} database timed out after ${timeoutMs}ms. ` +
298
+ `The server may require SSL, use an invalid certificate, or be unreachable.`)), timeoutMs)),
299
+ ]),
300
+ });
209
301
  client.release();
210
302
  }
211
303
  catch (err) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supabase/pg-delta",
3
- "version": "1.0.0-alpha.13",
3
+ "version": "1.0.0-alpha.15",
4
4
  "description": "PostgreSQL migrations made easy",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -72,6 +72,7 @@
72
72
  "format-and-lint": "biome check . --error-on-warnings",
73
73
  "knip": "knip",
74
74
  "pgdelta": "bun src/cli/bin/cli.ts",
75
+ "sync-base-images": "bun scripts/sync-supabase-base-images.ts",
75
76
  "test": "bun scripts/run-tests.ts",
76
77
  "test:unit": "bun run test src/",
77
78
  "test:integration": "bun run test tests/",
@@ -1,6 +1,7 @@
1
1
  import debug from "debug";
2
2
  import type { Catalog } from "./catalog.model.ts";
3
3
  import { expandReplaceDependencies } from "./expand-replace-dependencies.ts";
4
+ import { normalizePostDiffCycles } from "./post-diff-cycle-breaking.ts";
4
5
 
5
6
  const debugCatalog = debug("pg-delta:catalog");
6
7
 
@@ -232,11 +233,16 @@ export function diffCatalogs(
232
233
  return true;
233
234
  });
234
235
 
235
- filteredChanges = expandReplaceDependencies({
236
+ const expandedDependencies = expandReplaceDependencies({
236
237
  changes: filteredChanges,
237
238
  mainCatalog: main,
238
239
  branchCatalog: branch,
239
240
  });
241
+ filteredChanges = normalizePostDiffCycles({
242
+ changes: expandedDependencies.changes,
243
+ mainCatalog: main,
244
+ replacedTableIds: expandedDependencies.replacedTableIds,
245
+ });
240
246
 
241
247
  debugCatalog(
242
248
  "changes catalog diff: %O",
@@ -0,0 +1,142 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { isIPv6, normalizeConnectionUrl } from "./connection-url.ts";
3
+
4
+ describe("isIPv6", () => {
5
+ describe("accepted", () => {
6
+ const accepted = [
7
+ "::",
8
+ "::1",
9
+ "1::",
10
+ "1:2:3:4:5:6:7:8",
11
+ "2406:da18:243:740f:abda:9a5c:a92d:b3c9",
12
+ "::ffff:192.0.2.1",
13
+ "fe80::AbCd",
14
+ "fe80::1%eth0",
15
+ ];
16
+ for (const value of accepted) {
17
+ test(`accepts "${value}"`, () => {
18
+ expect(isIPv6(value)).toBe(true);
19
+ });
20
+ }
21
+ });
22
+
23
+ describe("rejected", () => {
24
+ const rejected = [
25
+ "",
26
+ "2406:da18:243:740f", // only 4 groups
27
+ "1:2:3:4:5:6:7:8:9", // 9 groups
28
+ "1::2::3", // double compression
29
+ "gggg::1", // invalid hex
30
+ "1.2.3.4", // pure IPv4
31
+ "[::1]", // bracketed
32
+ "localhost",
33
+ "example.com",
34
+ ":::", // malformed
35
+ ];
36
+ for (const value of rejected) {
37
+ test(`rejects ${JSON.stringify(value)}`, () => {
38
+ expect(isIPv6(value)).toBe(false);
39
+ });
40
+ }
41
+ });
42
+ });
43
+
44
+ describe("normalizeConnectionUrl", () => {
45
+ describe("normalizes percent-encoded IPv6 hosts", () => {
46
+ test("full 8-group IPv6 becomes bracketed", () => {
47
+ const input =
48
+ "postgresql://user:pass@2406%3Ada18%3A243%3A740f%3Aabda%3A9a5c%3Aa92d%3Ab3c9:5432/db";
49
+ expect(normalizeConnectionUrl(input)).toBe(
50
+ "postgresql://user:pass@[2406:da18:243:740f:abda:9a5c:a92d:b3c9]:5432/db",
51
+ );
52
+ });
53
+
54
+ test("compressed ::1 form", () => {
55
+ const input = "postgresql://user:pass@%3A%3A1:5432/db";
56
+ expect(normalizeConnectionUrl(input)).toBe(
57
+ "postgresql://user:pass@[::1]:5432/db",
58
+ );
59
+ });
60
+
61
+ test("IPv4-mapped ::ffff:192.0.2.1", () => {
62
+ const input = "postgresql://user:pass@%3A%3Affff%3A192.0.2.1:5432/db";
63
+ expect(normalizeConnectionUrl(input)).toBe(
64
+ "postgresql://user:pass@[::ffff:192.0.2.1]:5432/db",
65
+ );
66
+ });
67
+
68
+ test("mixed-case percent triples (%3a and %3A)", () => {
69
+ const input =
70
+ "postgresql://user:pass@2406%3ada18%3A243%3a740f%3Aabda%3A9a5c%3Aa92d%3Ab3c9:5432/db";
71
+ expect(normalizeConnectionUrl(input)).toBe(
72
+ "postgresql://user:pass@[2406:da18:243:740f:abda:9a5c:a92d:b3c9]:5432/db",
73
+ );
74
+ });
75
+
76
+ test("preserves URL-encoded password and query string", () => {
77
+ const input =
78
+ "postgresql://user:p%40ss%2Fword@%3A%3A1:5432/db?sslmode=require&application_name=pgdelta";
79
+ expect(normalizeConnectionUrl(input)).toBe(
80
+ "postgresql://user:p%40ss%2Fword@[::1]:5432/db?sslmode=require&application_name=pgdelta",
81
+ );
82
+ });
83
+
84
+ test("preserves fragment", () => {
85
+ const input = "postgresql://user:pass@%3A%3A1:5432/db#frag";
86
+ expect(normalizeConnectionUrl(input)).toBe(
87
+ "postgresql://user:pass@[::1]:5432/db#frag",
88
+ );
89
+ });
90
+
91
+ test("works without a port", () => {
92
+ const input = "postgresql://user:pass@%3A%3A1/db";
93
+ expect(normalizeConnectionUrl(input)).toBe(
94
+ "postgresql://user:pass@[::1]/db",
95
+ );
96
+ });
97
+
98
+ test("works without userinfo", () => {
99
+ const input = "postgresql://%3A%3A1:5432/db";
100
+ expect(normalizeConnectionUrl(input)).toBe("postgresql://[::1]:5432/db");
101
+ });
102
+
103
+ test("works with username only (no password)", () => {
104
+ const input = "postgresql://user@%3A%3A1:5432/db";
105
+ expect(normalizeConnectionUrl(input)).toBe(
106
+ "postgresql://user@[::1]:5432/db",
107
+ );
108
+ });
109
+ });
110
+
111
+ describe("leaves URL unchanged (guardrail)", () => {
112
+ test("already-bracketed IPv6", () => {
113
+ const input = "postgresql://user:pass@[::1]:5432/db";
114
+ expect(normalizeConnectionUrl(input)).toBe(input);
115
+ });
116
+
117
+ test("IPv4 host", () => {
118
+ const input = "postgresql://user:pass@127.0.0.1:5432/db";
119
+ expect(normalizeConnectionUrl(input)).toBe(input);
120
+ });
121
+
122
+ test("DNS hostname", () => {
123
+ const input = "postgresql://user:pass@db.example.com:5432/db";
124
+ expect(normalizeConnectionUrl(input)).toBe(input);
125
+ });
126
+
127
+ test("percent-encoded colons that do not decode to a valid IPv6 (4 groups only)", () => {
128
+ const input = "postgresql://user:pass@2406%3Ada18%3A243%3A740f:5432/db";
129
+ expect(normalizeConnectionUrl(input)).toBe(input);
130
+ });
131
+
132
+ test("non-colon percent-encoded character in hostname", () => {
133
+ const input = "postgresql://user:pass@host%2Dname:5432/db";
134
+ expect(normalizeConnectionUrl(input)).toBe(input);
135
+ });
136
+
137
+ test("garbage host `%3A%3Azzz` decodes to `::zzz`, not valid IPv6", () => {
138
+ const input = "postgresql://user:pass@%3A%3Azzz:5432/db";
139
+ expect(normalizeConnectionUrl(input)).toBe(input);
140
+ });
141
+ });
142
+ });
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Connection URL normalization for pg-delta.
3
+ *
4
+ * Auto-normalizes percent-encoded IPv6 hosts in PostgreSQL connection URLs.
5
+ * A URL like `postgresql://user:pass@2406%3Ada18%3A...%3Ab3c9:5432/db`
6
+ * becomes `postgresql://user:pass@[2406:da18:...:b3c9]:5432/db` before it
7
+ * reaches `pg-connection-string` / `pg.Pool`, so DNS resolution sees the
8
+ * address in its canonical bracketed form.
9
+ *
10
+ * Non-IPv6 hosts (IPv4, DNS names, already-bracketed IPv6, partial fragments
11
+ * that just happen to contain `%3A`) are returned verbatim.
12
+ */
13
+
14
+ // IPv6 detection regex vendored from ip-regex (Sindre Sorhus, MIT).
15
+ // https://github.com/sindresorhus/ip-regex
16
+ const v4 =
17
+ "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}";
18
+ const v6seg = "[a-fA-F\\d]{1,4}";
19
+ const v6 = `
20
+ (?:
21
+ (?:${v6seg}:){7}(?:${v6seg}|:)|
22
+ (?:${v6seg}:){6}(?:${v4}|:${v6seg}|:)|
23
+ (?:${v6seg}:){5}(?::${v4}|(?::${v6seg}){1,2}|:)|
24
+ (?:${v6seg}:){4}(?:(?::${v6seg}){0,1}:${v4}|(?::${v6seg}){1,3}|:)|
25
+ (?:${v6seg}:){3}(?:(?::${v6seg}){0,2}:${v4}|(?::${v6seg}){1,4}|:)|
26
+ (?:${v6seg}:){2}(?:(?::${v6seg}){0,3}:${v4}|(?::${v6seg}){1,5}|:)|
27
+ (?:${v6seg}:){1}(?:(?::${v6seg}){0,4}:${v4}|(?::${v6seg}){1,6}|:)|
28
+ (?::(?:(?::${v6seg}){0,5}:${v4}|(?::${v6seg}){1,7}|:))
29
+ )(?:%[0-9a-zA-Z]{1,})?
30
+ `
31
+ .replace(/\s*\/\/.*$/gm, "")
32
+ .replace(/\n/g, "")
33
+ .trim();
34
+
35
+ const V6_EXACT = new RegExp(`^${v6}$`);
36
+
37
+ /**
38
+ * Return true if `value` is a valid IPv6 literal in any canonical form:
39
+ * full 8-group, `::` compression, or IPv4-mapped (`::ffff:1.2.3.4`).
40
+ * RFC 4007 zone identifiers (`fe80::1%eth0`) are accepted.
41
+ */
42
+ export function isIPv6(value: string): boolean {
43
+ return typeof value === "string" && V6_EXACT.test(value);
44
+ }
45
+
46
+ /**
47
+ * Normalize a PostgreSQL connection URL so IPv6 hosts reach pg in the
48
+ * canonical bracketed form.
49
+ *
50
+ * If the URL's hostname contains a percent-encoded colon AND the decoded
51
+ * hostname is a valid IPv6 literal, the hostname is decoded and wrapped in
52
+ * `[...]`. All other fields (scheme, userinfo, port, path, query, fragment)
53
+ * are preserved byte-for-byte from the input.
54
+ *
55
+ * Any URL whose decoded hostname does not validate as IPv6 is returned
56
+ * verbatim, so a malformed input will surface its usual downstream error
57
+ * instead of being silently rewritten.
58
+ */
59
+ export function normalizeConnectionUrl(url: string): string {
60
+ const urlObj = new URL(url);
61
+ // Cheap pre-filter: only look closer if the hostname contains a
62
+ // percent-encoded colon. Anything else is left entirely untouched.
63
+ if (!/%3[aA]/.test(urlObj.hostname)) return url;
64
+
65
+ const decodedHost = decodeURIComponent(urlObj.hostname);
66
+ // Authoritative validation: only normalize when the decoded string is a
67
+ // real IPv6 literal. Rejects partial fragments, random hostnames that
68
+ // happen to contain `%3A`, and any malformed input.
69
+ if (!isIPv6(decodedHost)) return url;
70
+
71
+ // Preserve username/password/port/path/search/hash exactly as they appear
72
+ // in the WHATWG URL model (these are returned already percent-encoded).
73
+ const scheme = `${urlObj.protocol}//`;
74
+ const auth = urlObj.username
75
+ ? urlObj.password
76
+ ? `${urlObj.username}:${urlObj.password}@`
77
+ : `${urlObj.username}@`
78
+ : "";
79
+ const port = urlObj.port ? `:${urlObj.port}` : "";
80
+ const tail = `${urlObj.pathname}${urlObj.search}${urlObj.hash}`;
81
+ return `${scheme}${auth}[${decodedHost}]${port}${tail}`;
82
+ }