@rebasepro/server-postgres 0.0.1-canary.4829d6e

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 (121) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +86 -0
  3. package/dist/PostgresAdapter.d.ts +6 -0
  4. package/dist/PostgresBackendDriver.d.ts +150 -0
  5. package/dist/PostgresBootstrapper.d.ts +51 -0
  6. package/dist/auth/ensure-tables.d.ts +10 -0
  7. package/dist/auth/services.d.ts +250 -0
  8. package/dist/backup/backup-cli.d.ts +3 -0
  9. package/dist/backup/backup-cron.d.ts +53 -0
  10. package/dist/backup/backup-service.d.ts +85 -0
  11. package/dist/backup/index.d.ts +12 -0
  12. package/dist/backup/pg-tools.d.ts +110 -0
  13. package/dist/backup/retention.d.ts +35 -0
  14. package/dist/chunk-DSJWtz9O.js +40 -0
  15. package/dist/cli-errors.d.ts +42 -0
  16. package/dist/cli-helpers.d.ts +7 -0
  17. package/dist/cli.d.ts +1 -0
  18. package/dist/collections/PostgresCollectionRegistry.d.ts +47 -0
  19. package/dist/connection.d.ts +65 -0
  20. package/dist/data-transformer.d.ts +55 -0
  21. package/dist/databasePoolManager.d.ts +20 -0
  22. package/dist/history/HistoryService.d.ts +71 -0
  23. package/dist/history/ensure-history-table.d.ts +7 -0
  24. package/dist/index.d.ts +15 -0
  25. package/dist/index.es.js +23535 -0
  26. package/dist/index.es.js.map +1 -0
  27. package/dist/interfaces.d.ts +18 -0
  28. package/dist/schema/auth-bootstrap-sql.d.ts +24 -0
  29. package/dist/schema/auth-default-policies.d.ts +10 -0
  30. package/dist/schema/auth-schema.d.ts +2376 -0
  31. package/dist/schema/doctor-cli.d.ts +2 -0
  32. package/dist/schema/doctor.d.ts +58 -0
  33. package/dist/schema/dynamic-tables.d.ts +31 -0
  34. package/dist/schema/generate-drizzle-schema-logic.d.ts +2 -0
  35. package/dist/schema/generate-drizzle-schema.d.ts +1 -0
  36. package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -0
  37. package/dist/schema/generate-postgres-ddl.d.ts +1 -0
  38. package/dist/schema/introspect-db-inference.d.ts +5 -0
  39. package/dist/schema/introspect-db-logic.d.ts +118 -0
  40. package/dist/schema/introspect-db.d.ts +1 -0
  41. package/dist/schema/introspect-runtime.d.ts +57 -0
  42. package/dist/schema/test-schema.d.ts +24 -0
  43. package/dist/security/policy-drift.d.ts +57 -0
  44. package/dist/security/rls-enforcement.d.ts +122 -0
  45. package/dist/services/BranchService.d.ts +47 -0
  46. package/dist/services/FetchService.d.ts +214 -0
  47. package/dist/services/PersistService.d.ts +39 -0
  48. package/dist/services/RelationService.d.ts +109 -0
  49. package/dist/services/cdc/CdcListener.d.ts +54 -0
  50. package/dist/services/cdc/trigger-cdc.d.ts +64 -0
  51. package/dist/services/collection-helpers.d.ts +38 -0
  52. package/dist/services/dataService.d.ts +110 -0
  53. package/dist/services/index.d.ts +4 -0
  54. package/dist/services/realtimeService.d.ts +298 -0
  55. package/dist/src-Eh-CZosp.js +595 -0
  56. package/dist/src-Eh-CZosp.js.map +1 -0
  57. package/dist/types.d.ts +3 -0
  58. package/dist/utils/drizzle-conditions.d.ts +138 -0
  59. package/dist/utils/pg-array-null-patch.d.ts +16 -0
  60. package/dist/utils/pg-error-utils.d.ts +65 -0
  61. package/dist/utils/table-classification.d.ts +8 -0
  62. package/dist/websocket.d.ts +18 -0
  63. package/package.json +113 -0
  64. package/src/PostgresAdapter.ts +58 -0
  65. package/src/PostgresBackendDriver.ts +1387 -0
  66. package/src/PostgresBootstrapper.ts +581 -0
  67. package/src/auth/ensure-tables.ts +367 -0
  68. package/src/auth/services.ts +1321 -0
  69. package/src/backup/backup-cli.ts +383 -0
  70. package/src/backup/backup-cron.ts +189 -0
  71. package/src/backup/backup-service.ts +299 -0
  72. package/src/backup/index.ts +12 -0
  73. package/src/backup/pg-tools.ts +231 -0
  74. package/src/backup/retention.ts +75 -0
  75. package/src/cli-errors.ts +265 -0
  76. package/src/cli-helpers.ts +196 -0
  77. package/src/cli.ts +786 -0
  78. package/src/collections/PostgresCollectionRegistry.ts +103 -0
  79. package/src/connection.ts +166 -0
  80. package/src/data-transformer.ts +733 -0
  81. package/src/databasePoolManager.ts +87 -0
  82. package/src/history/HistoryService.ts +272 -0
  83. package/src/history/ensure-history-table.ts +46 -0
  84. package/src/index.ts +15 -0
  85. package/src/interfaces.ts +60 -0
  86. package/src/schema/auth-bootstrap-sql.ts +41 -0
  87. package/src/schema/auth-default-policies.ts +125 -0
  88. package/src/schema/auth-schema.ts +233 -0
  89. package/src/schema/doctor-cli.ts +113 -0
  90. package/src/schema/doctor.ts +733 -0
  91. package/src/schema/dynamic-tables.test.ts +302 -0
  92. package/src/schema/dynamic-tables.ts +293 -0
  93. package/src/schema/generate-drizzle-schema-logic.ts +850 -0
  94. package/src/schema/generate-drizzle-schema.ts +131 -0
  95. package/src/schema/generate-postgres-ddl-logic.ts +490 -0
  96. package/src/schema/generate-postgres-ddl.ts +92 -0
  97. package/src/schema/introspect-db-inference.ts +238 -0
  98. package/src/schema/introspect-db-logic.ts +910 -0
  99. package/src/schema/introspect-db.ts +266 -0
  100. package/src/schema/introspect-runtime.test.ts +212 -0
  101. package/src/schema/introspect-runtime.ts +293 -0
  102. package/src/schema/test-schema.ts +11 -0
  103. package/src/security/policy-drift.test.ts +122 -0
  104. package/src/security/policy-drift.ts +159 -0
  105. package/src/security/rls-enforcement.ts +295 -0
  106. package/src/services/BranchService.ts +251 -0
  107. package/src/services/FetchService.ts +1661 -0
  108. package/src/services/PersistService.ts +329 -0
  109. package/src/services/RelationService.ts +1306 -0
  110. package/src/services/cdc/CdcListener.ts +167 -0
  111. package/src/services/cdc/trigger-cdc.ts +169 -0
  112. package/src/services/collection-helpers.ts +151 -0
  113. package/src/services/dataService.ts +246 -0
  114. package/src/services/index.ts +13 -0
  115. package/src/services/realtimeService.ts +1502 -0
  116. package/src/types.ts +4 -0
  117. package/src/utils/drizzle-conditions.ts +1162 -0
  118. package/src/utils/pg-array-null-patch.ts +42 -0
  119. package/src/utils/pg-error-utils.ts +227 -0
  120. package/src/utils/table-classification.ts +16 -0
  121. package/src/websocket.ts +640 -0
@@ -0,0 +1,265 @@
1
+ import chalk from "chalk";
2
+ import { logger } from "@rebasepro/server";
3
+
4
+ /**
5
+ * Detect whether an error (or AggregateError wrapping multiple attempts)
6
+ * represents an ECONNREFUSED — i.e. the database is simply not running.
7
+ *
8
+ * Handles:
9
+ * - Direct `{ code: "ECONNREFUSED" }` errors from Node `net`
10
+ * - `AggregateError` from dual-stack IPv4+IPv6 connection attempts
11
+ * - Drizzle's `cause`-wrapped pg errors
12
+ */
13
+ export function isEconnrefused(err: unknown): boolean {
14
+ if (!err || typeof err !== "object") return false;
15
+ const e = err as { code?: string; cause?: unknown; errors?: unknown[] };
16
+ if (e.code === "ECONNREFUSED") return true;
17
+ // AggregateError from Node net (dual-stack IPv4 + IPv6)
18
+ if (Array.isArray(e.errors)) {
19
+ return e.errors.some(inner =>
20
+ inner && typeof inner === "object" && (inner as { code?: string }).code === "ECONNREFUSED"
21
+ );
22
+ }
23
+ // Drizzle wraps the pg error in `cause`
24
+ if (e.cause && typeof e.cause === "object") {
25
+ return isEconnrefused(e.cause);
26
+ }
27
+ return false;
28
+ }
29
+
30
+ /**
31
+ * Detect PostgreSQL authentication failures.
32
+ * PG error codes: 28P01 (invalid_password), 28000 (invalid_authorization_specification)
33
+ */
34
+ export function isAuthFailure(err: unknown): boolean {
35
+ if (!err || typeof err !== "object") return false;
36
+ const e = err as { code?: string; cause?: unknown };
37
+ if (e.code === "28P01" || e.code === "28000") return true;
38
+ if (e.cause && typeof e.cause === "object") {
39
+ return isAuthFailure(e.cause);
40
+ }
41
+ // Also check the message for common pg auth failure text
42
+ if ("message" in e && typeof (e as { message?: string }).message === "string") {
43
+ const msg = (e as { message: string }).message.toLowerCase();
44
+ if (msg.includes("password authentication failed") || msg.includes("no pg_hba.conf entry")) {
45
+ return true;
46
+ }
47
+ }
48
+ return false;
49
+ }
50
+
51
+ /**
52
+ * Detect the "SSL is not enabled on the server" failure — the client attempted
53
+ * an SSL handshake against a Postgres server that doesn't support it (common
54
+ * with a plain local dev database). The fix is `?sslmode=disable` on the URL.
55
+ */
56
+ export function isSslNotEnabled(err: unknown): boolean {
57
+ if (!err || typeof err !== "object") return false;
58
+ const e = err as { message?: string; cause?: unknown };
59
+ if (typeof e.message === "string" && e.message.toLowerCase().includes("ssl is not enabled on the server")) {
60
+ return true;
61
+ }
62
+ if (e.cause && typeof e.cause === "object") {
63
+ return isSslNotEnabled(e.cause);
64
+ }
65
+ return false;
66
+ }
67
+
68
+ /**
69
+ * Detect PostgreSQL "cannot drop ... because other objects depend on it"
70
+ * (error code 2BP01, dependent_objects_still_exist). This is the failure that
71
+ * strands a declarative `db push` half-applied when a collection is removed but
72
+ * an enum type it defined is still referenced by another object.
73
+ */
74
+ export function isDependencyDropError(err: unknown): boolean {
75
+ if (!err || typeof err !== "object") return false;
76
+ const e = err as { code?: string; message?: string; cause?: unknown };
77
+ if (e.code === "2BP01") return true;
78
+ if (typeof e.message === "string") {
79
+ const msg = e.message.toLowerCase();
80
+ if (msg.includes("other objects depend on it") || msg.includes("cannot drop type")) {
81
+ return true;
82
+ }
83
+ }
84
+ if (e.cause && typeof e.cause === "object") {
85
+ return isDependencyDropError(e.cause);
86
+ }
87
+ return false;
88
+ }
89
+
90
+ /**
91
+ * Parse host:port from a DATABASE_URL for display purposes.
92
+ */
93
+ function parseHostInfo(databaseUrl: string): string {
94
+ try {
95
+ const parsed = new URL(databaseUrl);
96
+ return `${parsed.hostname}:${parsed.port || 5432}`;
97
+ } catch {
98
+ return "unknown";
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Format a diagnostic banner for ECONNREFUSED errors.
104
+ */
105
+ function formatConnectionRefusedBanner(databaseUrl: string): string {
106
+ const hostInfo = parseHostInfo(databaseUrl);
107
+ return (
108
+ `\n` +
109
+ `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n` +
110
+ ` ❌ Cannot connect to PostgreSQL at ${hostInfo}\n` +
111
+ `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n` +
112
+ `\n` +
113
+ ` The database server is not running or is not accepting\n` +
114
+ ` connections. Common fixes:\n` +
115
+ `\n` +
116
+ ` • brew services start postgresql@18\n` +
117
+ ` • docker compose up -d postgres\n` +
118
+ ` • Verify DATABASE_URL in your .env file\n` +
119
+ `\n` +
120
+ `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`
121
+ );
122
+ }
123
+
124
+ /**
125
+ * Format a diagnostic banner for authentication failures.
126
+ */
127
+ function formatAuthFailureBanner(databaseUrl: string): string {
128
+ const hostInfo = parseHostInfo(databaseUrl);
129
+ let username = "unknown";
130
+ try {
131
+ username = new URL(databaseUrl).username || "unknown";
132
+ } catch { /* ignore */ }
133
+
134
+ return (
135
+ `\n` +
136
+ `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n` +
137
+ ` ❌ Authentication failed for user "${username}" at ${hostInfo}\n` +
138
+ `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n` +
139
+ `\n` +
140
+ ` PostgreSQL rejected the credentials. Common fixes:\n` +
141
+ `\n` +
142
+ ` • Check the username and password in DATABASE_URL\n` +
143
+ ` • Verify the user exists: psql -c "\\du"\n` +
144
+ ` • Reset the password: ALTER USER ${username} PASSWORD 'new_password';\n` +
145
+ `\n` +
146
+ `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`
147
+ );
148
+ }
149
+
150
+ /**
151
+ * Format a diagnostic banner for "SSL is not enabled on the server".
152
+ */
153
+ function formatSslNotEnabledBanner(databaseUrl: string): string {
154
+ const hostInfo = parseHostInfo(databaseUrl);
155
+ const suggestion = databaseUrl.includes("?") ? "&sslmode=disable" : "?sslmode=disable";
156
+ return (
157
+ `\n` +
158
+ `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n` +
159
+ ` ❌ SSL is not enabled on the PostgreSQL server at ${hostInfo}\n` +
160
+ `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n` +
161
+ `\n` +
162
+ ` The client tried to connect over SSL, but the server does not\n` +
163
+ ` support it. This is normal for a plain local dev database.\n` +
164
+ `\n` +
165
+ ` Fix: append ${chalk.bold("sslmode=disable")} to DATABASE_URL, e.g.\n` +
166
+ `\n` +
167
+ ` DATABASE_URL=...${suggestion}\n` +
168
+ `\n` +
169
+ `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`
170
+ );
171
+ }
172
+
173
+ /**
174
+ * Format a diagnostic banner for a dependency-drop failure during `db push`.
175
+ * Explains that the database may be left partially migrated and how to recover.
176
+ */
177
+ function formatDependencyDropBanner(): string {
178
+ return (
179
+ `\n` +
180
+ `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n` +
181
+ ` ❌ Schema push failed: a type/table could not be dropped\n` +
182
+ ` because other objects still depend on it.\n` +
183
+ `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n` +
184
+ `\n` +
185
+ ` ${chalk.yellow("The database may now be partially migrated.")} Atlas applies\n` +
186
+ ` statements individually, so earlier changes in this push may\n` +
187
+ ` already be committed while later ones failed.\n` +
188
+ `\n` +
189
+ ` This commonly happens when a collection is removed but an enum\n` +
190
+ ` type it defined is still referenced. To recover:\n` +
191
+ `\n` +
192
+ ` 1. Inspect the leftover object named in the error above.\n` +
193
+ ` 2. Drop it with CASCADE, e.g.:\n` +
194
+ ` psql "$DATABASE_URL" -c 'DROP TYPE "<name>" CASCADE;'\n` +
195
+ ` 3. Re-run: ${chalk.bold.green("rebase db push")}\n` +
196
+ `\n` +
197
+ ` Prefer a safe, versioned workflow? Use ${chalk.bold("rebase db generate")}\n` +
198
+ ` + ${chalk.bold("rebase db migrate")} instead of push for destructive changes.\n` +
199
+ `\n` +
200
+ `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`
201
+ );
202
+ }
203
+
204
+ /**
205
+ * Pre-flight check: verify that the database is reachable before running
206
+ * a heavy subprocess (Atlas, migrations, etc.).
207
+ *
208
+ * Exits with code 1 and a friendly banner on known failure modes.
209
+ * On unknown errors, logs a warning and allows the caller to proceed.
210
+ */
211
+ export async function checkDatabaseConnectivity(databaseUrl: string): Promise<void> {
212
+ let client: import("pg").Client | undefined;
213
+ try {
214
+ const { Client } = await import("pg");
215
+ client = new Client({
216
+ connectionString: databaseUrl,
217
+ connectionTimeoutMillis: 5000
218
+ });
219
+ await client.connect();
220
+ await client.query("SELECT 1");
221
+ } catch (err: unknown) {
222
+ if (isEconnrefused(err)) {
223
+ logger.error(formatConnectionRefusedBanner(databaseUrl));
224
+ process.exit(1);
225
+ }
226
+ if (isAuthFailure(err)) {
227
+ logger.error(formatAuthFailureBanner(databaseUrl));
228
+ process.exit(1);
229
+ }
230
+ if (isSslNotEnabled(err)) {
231
+ logger.error(formatSslNotEnabledBanner(databaseUrl));
232
+ process.exit(1);
233
+ }
234
+ // Unknown error — warn but don't block; let the downstream tool surface details
235
+ logger.warn(chalk.yellow(` ⚠ Could not verify database connectivity: ${err instanceof Error ? err.message : String(err)}`));
236
+ logger.warn(chalk.gray(" Proceeding anyway — the command may fail if the database is unreachable."));
237
+ } finally {
238
+ try {
239
+ await client?.end();
240
+ } catch {
241
+ // ignore cleanup errors
242
+ }
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Post-hoc error diagnosis for direct database operations (e.g. applyPolicies).
248
+ * Returns a formatted diagnostic string if the error matches a known pattern,
249
+ * or null if unrecognized.
250
+ */
251
+ export function diagnoseDbError(err: unknown, databaseUrl?: string): string | null {
252
+ if (isEconnrefused(err)) {
253
+ return formatConnectionRefusedBanner(databaseUrl || "");
254
+ }
255
+ if (isAuthFailure(err)) {
256
+ return formatAuthFailureBanner(databaseUrl || "");
257
+ }
258
+ if (isSslNotEnabled(err)) {
259
+ return formatSslNotEnabledBanner(databaseUrl || "");
260
+ }
261
+ if (isDependencyDropError(err)) {
262
+ return formatDependencyDropBanner();
263
+ }
264
+ return null;
265
+ }
@@ -0,0 +1,196 @@
1
+ import path from "path";
2
+ import fs from "fs";
3
+ import { execSync } from "child_process";
4
+ import { fileURLToPath, pathToFileURL } from "url";
5
+ import chalk from "chalk";
6
+ import { logger } from "@rebasepro/server";
7
+ import type { CollectionConfig, Relation } from "@rebasepro/types";
8
+
9
+ const getHelpersDirname = () => {
10
+ try {
11
+ return eval("__dirname");
12
+ } catch {
13
+ const err = new Error();
14
+ const stackLine = err.stack?.split("\n")[1] || "";
15
+ const match = stackLine.match(/\((.*?):\d+:\d+\)/) || stackLine.match(/at (.*?):\d+:\d+/);
16
+ if (match && match[1]) {
17
+ let cleanPath = match[1];
18
+ if (cleanPath.startsWith("file://")) {
19
+ cleanPath = fileURLToPath(cleanPath);
20
+ }
21
+ return path.dirname(cleanPath);
22
+ }
23
+ return process.cwd();
24
+ }
25
+ };
26
+ const __helpersDirname = getHelpersDirname();
27
+
28
+
29
+
30
+ export function resolveLocalBin(binName: string): string | null {
31
+ // Try to find node_modules/.bin upwards from __helpersDirname first (package-relative)
32
+ let dir = __helpersDirname;
33
+ while (true) {
34
+ const candidate = path.join(dir, "node_modules", ".bin", binName);
35
+ if (fs.existsSync(candidate)) return candidate;
36
+ const parent = path.dirname(dir);
37
+ if (parent === dir) break;
38
+ dir = parent;
39
+ }
40
+
41
+ let cwd = process.cwd();
42
+ // Try to find node_modules/.bin upwards from process.cwd()
43
+ while (true) {
44
+ const candidate = path.join(cwd, "node_modules", ".bin", binName);
45
+ if (fs.existsSync(candidate)) return candidate;
46
+ const parent = path.dirname(cwd);
47
+ if (parent === cwd) break;
48
+ cwd = parent;
49
+ }
50
+ // Fall back to globally installed binary via which/where
51
+ try {
52
+ const cmd = process.platform === "win32" ? `where ${binName}` : `which ${binName}`;
53
+ const globalPath = execSync(cmd, { encoding: "utf-8" }).trim().split("\n")[0].trim();
54
+ if (globalPath && fs.existsSync(globalPath)) return globalPath;
55
+ } catch {
56
+ // not found globally
57
+ }
58
+ return null;
59
+ }
60
+
61
+ export async function getTableIncludesFromCollections(collections: CollectionConfig[]): Promise<string[]> {
62
+ const { getTableName, resolveCollectionRelations } = await import("@rebasepro/common");
63
+ const { isPostgresCollectionConfig } = await import("@rebasepro/types");
64
+
65
+ const includes: string[] = [];
66
+ for (const col of collections) {
67
+ const tableName = getTableName(col);
68
+ const schema = isPostgresCollectionConfig(col) && col.schema ? col.schema : "public";
69
+ if (tableName) {
70
+ includes.push(`${schema}.${tableName}`);
71
+ }
72
+
73
+ const resolvedRelations = resolveCollectionRelations(col);
74
+ for (const relation of Object.values(resolvedRelations) as Relation[]) {
75
+ if (relation.through) {
76
+ const junctionTableName = relation.through.table;
77
+ const targetCollection = relation.target();
78
+ const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : "public";
79
+ includes.push(`${targetSchema}.${junctionTableName}`);
80
+ }
81
+ }
82
+ }
83
+
84
+ return Array.from(new Set(includes));
85
+ }
86
+
87
+ export async function getTableIncludes(collectionsPath: string): Promise<string[]> {
88
+ // Note: a relative --collections path resolves against the *current working
89
+ // directory*, not the backend package. When invoked via the generated npm
90
+ // script (cwd = backend/), the script uses "../config/collections" to
91
+ // compensate — so running the CLI directly from the repo root with a
92
+ // different relative path can silently point at the wrong place.
93
+ const resolvedPath = path.resolve(collectionsPath);
94
+ const collections: CollectionConfig[] = [];
95
+ if (!fs.existsSync(resolvedPath)) {
96
+ logger.warn(chalk.yellow(
97
+ ` ⚠ Collections path not found: "${collectionsPath}"\n` +
98
+ ` Resolved to: ${resolvedPath}\n` +
99
+ ` (relative to cwd: ${process.cwd()})\n` +
100
+ ` Pass an absolute path, or a path relative to where you run the command.`
101
+ ));
102
+ }
103
+ if (fs.existsSync(resolvedPath)) {
104
+ const stats = fs.statSync(resolvedPath);
105
+ if (stats.isDirectory()) {
106
+ const files = fs.readdirSync(resolvedPath);
107
+ for (const file of files) {
108
+ if ((file.endsWith(".ts") || file.endsWith(".js")) &&
109
+ !file.includes(".test.") &&
110
+ !file.endsWith(".d.ts") &&
111
+ file !== "index.ts" && file !== "index.js") {
112
+ try {
113
+ const filePath = path.join(resolvedPath, file);
114
+ const fileUrl = pathToFileURL(filePath).href;
115
+ const module = await import(fileUrl);
116
+ if (module && module.default) {
117
+ collections.push(module.default);
118
+ }
119
+ } catch {
120
+ // ignore
121
+ }
122
+ }
123
+ }
124
+ }
125
+ }
126
+
127
+ return getTableIncludesFromCollections(collections);
128
+ }
129
+
130
+ export function getDevDatabaseUrl(databaseUrl: string): string {
131
+ try {
132
+ const parsed = new URL(databaseUrl);
133
+ const dbName = parsed.pathname.slice(1);
134
+ parsed.pathname = `/${dbName}_dev_diff`;
135
+ return parsed.toString();
136
+ } catch {
137
+ return databaseUrl + "_dev_diff";
138
+ }
139
+ }
140
+
141
+ export async function ensureDevDatabaseExists(databaseUrl: string, devDatabaseUrl: string) {
142
+ try {
143
+ const { Client } = await import("pg");
144
+ const parsed = new URL(databaseUrl);
145
+ const devDbName = new URL(devDatabaseUrl).pathname.slice(1);
146
+
147
+ parsed.pathname = "/postgres";
148
+ const client = new Client({ connectionString: parsed.toString() });
149
+ await client.connect();
150
+ try {
151
+ const res = await client.query("SELECT 1 FROM pg_database WHERE datname = $1", [devDbName]);
152
+ if (res.rowCount === 0) {
153
+ await client.query(`CREATE DATABASE "${devDbName}"`);
154
+ logger.info(chalk.gray(` ✓ Created validation database "${devDbName}"`));
155
+ }
156
+ } finally {
157
+ await client.end();
158
+ }
159
+ } catch {
160
+ // Ignore, let Atlas handle connection failures
161
+ }
162
+ }
163
+
164
+ export async function getTableExcludes(databaseUrl: string, collectionsPath: string): Promise<string[]> {
165
+ const includes = await getTableIncludes(collectionsPath);
166
+ const excludes: string[] = ["atlas_schema_revisions.*", "auth.*"];
167
+
168
+ try {
169
+ const { Client } = await import("pg");
170
+ const client = new Client({ connectionString: databaseUrl });
171
+ await client.connect();
172
+ try {
173
+ const res = await client.query(`
174
+ SELECT table_schema || '.' || table_name AS full_name
175
+ FROM information_schema.tables
176
+ WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
177
+ AND table_type IN ('BASE TABLE', 'VIEW');
178
+ `);
179
+
180
+ const existingTables = res.rows.map((row: { full_name: string }) => row.full_name);
181
+
182
+ for (const table of existingTables) {
183
+ if (!includes.includes(table)) {
184
+ excludes.push(table);
185
+ }
186
+ }
187
+ } finally {
188
+ await client.end();
189
+ }
190
+ } catch (err) {
191
+ logger.warn(chalk.yellow(` ⚠️ Failed to query database for unmapped tables: ${err instanceof Error ? err.message : String(err)}`));
192
+ }
193
+
194
+ return excludes;
195
+ }
196
+