@rebasepro/server-postgres 0.19.1 → 0.19.2-canary.g08eed46
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/{BranchService-ByLfM_Tt.js → BranchService-W3DMfcZZ.js} +2 -2
- package/dist/{BranchService-ByLfM_Tt.js.map → BranchService-W3DMfcZZ.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +81 -7
- package/dist/PostgresBootstrapper.d.ts +10 -0
- package/dist/{backup-cli-oM9WQVlV.js → backup-cli-DSpQyqcG.js} +2 -2
- package/dist/{backup-cli-oM9WQVlV.js.map → backup-cli-DSpQyqcG.js.map} +1 -1
- package/dist/{backup-service-Br3tqwsy.js → backup-service-DA7a6SUV.js} +2 -2
- package/dist/{backup-service-Br3tqwsy.js.map → backup-service-DA7a6SUV.js.map} +1 -1
- package/dist/{cli-errors-DxN4yzdH.js → cli-errors-C3g_kHBw.js} +137 -18
- package/dist/cli-errors-C3g_kHBw.js.map +1 -0
- package/dist/cli-errors.d.ts +19 -0
- package/dist/cli-helpers.d.ts +47 -0
- package/dist/cli.js +233 -19
- package/dist/cli.js.map +1 -1
- package/dist/{collection-index-BHgT_TKd.js → collection-index-DdnsxiJ_.js} +14 -4
- package/dist/{collection-index-BHgT_TKd.js.map → collection-index-DdnsxiJ_.js.map} +1 -1
- package/dist/collections/validate-relations.d.ts +7 -0
- package/dist/column-plan-helpers-CpILzHJS.js +145 -0
- package/dist/column-plan-helpers-CpILzHJS.js.map +1 -0
- package/dist/{doctor-D7HWmGzs.js → doctor-D5SrGJ5P.js} +175 -61
- package/dist/doctor-D5SrGJ5P.js.map +1 -0
- package/dist/{ensure-collection-policies-2c2NV8zX.js → ensure-collection-policies-CHO0moXQ.js} +5 -5
- package/dist/{ensure-collection-policies-2c2NV8zX.js.map → ensure-collection-policies-CHO0moXQ.js.map} +1 -1
- package/dist/{ensure-collection-tables-D4wJzM4y.js → ensure-collection-tables-Bkvehxdm.js} +318 -312
- package/dist/ensure-collection-tables-Bkvehxdm.js.map +1 -0
- package/dist/{ensure-tables-CIojK-Rx.js → ensure-tables-CYMtuuOd.js} +2 -2
- package/dist/{ensure-tables-CIojK-Rx.js.map → ensure-tables-CYMtuuOd.js.map} +1 -1
- package/dist/generate-drizzle-schema-logic-Dfyf_MRu.js +228 -0
- package/dist/generate-drizzle-schema-logic-Dfyf_MRu.js.map +1 -0
- package/dist/{generate-drizzle-schema-CwEgVyjO.js → generate-drizzle-schema-vSK-VdYT.js} +3 -3
- package/dist/generate-drizzle-schema-vSK-VdYT.js.map +1 -0
- package/dist/generate-postgres-ddl-logic-CR2xcS7e.js +475 -0
- package/dist/generate-postgres-ddl-logic-CR2xcS7e.js.map +1 -0
- package/dist/{generated-schema-staleness-DQdfJl2A.js → generated-schema-staleness-DRQe2BpC.js} +81 -3
- package/dist/{generated-schema-staleness-DQdfJl2A.js.map → generated-schema-staleness-DRQe2BpC.js.map} +1 -1
- package/dist/history/HistoryService.d.ts +23 -4
- package/dist/index.es.js +1991 -580
- package/dist/index.es.js.map +1 -1
- package/dist/introspect-db-logic-C6LQdTxj.js.map +1 -1
- package/dist/plan-schema-Hgl62S-w.js +1531 -0
- package/dist/plan-schema-Hgl62S-w.js.map +1 -0
- package/dist/{policy-drift-kNJ6X2Uj.js → policy-drift-B0GDRh7_.js} +2 -2
- package/dist/{policy-drift-kNJ6X2Uj.js.map → policy-drift-B0GDRh7_.js.map} +1 -1
- package/dist/{rls-bootstrap-sql-DLDnUjtx.js → rls-bootstrap-sql-BlzsOUtz.js} +111 -8
- package/dist/{rls-bootstrap-sql-DLDnUjtx.js.map → rls-bootstrap-sql-BlzsOUtz.js.map} +1 -1
- package/dist/{rls-enforcement-DeYEjYLt.js → rls-enforcement-BV12vBwQ.js} +2 -1
- package/dist/rls-enforcement-BV12vBwQ.js.map +1 -0
- package/dist/schema/catalogue-schema.d.ts +97 -0
- package/dist/schema/collection-index.d.ts +9 -0
- package/dist/schema/column-plan-helpers.d.ts +125 -0
- package/dist/schema/config-relations.d.ts +32 -0
- package/dist/schema/doctor-cli.js +4 -4
- package/dist/schema/doctor.d.ts +9 -0
- package/dist/schema/dynamic-tables.d.ts +27 -6
- package/dist/schema/ensure-collection-tables.d.ts +31 -268
- package/dist/schema/generate-drizzle-schema-logic.d.ts +26 -8
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +84 -168
- package/dist/schema/generate-postgres-ddl.js +8 -2
- package/dist/schema/generate-postgres-ddl.js.map +1 -1
- package/dist/schema/generated-column-conflicts.d.ts +84 -0
- package/dist/schema/generated-schema-diff.d.ts +56 -0
- package/dist/schema/generated-schema-staleness.d.ts +33 -0
- package/dist/schema/introspect-db-logic.d.ts +2 -0
- package/dist/schema/plan/diff-plan.d.ts +220 -0
- package/dist/schema/plan/plan-schema.d.ts +84 -0
- package/dist/schema/plan/render-ddl.d.ts +62 -0
- package/dist/schema/plan/render-drizzle.d.ts +31 -0
- package/dist/schema/plan/types.d.ts +410 -0
- package/dist/schema/plan/updated-at-trigger.d.ts +22 -0
- package/dist/schema/relation-names.d.ts +28 -0
- package/dist/schema/search-column.d.ts +9 -0
- package/dist/security/rls-enforcement.d.ts +17 -0
- package/dist/services/FetchService.d.ts +176 -36
- package/dist/services/PersistService.d.ts +17 -4
- package/dist/services/RelationService.d.ts +11 -3
- package/dist/services/collection-helpers.d.ts +16 -2
- package/dist/services/dataService.d.ts +29 -2
- package/dist/services/field-op-sql.d.ts +16 -0
- package/dist/services/field-viewer.d.ts +19 -0
- package/dist/services/realtimeService.d.ts +35 -1
- package/dist/services/row-pipeline.d.ts +29 -5
- package/dist/services/soft-delete.d.ts +73 -0
- package/dist/utils/pg-error-utils.d.ts +41 -1
- package/dist/{vector-index-DkWxm2de.js → vector-index-CMJKb3C9.js} +3 -14
- package/dist/{vector-index-DkWxm2de.js.map → vector-index-CMJKb3C9.js.map} +1 -1
- package/package.json +18 -10
- package/dist/cli-errors-DxN4yzdH.js.map +0 -1
- package/dist/doctor-D7HWmGzs.js.map +0 -1
- package/dist/ensure-collection-tables-D4wJzM4y.js.map +0 -1
- package/dist/generate-drizzle-schema-CwEgVyjO.js.map +0 -1
- package/dist/generate-drizzle-schema-logic-so2Z_lyC.js +0 -528
- package/dist/generate-drizzle-schema-logic-so2Z_lyC.js.map +0 -1
- package/dist/generate-postgres-ddl-logic-CtnpIBVv.js +0 -1312
- package/dist/generate-postgres-ddl-logic-CtnpIBVv.js.map +0 -1
- package/dist/rls-enforcement-DeYEjYLt.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli-errors-C3g_kHBw.js","names":[],"sources":["../src/utils/pg-error-utils.ts","../src/cli-errors.ts"],"sourcesContent":["/**\n * Shared PostgreSQL error extraction and user-friendly message formatting.\n *\n * Drizzle wraps native PG errors in a `.cause` chain. These utilities\n * unwrap that chain to get the real PostgreSQL error (identified by a\n * 5-character alphanumeric `code` such as `42P01`) and translate it into\n * a message that is safe and helpful to show to end-users.\n */\n\nimport { logger } from \"@rebasepro/server\";\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getTableName } from \"@rebasepro/common\";\n\n/**\n * Shape of a deliberate client-facing error — `ApiError` from\n * `@rebasepro/server`, or anything else carrying a 4xx `statusCode`.\n *\n * Matched structurally rather than with `instanceof`: `@rebasepro/server` can\n * be loaded twice (published dist vs. workspace source), which breaks class\n * identity — `PersistService` hedges against the same thing by also accepting\n * `name === \"ApiError\"`.\n */\ninterface ClientFacingError extends Error {\n statusCode?: number;\n code?: string;\n /** See `ApiError.expected` — routine outcomes log at debug, not warn. */\n expected?: boolean;\n}\n\n/**\n * Return the error when it is a deliberate 4xx, otherwise null.\n *\n * A thrown `ApiError` is a decision the server made about the request, not a\n * database failure: its message and code are already written for the client.\n */\nfunction asClientFacingError(error: unknown): ClientFacingError | null {\n if (!(error instanceof Error)) return null;\n const e = error as ClientFacingError;\n if (typeof e.statusCode !== \"number\" || e.statusCode < 400 || e.statusCode >= 500) return null;\n return e;\n}\n\n/** Shape of PostgreSQL errors with diagnostic metadata. */\nexport interface PostgresError extends Error {\n code?: string;\n detail?: string;\n hint?: string;\n constraint?: string;\n column?: string;\n table?: string;\n dataType?: string;\n cause?: unknown;\n}\n\n/**\n * Extract the underlying PostgreSQL error from a Drizzle wrapper.\n * Drizzle wraps PG errors in a `cause` property — this function\n * recursively walks the chain until it finds an object with a PG\n * error code (5-char alphanumeric, e.g. `42P01`).\n */\nexport function extractPgError(error: unknown): PostgresError | null {\n if (!error || typeof error !== \"object\") return null;\n if (!(error instanceof Error)) {\n // Check non-Error objects for a cause chain (Drizzle sometimes wraps oddly)\n if (\"cause\" in error && (error as Record<string, unknown>).cause && typeof (error as Record<string, unknown>).cause === \"object\") {\n return extractPgError((error as Record<string, unknown>).cause);\n }\n return null;\n }\n\n // Check if the error itself has a PG error code\n if (\"code\" in error && typeof (error as PostgresError).code === \"string\" && /^[0-9A-Z]{5}$/.test((error as PostgresError).code!)) {\n return error as PostgresError;\n }\n\n // Check the cause chain (Drizzle wraps PG errors)\n if (error.cause && typeof error.cause === \"object\") {\n return extractPgError(error.cause);\n }\n\n return null;\n}\n\n/**\n * Whether the failure came back from Postgres rather than from building the\n * query — which decides whether a fallback query is worth issuing.\n *\n * Reads here run inside a transaction (that is where `SET LOCAL ROLE` binds\n * RLS). Once a statement raises, that transaction is aborted, and every later\n * statement on it returns `25P02` — \"current transaction is aborted, commands\n * ignored until end of transaction block\". So a retry after a database error\n * cannot succeed, and it replaces a precise diagnosis (\"invalid input syntax\n * for type uuid\") with a generic one. Rethrow instead.\n *\n * A query the driver could not even build — a missing reciprocal relation, say\n * — never reached Postgres, leaves the transaction usable, and is exactly what\n * the fallback paths exist for.\n */\nexport function reachedDatabase(error: unknown): boolean {\n return extractPgError(error) !== null;\n}\n\n/**\n * Walk the error cause chain and return the deepest meaningful message.\n */\nexport function extractCauseMessage(error: unknown): string | null {\n if (!error || typeof error !== \"object\") return null;\n if (!(error instanceof Error)) return null;\n\n if (error.cause && typeof error.cause === \"object\") {\n const deeper = extractCauseMessage(error.cause);\n if (deeper) return deeper;\n // The cause itself has a message\n if (error.cause instanceof Error && error.cause.message) {\n return error.cause.message;\n }\n }\n return null;\n}\n\n/**\n * Codes that mean \"this connection will never work as configured\".\n *\n * A wrong password or a database that does not exist is a settled fact about\n * the connection string, not a transient fault — retrying produces the same\n * answer forever.\n */\nconst UNRECOVERABLE_CONNECT_CODES = new Set([\n \"28P01\", // invalid_password\n \"28000\", // invalid_authorization_specification\n \"3D000\", // invalid_catalog_name — the database does not exist\n \"42501\" // insufficient_privilege\n]);\n\nexport interface ConnectFailure {\n /** True when retrying cannot help: the connection string itself is wrong. */\n fatal: boolean;\n /** The deepest message available — the Postgres one where there is one. */\n reason: string;\n /** The `SQLSTATE`, when the failure came from Postgres rather than the socket. */\n code?: string;\n}\n\n/**\n * Describe a failed connection attempt in terms a developer can act on.\n *\n * The error a caller catches is Drizzle's wrapper: its message is\n * `Failed query: SELECT 1` and its stack runs through drizzle internals, while\n * the sentence that says what is actually wrong — \"password authentication\n * failed for user …\", \"database … does not exist\" — sits in `.cause`. Logging\n * the wrapper, as the bootstrapper used to, tells a developer with a typo in\n * their `DATABASE_URL` nothing at all.\n */\nexport function classifyConnectFailure(error: unknown): ConnectFailure {\n const pgError = extractPgError(error);\n const reason =\n pgError?.message ??\n extractCauseMessage(error) ??\n (error instanceof Error ? error.message : String(error));\n return {\n fatal: Boolean(pgError?.code && UNRECOVERABLE_CONNECT_CODES.has(pgError.code)),\n reason,\n code: pgError?.code\n };\n}\n\n/**\n * Detect whether an error is specifically a role-switching permission failure\n * (e.g. \"permission denied to set role\" or \"must be member of role\"),\n * as opposed to a table-level permission denial.\n *\n * This is used by the backend driver to auto-disable role switching when the\n * connection user lacks SET ROLE privileges, rather than surfacing a confusing\n * error to the Studio SQL Editor user.\n */\nexport function isRoleSwitchingPermissionError(error: unknown): boolean {\n const pgError = extractPgError(error);\n if (!pgError || pgError.code !== \"42501\") return false;\n const msg = pgError.message.toLowerCase();\n return msg.includes(\"set role\") || msg.includes(\"member of role\");\n}\n\n/**\n * Was this `42501` the *caller* being refused by a policy, rather than the\n * server lacking a privilege?\n *\n * Both arrive as `insufficient_privilege`, and they are opposite kinds of\n * problem. A row-level-security refusal is a working access-control system\n * doing its job: the caller asked for something their policies do not permit,\n * which is a 403 and nobody's bug. A missing `GRANT` is the deployment being\n * wrong — the connection role cannot touch the table at all, no policy is\n * involved, and nothing the caller changes about the request will help.\n *\n * Postgres distinguishes them in the message, so this does too:\n *\n * new row violates row-level security policy for table \"notes\" → the caller\n * permission denied for table notes → the server\n *\n * Only writes reach this. A read that RLS excludes is not an error — the rows\n * are filtered and the caller gets an empty page — so the erroring case is\n * specifically an `INSERT`/`UPDATE` whose row fails a policy's `WITH CHECK`.\n *\n * Matched on the message because that is the only thing carrying the\n * distinction; the SQLSTATE is identical either way. Narrow by design: anything\n * not naming row-level security stays the server's problem, since reporting a\n * genuine privilege misconfiguration as \"forbidden\" would send an operator\n * hunting for a policy bug that does not exist.\n */\nexport function isRowLevelSecurityDenial(error: unknown): boolean {\n const pgError = extractPgError(error);\n if (!pgError || pgError.code !== \"42501\") return false;\n return pgError.message.toLowerCase().includes(\"row-level security policy\");\n}\n\n/**\n * One constraint the database refused, named in the caller's vocabulary.\n *\n * `field` is the **wire** name, derived from the physical column: `author_id`\n * on the table is `authorId` on the row and in the request body, and telling a\n * caller their `author_id` is missing sends them looking for a key their client\n * has never seen. `code` is the SQLSTATE, which is stable, documented by\n * Postgres and the same in every environment — unlike the message, which is\n * deliberately thinner in production.\n *\n * Deliberately no `value`. The column name is safe to publish: it is already in\n * the OpenAPI, the generated SDK and the caller's own request. The *value* is\n * not — `23505`'s detail reads `Key (email)=(a@b.c) already exists.`, which\n * answers \"is this person registered?\" for any address on a table whose rows\n * RLS is otherwise hiding completely.\n */\nexport interface PgFieldViolation {\n field: string;\n code: string;\n}\n\n/**\n * The physical column names a Postgres error is about.\n *\n * Postgres puts one in `column` for `23502` and nowhere else, so the rest are\n * read out of the two places that do carry them:\n *\n * - `detail` — `Key (author_id)=(9) is not present in table \"authors\".` and\n * `Key (email, tenant_id)=(…) already exists.` Only the parenthesised column\n * list is read; the values after `=` are never touched.\n * - `constraint` — `users_email_key`, `posts_author_id_fkey`. The table prefix\n * and the constraint suffix are stripped, leaving the columns joined by `_`,\n * which is ambiguous for multi-column constraints and is therefore only used\n * when `detail` gave nothing.\n *\n * `22P02` carries neither, because an invalid literal fails during parse rather\n * than against a constraint. Its message names the *type*, and an enum type is\n * generated as `<table>_<column>` — which is the one case worth decoding,\n * because a value outside an enum's labels is the most common 22P02 anyone\n * hits and the least legible one.\n */\nfunction offendingColumns(pgError: PostgresError, collection?: CollectionConfig): string[] {\n if (pgError.column) return [pgError.column];\n\n const detail = pgError.detail;\n if (detail) {\n const keyed = /Key \\(([^)]+)\\)=/.exec(detail);\n if (keyed) {\n return keyed[1].split(\",\").map(part => part.trim().replace(/^\"|\"$/g, \"\")).filter(Boolean);\n }\n }\n\n if (pgError.code === \"22P02\") {\n // `invalid input value for enum posts_status: \"archived\"`\n const enumType = /invalid input value for enum ([^:\\s]+)/i.exec(pgError.message ?? \"\");\n if (enumType && collection) {\n const typeName = enumType[1].replace(/^.*\\./, \"\").replace(/\"/g, \"\");\n const table = getTableName(collection);\n if (typeName.startsWith(`${table}_`)) return [typeName.slice(table.length + 1)];\n }\n return [];\n }\n\n const constraint = pgError.constraint;\n if (constraint && collection) {\n const table = getTableName(collection);\n const stripped = constraint\n .replace(new RegExp(`^${table}_`), \"\")\n .replace(/_(pkey|key|fkey|unique|check|excl|idx)$/, \"\");\n // Only when it names something the collection actually has: a\n // hand-written constraint name is not a column list, and guessing at one\n // would put a field in the response that does not exist.\n if (stripped && stripped !== constraint) {\n const columns = new Set<string>();\n for (const [key, prop] of Object.entries(collection.properties ?? {})) {\n columns.add((prop as { columnName?: string })?.columnName ?? key);\n }\n if (columns.has(stripped)) return [stripped];\n const wire = fieldKeyForColumn(collection, stripped);\n if (collection.properties && wire in collection.properties) return [stripped];\n }\n }\n\n return [];\n}\n\n/**\n * The fields a Postgres error is about, for `details.violations`.\n *\n * Only the four SQLSTATEs that describe *the caller's data*: a missing value, a\n * duplicate, a bad literal, a foreign key pointing at nothing. Everything else\n * — a dropped connection, a missing table, a privilege problem — is the\n * deployment's, and naming a field for it would send the reader to the wrong\n * place.\n *\n * Empty when the collection is unknown or the column cannot be recovered. An\n * empty list is the honest answer; inventing a field is worse than saying\n * nothing, because a form will mark the wrong input red.\n */\nexport function pgFieldViolations(\n pgError: PostgresError,\n collection?: CollectionConfig\n): PgFieldViolation[] {\n const code = pgError.code;\n if (code !== \"23502\" && code !== \"23505\" && code !== \"22P02\" && code !== \"23503\") return [];\n // Without the collection there is no mapping, only a guess. `toWireKey`\n // would get the default case right and silently invent a field for any\n // property carrying an explicit `columnName` — and a form pointed at an\n // input that does not exist is worse off than one shown the raw column.\n if (!collection) return [];\n const columns = offendingColumns(pgError, collection);\n if (columns.length === 0) return [];\n return columns.map(column => ({\n field: fieldKeyForColumn(collection, column),\n code\n }));\n}\n\n/**\n * Translate a raw PostgreSQL error into a user-friendly message.\n *\n * @param pgError - The extracted PostgreSQL error (from {@link extractPgError})\n * @param context - A human-readable context string (e.g. collection slug or path)\n * @returns An object with a `message` safe for the client and the PG `code`.\n */\nexport function pgErrorToFriendlyMessage(\n pgError: PostgresError,\n context: string,\n options: { verbose?: boolean; collection?: CollectionConfig } = {}\n): { message: string; code: string; violations: PgFieldViolation[] } {\n // Postgres's own `DETAIL` and `HINT`, and the raw driver message, are what\n // make these errors useful while you are building — and what makes them an\n // oracle once the server is answering strangers.\n //\n // The sharp one is `23505`: its detail reads `Key (email)=(a@b.c) already\n // exists.`, which answers \"is this person registered?\" for any address, on\n // a table whose rows RLS is otherwise hiding completely. The rest leak\n // physical column and constraint names, which are the map for the next\n // question. So in production the shape of the failure is served — what\n // rule was broken, and where — and the values are not.\n //\n // The full text is not lost: the caller logs the original error. This\n // decides what crosses the wire, not what is recorded.\n const verbose = options.verbose ?? process.env.NODE_ENV !== \"production\";\n\n const detail = verbose ? (pgError.detail as string | undefined) : undefined;\n const hint = verbose ? (pgError.hint as string | undefined) : undefined;\n const constraint = pgError.constraint as string | undefined;\n const column = pgError.column as string | undefined;\n const table = pgError.table as string | undefined;\n const dataType = verbose ? (pgError.dataType as string | undefined) : undefined;\n const rawMessage = pgError.message || \"Unknown database error\";\n const pgMessage = verbose ? rawMessage : \"\";\n const code = pgError.code || \"UNKNOWN\";\n\n // Which *field* the caller has to fix, derived from the column. Safe in\n // production — a column name is already published in the OpenAPI and the\n // generated SDK — where the value that broke the rule is not, and is never\n // included. See `pgFieldViolations`.\n const violations = pgFieldViolations(pgError, options.collection);\n\n const suffix = hint ? ` Hint: ${hint}` : \"\";\n const tableRef = table ?? context;\n\n /** `\": <postgres said>\"`, or nothing when the details are withheld. */\n const said = pgMessage ? `: ${pgMessage}` : \"\";\n\n switch (pgError.code) {\n case \"23503\": // foreign_key_violation\n return {\n message: detail\n ? `Foreign key constraint violated: ${detail}${suffix}`\n : `Cannot complete operation: a foreign key constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code,\n violations\n };\n case \"23505\": // unique_violation\n return {\n message: detail\n ? `Duplicate value: ${detail}${suffix}`\n : `Cannot complete operation: a unique constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code,\n violations\n };\n case \"23502\": {\n // not_null_violation. The message names the *field* when the\n // collection is known, because that is the key the caller sent and\n // the only one they can act on: told `author_id` is missing, they go\n // looking for a key their generated client has never mentioned.\n const named = violations[0]?.field ?? column ?? \"unknown\";\n return {\n message: `Missing required field: \"${named}\" in \"${tableRef}\" cannot be empty.${suffix}`,\n code,\n violations\n };\n }\n case \"23514\": // check_violation\n return {\n message: `Validation failed: a check constraint${constraint ? ` (${constraint})` : \"\"} was violated in \"${context}\".${suffix}`,\n code,\n violations\n };\n case \"22P02\": // invalid_text_representation (e.g. invalid UUID, wrong enum value)\n return {\n message: `Invalid data format in \"${context}\"${said}.${suffix}`,\n code,\n violations\n };\n case \"22001\": // string_data_right_truncation (value too long)\n return {\n message: `Value too long for column \"${column ?? \"unknown\"}\" in \"${tableRef}\"${said}.${suffix}`,\n code,\n violations\n };\n case \"22003\": // numeric_value_out_of_range\n return {\n message: `Numeric value out of range for column \"${column ?? \"unknown\"}\" in \"${tableRef}\"${said}.${suffix}`,\n code,\n violations\n };\n case \"42703\": // undefined_column\n return {\n message: `Unknown column in \"${tableRef}\"${said}. Check if your schema is up to date (run migrations).${suffix}`,\n code,\n violations\n };\n case \"42P01\": // undefined_table\n return {\n message: `Table not found for \"${context}\"${said}. Check if your schema is up to date (run migrations).${suffix}`,\n code,\n violations\n };\n case \"42501\": // insufficient_privilege\n // Two unrelated failures share this SQLSTATE, and the old message\n // named both causes because it could not tell them apart — which\n // meant it was half wrong whichever one had happened, and sent the\n // reader to check the other. Postgres says which in its own message.\n return rawMessage.toLowerCase().includes(\"row-level security policy\")\n ? {\n // The caller. Their policies do not permit this row; the\n // deployment is working exactly as configured.\n message: `Not permitted to write this row in \"${tableRef}\": it does not satisfy the row-level security policy.${suffix}`,\n code,\n violations\n }\n : {\n // The deployment. No policy is involved — the connecting\n // role cannot touch the table at all.\n message: `Permission denied on \"${tableRef}\": the database role this server connects as lacks privileges on it.${suffix}`,\n code,\n violations\n };\n case \"28000\": // invalid_authorization_specification\n return {\n message: `Authorization failed for \"${context}\". Check your database credentials.${suffix}`,\n code,\n violations\n };\n default: {\n // Unhandled PG code — still surface the actual database message\n const parts = [`Database error in \"${context}\" [${code}]${said}`];\n if (detail) parts.push(`Detail: ${detail}`);\n if (column) parts.push(`Column: ${column}`);\n if (dataType) parts.push(`Data type: ${dataType}`);\n if (constraint) parts.push(`Constraint: ${constraint}`);\n if (hint) parts.push(`Hint: ${hint}`);\n return { message: parts.join(\". \"), code, violations };\n }\n }\n}\n\n/**\n * Sanitize any error into a message safe and helpful for the client.\n *\n * A deliberate 4xx (`ApiError`) passes through untouched — the server already\n * decided what the client should read. Otherwise the PG error is extracted\n * from the Drizzle cause chain, falling back to a generic message that\n * doesn't leak SQL.\n *\n * @param error - The raw caught error\n * @param context - A human-readable context string (e.g. collection path)\n * @returns An object with `message` (user-friendly) and optional `code`\n * (the `ApiError` code, or the PG SQLSTATE).\n */\nexport function sanitizeErrorForClient(\n error: unknown,\n context: string,\n options: { collection?: CollectionConfig } = {}\n): { message: string; code?: string; violations?: PgFieldViolation[] } {\n // ── A deliberate 4xx is not a database failure ──────────────────\n // Its message and code are written for the client; replacing them with\n // \"Check server logs\" would discard the only diagnosis the caller gets\n // (e.g. the offending filter field and the collection's valid ones).\n // Log level follows the same convention as the HTTP error handler in\n // @rebasepro/server: routine outcomes at debug, everything else at warn.\n const clientError = asClientFacingError(error);\n if (clientError) {\n const line = `[API ${clientError.statusCode} ${clientError.code ?? \"BAD_REQUEST\"}] in \"${context}\": ${clientError.message}`;\n if (clientError.expected) {\n logger.debug(line);\n } else {\n logger.warn(`⚠️ ${line}`);\n }\n return { message: clientError.message, ...(clientError.code && { code: clientError.code }) };\n }\n\n // ── Always log the full, unsanitized error server-side ──────────\n const pgError = extractPgError(error);\n\n if (pgError) {\n logger.error(`[PG ${pgError.code}] Error in \"${context}\"`, {\n code: pgError.code,\n message: pgError.message,\n detail: pgError.detail,\n hint: pgError.hint,\n column: pgError.column,\n table: pgError.table,\n constraint: pgError.constraint,\n dataType: pgError.dataType\n // The outer Drizzle wrapper message used to be logged here \"for\n // full context\": it is `Failed query: <sql>\\nparams: <values>`, so\n // it published the statement and every bound value (an email, a\n // password hash) on every realtime data failure. The SQLSTATE,\n // detail, table, column and constraint above are the diagnostic\n // value; the wrapper added only the leak. `logger` strips the\n // wrapper as well, but the field itself carried nothing else.\n });\n const { message, code, violations } = pgErrorToFriendlyMessage(pgError, context, { collection: options.collection });\n return { message, code, ...(violations.length > 0 && { violations }) };\n }\n\n // No PG error found — log the raw error as-is\n logger.error(`Database error in \"${context}\" (no PG error extracted)`, {\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n cause: error instanceof Error && error.cause\n ? (error.cause instanceof Error ? error.cause.message : String(error.cause))\n : undefined\n });\n\n // Try to get the deepest cause message\n const causeMessage = extractCauseMessage(error);\n if (causeMessage) {\n return { message: `Database error in \"${context}\": ${causeMessage}` };\n }\n\n // Last resort — generic message, never leak raw SQL\n return { message: `Could not load data for \"${context}\". Check server logs for details.` };\n}\n","import chalk from \"chalk\";\nimport { outWarn, outError } from \"./cli-output\";\nimport { extractCauseMessage } from \"./utils/pg-error-utils\";\n\n/**\n * Detect whether an error (or AggregateError wrapping multiple attempts)\n * represents an ECONNREFUSED — i.e. the database is simply not running.\n *\n * Handles:\n * - Direct `{ code: \"ECONNREFUSED\" }` errors from Node `net`\n * - `AggregateError` from dual-stack IPv4+IPv6 connection attempts\n * - Drizzle's `cause`-wrapped pg errors\n */\nexport function isEconnrefused(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { code?: string; cause?: unknown; errors?: unknown[] };\n if (e.code === \"ECONNREFUSED\") return true;\n // AggregateError from Node net (dual-stack IPv4 + IPv6)\n if (Array.isArray(e.errors)) {\n return e.errors.some(inner =>\n inner && typeof inner === \"object\" && (inner as { code?: string }).code === \"ECONNREFUSED\"\n );\n }\n // Drizzle wraps the pg error in `cause`\n if (e.cause && typeof e.cause === \"object\") {\n return isEconnrefused(e.cause);\n }\n return false;\n}\n\n/**\n * Detect PostgreSQL authentication failures.\n * PG error codes: 28P01 (invalid_password), 28000 (invalid_authorization_specification)\n */\nexport function isAuthFailure(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { code?: string; cause?: unknown };\n if (e.code === \"28P01\" || e.code === \"28000\") return true;\n if (e.cause && typeof e.cause === \"object\") {\n return isAuthFailure(e.cause);\n }\n // Also check the message for common pg auth failure text\n if (\"message\" in e && typeof (e as { message?: string }).message === \"string\") {\n const msg = (e as { message: string }).message.toLowerCase();\n if (msg.includes(\"password authentication failed\") || msg.includes(\"no pg_hba.conf entry\")) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Detect the \"SSL is not enabled on the server\" failure — the client attempted\n * an SSL handshake against a Postgres server that doesn't support it (common\n * with a plain local dev database). The fix is `?sslmode=disable` on the URL.\n */\nexport function isSslNotEnabled(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { message?: string; cause?: unknown };\n if (typeof e.message === \"string\" && e.message.toLowerCase().includes(\"ssl is not enabled on the server\")) {\n return true;\n }\n if (e.cause && typeof e.cause === \"object\") {\n return isSslNotEnabled(e.cause);\n }\n return false;\n}\n\n/**\n * Detect PostgreSQL \"cannot drop ... because other objects depend on it\"\n * (error code 2BP01, dependent_objects_still_exist). This is the failure that\n * strands a declarative `db push` half-applied when a collection is removed but\n * an enum type it defined is still referenced by another object.\n */\nexport function isDependencyDropError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as { code?: string; message?: string; cause?: unknown };\n if (e.code === \"2BP01\") return true;\n if (typeof e.message === \"string\") {\n const msg = e.message.toLowerCase();\n if (msg.includes(\"other objects depend on it\") || msg.includes(\"cannot drop type\")) {\n return true;\n }\n }\n if (e.cause && typeof e.cause === \"object\") {\n return isDependencyDropError(e.cause);\n }\n return false;\n}\n\n/**\n * Parse host:port from a DATABASE_URL for display purposes.\n *\n * Exported because every message about a connection has to name the thing it\n * could not reach, and the boot path needs the same rendering the CLI banners\n * use — including the same refusal to print the URL itself, which carries the\n * password.\n */\nexport function parseHostInfo(databaseUrl: string): string {\n try {\n const parsed = new URL(databaseUrl);\n return `${parsed.hostname}:${parsed.port || 5432}`;\n } catch {\n return \"unknown\";\n }\n}\n\n/**\n * The sentence the operating system actually produced, dug out of the wrappers.\n *\n * `connect ECONNREFUSED 127.0.0.1:5432` is written by `net`, then wrapped by\n * `pg`, then wrapped again by Drizzle as `Failed query: …` — and on a\n * dual-stack host it is not in `.cause` at all but inside the\n * `AggregateError.errors` array of one attempt per resolved address. Printing\n * the banner without it loses the one token every search engine, runbook and\n * colleague recognises.\n */\nexport function deepestErrorMessage(err: unknown): string | null {\n if (!err || typeof err !== \"object\") return null;\n const e = err as { message?: string; code?: string; cause?: unknown; errors?: unknown[] };\n\n if (Array.isArray(e.errors)) {\n for (const inner of e.errors) {\n const deeper = deepestErrorMessage(inner);\n if (deeper) return deeper;\n }\n }\n if (e.cause) {\n const deeper = deepestErrorMessage(e.cause);\n if (deeper) return deeper;\n }\n if (typeof e.message === \"string\" && e.message && !e.message.startsWith(\"Failed query:\")) {\n return e.code ? `${e.message} (${e.code})` : e.message;\n }\n return null;\n}\n\n/** One indented line naming the driver's own reason, or nothing. */\nfunction driverReasonLine(err: unknown): string {\n const reason = err === undefined ? null : deepestErrorMessage(err);\n return reason ? ` The driver said: ${reason}\\n\\n` : \"\";\n}\n\n/**\n * Format a diagnostic banner for ECONNREFUSED errors.\n */\nfunction formatConnectionRefusedBanner(databaseUrl: string, err?: unknown): string {\n const hostInfo = parseHostInfo(databaseUrl);\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ Cannot connect to PostgreSQL at ${hostInfo}\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n driverReasonLine(err) +\n ` The database server is not running or is not accepting\\n` +\n ` connections. Common fixes:\\n` +\n `\\n` +\n ` • docker compose up -d db (the service a Rebase scaffold ships)\\n` +\n ` • brew services start postgresql@18\\n` +\n ` • Verify DATABASE_URL in your .env file\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/**\n * Format a diagnostic banner for authentication failures.\n */\nfunction formatAuthFailureBanner(databaseUrl: string, err?: unknown): string {\n const hostInfo = parseHostInfo(databaseUrl);\n let username = \"unknown\";\n try {\n username = new URL(databaseUrl).username || \"unknown\";\n } catch { /* ignore */ }\n\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ Authentication failed for user \"${username}\" at ${hostInfo}\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n driverReasonLine(err) +\n ` PostgreSQL rejected the credentials. Common fixes:\\n` +\n `\\n` +\n ` • Check the username and password in DATABASE_URL\\n` +\n ` • Verify the user exists: psql -c \"\\\\du\"\\n` +\n ` • Reset the password: ALTER USER ${username} PASSWORD 'new_password';\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/**\n * Format a diagnostic banner for \"SSL is not enabled on the server\".\n */\nfunction formatSslNotEnabledBanner(databaseUrl: string): string {\n const hostInfo = parseHostInfo(databaseUrl);\n const suggestion = databaseUrl.includes(\"?\") ? \"&sslmode=disable\" : \"?sslmode=disable\";\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ SSL is not enabled on the PostgreSQL server at ${hostInfo}\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n ` The client tried to connect over SSL, but the server does not\\n` +\n ` support it. This is normal for a plain local dev database.\\n` +\n `\\n` +\n ` Fix: append ${chalk.bold(\"sslmode=disable\")} to DATABASE_URL, e.g.\\n` +\n `\\n` +\n ` DATABASE_URL=...${suggestion}\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/**\n * Format a diagnostic banner for a dependency-drop failure during `db push`.\n * Explains that the database may be left partially migrated and how to recover.\n */\nfunction formatDependencyDropBanner(): string {\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ Schema push failed: a type/table could not be dropped\\n` +\n ` because other objects still depend on it.\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n ` ${chalk.yellow(\"The database may now be partially migrated.\")} Atlas applies\\n` +\n ` statements individually, so earlier changes in this push may\\n` +\n ` already be committed while later ones failed.\\n` +\n `\\n` +\n ` This commonly happens when a collection is removed but an enum\\n` +\n ` type it defined is still referenced. To recover:\\n` +\n `\\n` +\n ` 1. Inspect the leftover object named in the error above.\\n` +\n ` 2. Drop it with CASCADE, e.g.:\\n` +\n ` psql \"$DATABASE_URL\" -c 'DROP TYPE \"<name>\" CASCADE;'\\n` +\n ` 3. Re-run: ${chalk.bold.green(\"rebase db push\")}\\n` +\n `\\n` +\n ` Prefer a safe, versioned workflow? Use ${chalk.bold(\"rebase db generate\")}\\n` +\n ` + ${chalk.bold(\"rebase db migrate\")} instead of push for destructive changes.\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/**\n * Pre-flight check: verify that the database is reachable before running\n * a heavy subprocess (Atlas, migrations, etc.).\n *\n * Exits with code 1 and a friendly banner on known failure modes.\n * On unknown errors, logs a warning and allows the caller to proceed.\n */\nexport async function checkDatabaseConnectivity(databaseUrl: string): Promise<void> {\n let client: import(\"pg\").Client | undefined;\n try {\n const { Client } = await import(\"pg\");\n client = new Client({\n connectionString: databaseUrl,\n connectionTimeoutMillis: 5000\n });\n await client.connect();\n await client.query(\"SELECT 1\");\n } catch (err: unknown) {\n if (isEconnrefused(err)) {\n outError(formatConnectionRefusedBanner(databaseUrl, err));\n process.exit(1);\n }\n if (isAuthFailure(err)) {\n outError(formatAuthFailureBanner(databaseUrl, err));\n process.exit(1);\n }\n if (isSslNotEnabled(err)) {\n outError(formatSslNotEnabledBanner(databaseUrl));\n process.exit(1);\n }\n // Unknown error — warn but don't block; let the downstream tool surface details\n outWarn(chalk.yellow(` ⚠ Could not verify database connectivity: ${err instanceof Error ? err.message : String(err)}`));\n outWarn(chalk.gray(\" Proceeding anyway — the command may fail if the database is unreachable.\"));\n } finally {\n try {\n await client?.end();\n } catch {\n // ignore cleanup errors\n }\n }\n}\n\n/**\n * Post-hoc error diagnosis for direct database operations (e.g. applyPolicies).\n * Returns a formatted diagnostic string if the error matches a known pattern,\n * or null if unrecognized.\n */\nexport function diagnoseDbError(err: unknown, databaseUrl?: string): string | null {\n if (isEconnrefused(err)) {\n return formatConnectionRefusedBanner(databaseUrl || \"\", err);\n }\n if (isAuthFailure(err)) {\n return formatAuthFailureBanner(databaseUrl || \"\", err);\n }\n if (isSslNotEnabled(err)) {\n return formatSslNotEnabledBanner(databaseUrl || \"\");\n }\n if (isDependencyDropError(err)) {\n return formatDependencyDropBanner();\n }\n return null;\n}\n\n/**\n * Say why the command failed, on the way out.\n *\n * The entry point below used to be `.catch(() => process.exit(1))`, which threw\n * the error away. Every message this file and its services raise — \"Branch\n * \\\"x\\\" already exists.\", \"the source database has active connections\", \"Branch\n * name is too long\" — was written, wrapped in the right PG error code, and then\n * discarded one frame before it reached a terminal. What a developer saw was a\n * header line, no error, and exit 1.\n *\n * Two shapes are deliberately kept quiet:\n *\n * - **A child process that already spoke.** Atlas, `pg_dump` and `psql` run\n * with inherited stdio, so their diagnosis is on the terminal already and\n * execa's wrapper adds only `Command failed with exit code 1: atlas …`.\n * `packages/cli` filters exactly these two phrasings one level up\n * (`runDbCommand`), and this is that filter, for the process that is actually\n * throwing.\n *\n * - **A message that is only a query.** Drizzle reports failures as\n * `Failed query: <sql> params:` and hides the real PostgreSQL error in\n * `cause`, so the wrapper alone tells a reader nothing they can act on. The\n * cause is appended when it says something the message does not.\n *\n * - **An error that has already printed its own diagnosis**, marked\n * `alreadyReported`. `CollectionsPathMissing` is one: it prints the path, what\n * it resolved to and the cwd it resolved against, and then throws so the entry\n * point owns the exit code. Repeating its one-line summary underneath would\n * undo the \"printed once\" this whole path exists for.\n */\nexport function reportCommandFailure(error: unknown): void {\n const message = error instanceof Error ? error.message : String(error ?? \"\");\n\n if ((error as { alreadyReported?: boolean } | null)?.alreadyReported) return;\n if (!message || /Command failed|exited with code/i.test(message)) return;\n\n outError(\"\");\n outError(chalk.red(` ✗ ${message}`));\n\n const cause = extractCauseMessage(error);\n if (cause && !message.includes(cause)) {\n outError(chalk.gray(` ${cause}`));\n }\n outError(\"\");\n}\n\n/* ------------------------------------------------------------------------- *\n * Atlas failures that have a remedy\n *\n * Atlas runs with a teed stderr, so what reaches these is its output as text,\n * not a `pg` error object carrying a `code`. They are deliberately NOT part of\n * `diagnoseDbError`: that one is shared with the boot path, and \"record a\n * baseline with `rebase db migrate`\" is advice for somebody standing at a\n * terminal, not for a container that has just failed to start.\n * ------------------------------------------------------------------------- */\n\n/**\n * `migrate apply` refusing because the database already has the schema.\n *\n * `42710` (duplicate_object) and `42P07` (duplicate_table) are what a migration\n * hits when boot-ensure — or a `db push` — has already provisioned the objects\n * it was going to create. Since boot-ensure provisions *every* production\n * database, this is the normal case rather than the exotic one, and the raw\n * failure (`pq: type \"posts_status\" already exists (42710)`, then `sql/migrate:\n * write revision: … current transaction is aborted`) names no way forward.\n */\nexport function parseAlreadyProvisioned(text: string): { object: string; code: string } | null {\n const withCode = /(?:type|relation|constraint|schema) \"([^\"]+)\" already exists \\((42710|42P07)\\)/.exec(text);\n if (withCode) return { object: withCode[1], code: withCode[2] };\n // Some Atlas builds keep the SQLSTATE on a following line instead.\n const bare = /(?:type|relation|constraint|schema) \"([^\"]+)\" already exists/.exec(text);\n if (bare && /42710|42P07/.test(text)) return { object: bare[1], code: /42P07/.test(text) ? \"42P07\" : \"42710\" };\n return null;\n}\n\n/**\n * What to do about it: tell Atlas the database is already at a version.\n *\n * Atlas's own mechanism (`migrate apply --baseline <version>`), not a ledger of\n * ours — it writes the revision row Atlas reads, so every later `rebase db\n * migrate` is an ordinary one.\n */\nexport function formatBaselineRemedy(version: string | null, object?: string): string {\n const versionToken = version ?? \"<version>\";\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ This database already has the schema this migration creates\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n (object ? ` ${chalk.gray(`\"${object}\" is already there, so the migration cannot create it.`)}\\n\\n` : \"\") +\n ` Nothing is wrong with the migration — the database was provisioned\\n` +\n ` another way. Every Rebase boot ensures the schema, and ${chalk.bold(\"rebase db push\")}\\n` +\n ` applies it directly, so a database that has ever run either one is\\n` +\n ` ahead of a migration history that was never recorded.\\n` +\n `\\n` +\n ` Record where it already is, then migrate normally:\\n` +\n `\\n` +\n ` ${chalk.bold.green(`rebase db migrate --baseline ${versionToken}`)}\\n` +\n ` ${chalk.bold.green(\"rebase db migrate\")}\\n` +\n `\\n` +\n ` The baseline is the version already applied — the numeric prefix of\\n` +\n ` the migration file describing what is in the database now. Migrations\\n` +\n ` after it run; it and everything before it are marked done.\\n` +\n `\\n` +\n ` On a database nothing has ever booted against, none of this is needed.\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/** `ALTER TABLE … SET NOT NULL` on a table that already holds rows (23502). */\nexport function parseNotNullViolation(text: string): { table: string; column: string } | null {\n const match = /column \"([^\"]+)\" of relation \"([^\"]+)\" contains null values/.exec(text);\n return match ? { table: match[2], column: match[1] } : null;\n}\n\n/**\n * The three ways out, because there is no fourth.\n *\n * Boot-ensure handles this case — it adds the column nullable and sets NOT NULL\n * only when the table is empty — so a push that dies here is strictly worse\n * than the boot that would have run instead, and the developer deserves to be\n * told which of the three they want rather than left with `pq: … contains null\n * values (23502)` and no next step.\n */\nexport function formatNotNullViolationBanner(\n violation: { table: string; column: string },\n rowCount: number | null\n): string {\n const { table, column } = violation;\n const rows = rowCount === null\n ? ` \"${table}\" already holds rows, and none of them has a value for \"${column}\".\\n`\n : ` \"${table}\" already holds ${rowCount} row${rowCount === 1 ? \"\" : \"s\"}, and they have no value for \"${column}\".\\n`;\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ Cannot make \"${table}\".\"${column}\" required: existing rows are null\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n rows +\n ` PostgreSQL will not add the NOT NULL until every one of them does.\\n` +\n `\\n` +\n ` Three ways forward:\\n` +\n `\\n` +\n ` 1. Give the property a default, so the push can backfill:\\n` +\n ` ${chalk.gray(`{ type: \"string\", defaultValue: \"…\", validation: { required: true } }`)}\\n` +\n ` 2. Backfill by hand first, then push again:\\n` +\n ` ${chalk.gray(`psql \"$DATABASE_URL\" -c 'UPDATE \"${table}\" SET \"${column}\" = … WHERE \"${column}\" IS NULL;'`)}\\n` +\n ` 3. Leave it optional — take \\`validation.required\\` off the property.\\n` +\n `\\n` +\n ` ${chalk.gray(\"Nothing was applied for this column. `rebase dev` would have added it\")}\\n` +\n ` ${chalk.gray(\"nullable instead: boot sets NOT NULL only when it is safe.\")}\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/** Atlas refusing to remove a label from an enum — a renamed `enum` option id. */\nexport function parseEnumLabelDrop(text: string): { label: string; enumType: string } | null {\n const match = /dropping (?:enum )?value \"([^\"]+)\" from enum \"([^\"]+)\" is not supported/.exec(text);\n return match ? { label: match[1], enumType: match[2] } : null;\n}\n\n/**\n * Why the two paths disagree, and what retiring an option id actually costs.\n *\n * Boot-ensure adds enum labels and never removes one, so `rebase dev` accepts\n * the very edit that stops `db push` dead. PostgreSQL has no `ALTER TYPE …\n * DROP VALUE`: a label goes only by rewriting the type, which is a data\n * migration and not a schema push.\n */\nexport function formatEnumLabelDropBanner(drop: { label: string; enumType: string }): string {\n const { label, enumType } = drop;\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ \"${label}\" cannot be removed from the enum \"${enumType}\"\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n ` PostgreSQL has no ALTER TYPE … DROP VALUE. An option id can be added\\n` +\n ` to an enum but never taken out of one, so renaming an id reads as a\\n` +\n ` removal and a push cannot carry it.\\n` +\n `\\n` +\n ` ${chalk.yellow(\"Nothing was applied.\")} ${chalk.bold(\"rebase dev\")} accepts this same edit — boot adds\\n` +\n ` new labels and never removes one — so the two paths disagree by\\n` +\n ` design, and the old label would simply have stayed behind, unused.\\n` +\n `\\n` +\n ` To keep the id: put \"${label}\" back and change only its label text.\\n` +\n `\\n` +\n ` To retire it for real, it is a data migration:\\n` +\n `\\n` +\n ` 1. Add the new id alongside the old one, and push.\\n` +\n ` 2. Move the rows: ${chalk.gray(`UPDATE … SET … = '<new>' WHERE … = '${label}';`)}\\n` +\n ` 3. Rewrite the type, which is what actually drops the label:\\n` +\n ` ${chalk.gray(\"rebase db generate retire_option && rebase db migrate\")}\\n` +\n ` ${chalk.gray(\"(a migration can CREATE TYPE …, ALTER TABLE … TYPE … USING, DROP TYPE)\")}\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/** How many rows a table holds, or `null` when we cannot say. */\nasync function countRows(databaseUrl: string | undefined, table: string): Promise<number | null> {\n if (!databaseUrl) return null;\n try {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: databaseUrl, connectionTimeoutMillis: 5000 });\n await client.connect();\n try {\n // Identifier interpolation, and it has to be: the name comes from\n // PostgreSQL's own error text, and `count(*)` takes no parameter in\n // that position. Quoted, with any embedded quote doubled.\n const res = await client.query(`SELECT count(*)::int AS n FROM \"${table.replace(/\"/g, \"\\\"\\\"\")}\"`);\n return (res.rows[0] as { n: number } | undefined)?.n ?? null;\n } finally {\n await client.end();\n }\n } catch {\n return null;\n }\n}\n\n/**\n * A hand-written generated column reading a column the plan wants to retype or\n * drop.\n *\n * Rebase's own generated columns are dropped and rebuilt around the apply — it\n * holds their definition in `search.sql`. This one it does not: PostgreSQL\n * stores a generated expression only in the catalogue, so dropping it to let\n * the apply through would destroy the only copy. Refuse instead, and say what\n * the operator can do about it.\n */\nexport function formatForeignGeneratedColumnBanner(\n conflicts: { schema: string; table: string; column: string; blocking: { column: string; kind: string }[] }[]\n): string {\n const lines = conflicts.map(c => {\n const reads = c.blocking.map(b => `\"${b.column}\"`).join(\", \");\n return ` ${chalk.bold(`${c.schema}.${c.table}.${c.column}`)} reads ${reads}`;\n });\n const first = conflicts[0];\n return (\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n ` ❌ A generated column depends on a column this push changes\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n` +\n `\\n` +\n lines.join(\"\\n\") + `\\n` +\n `\\n` +\n ` PostgreSQL refuses to retype or drop a column while a GENERATED\\n` +\n ` ALWAYS AS … STORED expression reads it, and an Atlas apply is one\\n` +\n ` transaction — so this refusal would roll back every other statement\\n` +\n ` in the push with it.\\n` +\n `\\n` +\n ` ${chalk.yellow(\"Nothing was applied.\")} Rebase rebuilds the generated columns it made\\n` +\n ` itself (a collection's ${chalk.bold(\"search\")} block) around the apply. It has no\\n` +\n ` definition for this one, and a dropped generated expression is not\\n` +\n ` recoverable from anywhere but your own migration.\\n` +\n `\\n` +\n ` Drop it, push, and put it back:\\n` +\n `\\n` +\n ` ${chalk.gray(`ALTER TABLE \"${first.schema}\".\"${first.table}\" DROP COLUMN \"${first.column}\";`)}\\n` +\n ` ${chalk.gray(\"rebase db push\")}\\n` +\n ` ${chalk.gray(\"-- then re-create the column with its original expression\")}\\n` +\n `\\n` +\n ` Or declare it through a ${chalk.bold(\"search\")} block, and Rebase will own it.\\n` +\n `\\n` +\n `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`\n );\n}\n\n/**\n * The remedy for an Atlas invocation that failed, or `null`.\n *\n * Scoped by the invocation, because the same database state means different\n * things to different subcommands: \"already exists\" under `migrate apply` wants\n * a baseline, while under `schema apply` it is a genuine conflict.\n */\nexport async function diagnoseAtlasFailure(context: {\n domain: string;\n args: string[];\n stderr: string;\n databaseUrl?: string;\n /** The newest migration version on disk, named in the baseline remedy. */\n latestMigrationVersion?: string | null;\n}): Promise<string | null> {\n const { domain, args, stderr, databaseUrl } = context;\n\n if (domain === \"migrate\" && args.includes(\"apply\")) {\n const provisioned = parseAlreadyProvisioned(stderr);\n if (provisioned) {\n return formatBaselineRemedy(context.latestMigrationVersion ?? null, provisioned.object);\n }\n }\n\n if (domain === \"schema\" && args.includes(\"apply\")) {\n const enumDrop = parseEnumLabelDrop(stderr);\n if (enumDrop) return formatEnumLabelDropBanner(enumDrop);\n\n const notNull = parseNotNullViolation(stderr);\n if (notNull) return formatNotNullViolationBanner(notNull, await countRows(databaseUrl, notNull.table));\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmCA,SAAS,oBAAoB,OAA0C;CACnE,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CACtC,MAAM,IAAI;CACV,IAAI,OAAO,EAAE,eAAe,YAAY,EAAE,aAAa,OAAO,EAAE,cAAc,KAAK,OAAO;CAC1F,OAAO;AACX;;;;;;;AAoBA,SAAgB,eAAe,OAAsC;CACjE,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,IAAI,EAAE,iBAAiB,QAAQ;EAE3B,IAAI,WAAW,SAAU,MAAkC,SAAS,OAAQ,MAAkC,UAAU,UACpH,OAAO,eAAgB,MAAkC,KAAK;EAElE,OAAO;CACX;CAGA,IAAI,UAAU,SAAS,OAAQ,MAAwB,SAAS,YAAY,gBAAgB,KAAM,MAAwB,IAAK,GAC3H,OAAO;CAIX,IAAI,MAAM,SAAS,OAAO,MAAM,UAAU,UACtC,OAAO,eAAe,MAAM,KAAK;CAGrC,OAAO;AACX;;;;;;;;;;;;;;;;AAiBA,SAAgB,gBAAgB,OAAyB;CACrD,OAAO,eAAe,KAAK,MAAM;AACrC;;;;AAKA,SAAgB,oBAAoB,OAA+B;CAC/D,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CAEtC,IAAI,MAAM,SAAS,OAAO,MAAM,UAAU,UAAU;EAChD,MAAM,SAAS,oBAAoB,MAAM,KAAK;EAC9C,IAAI,QAAQ,OAAO;EAEnB,IAAI,MAAM,iBAAiB,SAAS,MAAM,MAAM,SAC5C,OAAO,MAAM,MAAM;CAE3B;CACA,OAAO;AACX;;;;;;;;AASA,IAAM,8CAA8B,IAAI,IAAI;CACxC;CACA;CACA;CACA;AACJ,CAAC;;;;;;;;;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,SAAS,KAAI,MAAK,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,KAAK,IAAI;EAC5D,OAAO,OAAO,MAAM,KAAK,GAAG,EAAE,OAAO,GAAG,EAAE,MAAM,GAAG,EAAE,QAAQ,EAAE,SAAS;CAC5E,CAAC;CACD,MAAM,QAAQ,UAAU;CACxB,OACI,oMAKA,MAAM,KAAK,IAAI,IAAI;;;;;;;IAOd,MAAM,OAAO,sBAAsB,EAAE,2EACd,MAAM,KAAK,QAAQ,EAAE,6MAM1C,MAAM,KAAK,gBAAgB,MAAM,OAAO,KAAK,MAAM,MAAM,iBAAiB,MAAM,OAAO,GAAG,EAAE,QAC5F,MAAM,KAAK,gBAAgB,EAAE,QAC7B,MAAM,KAAK,2DAA2D,EAAE,gCAElD,MAAM,KAAK,QAAQ,EAAE;AAI1D;;;;;;;;AASA,eAAsB,qBAAqB,SAOhB;CACvB,MAAM,EAAE,QAAQ,MAAM,QAAQ,gBAAgB;CAE9C,IAAI,WAAW,aAAa,KAAK,SAAS,OAAO,GAAG;EAChD,MAAM,cAAc,wBAAwB,MAAM;EAClD,IAAI,aACA,OAAO,qBAAqB,QAAQ,0BAA0B,MAAM,YAAY,MAAM;CAE9F;CAEA,IAAI,WAAW,YAAY,KAAK,SAAS,OAAO,GAAG;EAC/C,MAAM,WAAW,mBAAmB,MAAM;EAC1C,IAAI,UAAU,OAAO,0BAA0B,QAAQ;EAEvD,MAAM,UAAU,sBAAsB,MAAM;EAC5C,IAAI,SAAS,OAAO,6BAA6B,SAAS,MAAM,UAAU,aAAa,QAAQ,KAAK,CAAC;CACzG;CAEA,OAAO;AACX"}
|
package/dist/cli-errors.d.ts
CHANGED
|
@@ -148,6 +148,25 @@ export declare function formatEnumLabelDropBanner(drop: {
|
|
|
148
148
|
label: string;
|
|
149
149
|
enumType: string;
|
|
150
150
|
}): string;
|
|
151
|
+
/**
|
|
152
|
+
* A hand-written generated column reading a column the plan wants to retype or
|
|
153
|
+
* drop.
|
|
154
|
+
*
|
|
155
|
+
* Rebase's own generated columns are dropped and rebuilt around the apply — it
|
|
156
|
+
* holds their definition in `search.sql`. This one it does not: PostgreSQL
|
|
157
|
+
* stores a generated expression only in the catalogue, so dropping it to let
|
|
158
|
+
* the apply through would destroy the only copy. Refuse instead, and say what
|
|
159
|
+
* the operator can do about it.
|
|
160
|
+
*/
|
|
161
|
+
export declare function formatForeignGeneratedColumnBanner(conflicts: {
|
|
162
|
+
schema: string;
|
|
163
|
+
table: string;
|
|
164
|
+
column: string;
|
|
165
|
+
blocking: {
|
|
166
|
+
column: string;
|
|
167
|
+
kind: string;
|
|
168
|
+
}[];
|
|
169
|
+
}[]): string;
|
|
151
170
|
/**
|
|
152
171
|
* The remedy for an Atlas invocation that failed, or `null`.
|
|
153
172
|
*
|
package/dist/cli-helpers.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { GeneratedColumnDependency } from "./schema/generated-column-conflicts.js";
|
|
1
2
|
import type { CollectionConfig } from "@rebasepro/types";
|
|
2
3
|
/**
|
|
3
4
|
* Why is a dependency's binary missing — never installed, or installed with its
|
|
@@ -150,6 +151,27 @@ export declare function applySearchDdl(databaseUrl: string, drizzleDir?: string)
|
|
|
150
151
|
* `search` block, which is every project that has not opted in.
|
|
151
152
|
*/
|
|
152
153
|
export declare function getSearchExcludes(collectionsPath: string): Promise<string[]>;
|
|
154
|
+
/**
|
|
155
|
+
* Every `generated column → column it reads` edge in the database.
|
|
156
|
+
*
|
|
157
|
+
* Read from `pg_depend` rather than by matching names in the expression text:
|
|
158
|
+
* a generated column's `pg_attrdef` row carries one `deptype = 'n'` dependency
|
|
159
|
+
* per column its expression references, which is the catalogue's own answer and
|
|
160
|
+
* cannot be fooled by a column name that also appears inside a string literal
|
|
161
|
+
* or as part of a longer identifier.
|
|
162
|
+
*
|
|
163
|
+
* Used by `db push` to find what has to come out of the way before Atlas runs —
|
|
164
|
+
* see `generated-column-conflicts.ts` for why that is necessary at all.
|
|
165
|
+
*/
|
|
166
|
+
export declare function queryGeneratedColumnDependencies(databaseUrl: string): Promise<GeneratedColumnDependency[]>;
|
|
167
|
+
/**
|
|
168
|
+
* Drop the generated columns standing in the way of an apply.
|
|
169
|
+
*
|
|
170
|
+
* Their indexes and their `COMMENT ON COLUMN` stamp go with them, which is
|
|
171
|
+
* exactly right: `applySearchDdl` rebuilds all three from `search.sql` and a
|
|
172
|
+
* surviving stamp would make the rebuilt column look like drift.
|
|
173
|
+
*/
|
|
174
|
+
export declare function dropGeneratedColumns(databaseUrl: string, statements: string[]): Promise<void>;
|
|
153
175
|
/**
|
|
154
176
|
* The generated SQL for the project's `vector` properties, if it has any.
|
|
155
177
|
*
|
|
@@ -180,6 +202,31 @@ export declare function applyVectorDdl(databaseUrl: string, drizzleDir?: string)
|
|
|
180
202
|
* `vector` property, which is every project that has not opted in.
|
|
181
203
|
*/
|
|
182
204
|
export declare function getVectorExcludes(collectionsPath: string): Promise<string[]>;
|
|
205
|
+
/**
|
|
206
|
+
* The generated SQL for the project's `autoValue: "on_update"` properties, if
|
|
207
|
+
* it has any.
|
|
208
|
+
*
|
|
209
|
+
* @param drizzleDir directory holding the generated SQL. Defaults to `drizzle`
|
|
210
|
+
* under the working directory.
|
|
211
|
+
*/
|
|
212
|
+
export declare function readTriggersDdl(drizzleDir?: string): string;
|
|
213
|
+
/**
|
|
214
|
+
* Install the `updated_at` trigger function and bind it to every column that
|
|
215
|
+
* asked for one.
|
|
216
|
+
*
|
|
217
|
+
* Runs *after* Atlas, like {@link applySearchDdl} and {@link applyVectorDdl}:
|
|
218
|
+
* a trigger needs its table and its column to exist. Atlas is told to ignore
|
|
219
|
+
* the triggers ({@link getTriggerExcludes}) because it cannot manage a function
|
|
220
|
+
* at all — its free tier refuses to parse a desired state containing one.
|
|
221
|
+
*
|
|
222
|
+
* A no-op when no property declares `autoValue: "on_update"`. A failure is
|
|
223
|
+
* *not* swallowed: a push that reported success while the trigger never
|
|
224
|
+
* appeared is how `updated_at` ends up silently stale for every writer that is
|
|
225
|
+
* not the driver, which is the whole reason the trigger exists.
|
|
226
|
+
*/
|
|
227
|
+
export declare function applyTriggersDdl(databaseUrl: string, drizzleDir?: string): Promise<void>;
|
|
228
|
+
/** @see getSearchExcludes */
|
|
229
|
+
export declare function getTriggerExcludes(collectionsPath: string): Promise<string[]>;
|
|
183
230
|
/**
|
|
184
231
|
* Query the live database for every user table/view outside the system
|
|
185
232
|
* catalogs. Separated from {@link getTableExcludes} so its failure mode can
|
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { a as __toESM } from "./__vite-browser-external-BnuHet1e.js";
|
|
4
|
-
import {
|
|
4
|
+
import { a as formatForeignGeneratedColumnBanner, c as reportCommandFailure, i as diagnoseDbError, r as diagnoseAtlasFailure, t as checkDatabaseConnectivity } from "./cli-errors-C3g_kHBw.js";
|
|
5
5
|
import { n as outError, r as outWarn, t as out } from "./cli-output-CNdMql-L.js";
|
|
6
|
-
import { C as
|
|
6
|
+
import { A as execa, C as loadCollectionsForCli, D as readTriggersDdl, E as readSearchDdl, O as readVectorDdl, S as getVectorExcludes, T as queryGeneratedColumnDependencies, _ as getDevDatabaseUrl, a as ExcludeIntrospectionError, b as getTableExcludes, c as applyVectorDdl, d as describeReinstallCommand, f as detectProjectPackageManager, g as ensureDevDatabaseExists, h as dropGeneratedColumns, j as forLibpq, k as resolveLocalBin, l as describeBuildScriptRemedy, m as dropDevDatabase, o as applySearchDdl, p as diagnoseMissingBin, r as dropLegacyAuthSchema, s as applyTriggersDdl, t as RLS_BOOTSTRAP_SQL, u as describeDevAddCommand, v as getForeignIndexExcludes, w as promptConfirm, x as getTriggerExcludes, y as getSearchExcludes } from "./rls-bootstrap-sql-BlzsOUtz.js";
|
|
7
7
|
import { t as chalk } from "./source-Br7L7GOI.js";
|
|
8
8
|
import { t as require_arg } from "./arg-Dni7MzLB.js";
|
|
9
9
|
import { logger } from "@rebasepro/server";
|
|
@@ -99,6 +99,177 @@ function decidePushSafety(opts) {
|
|
|
99
99
|
return opts.interactive ? "confirm" : "refuse";
|
|
100
100
|
}
|
|
101
101
|
//#endregion
|
|
102
|
+
//#region src/schema/generated-column-conflicts.ts
|
|
103
|
+
/**
|
|
104
|
+
* Which columns an Atlas plan cannot touch, because a generated column reads
|
|
105
|
+
* them.
|
|
106
|
+
*
|
|
107
|
+
* PostgreSQL refuses `ALTER COLUMN … TYPE` and `DROP COLUMN` on any column a
|
|
108
|
+
* `GENERATED ALWAYS AS … STORED` expression depends on:
|
|
109
|
+
*
|
|
110
|
+
* cannot alter type of a column used by a generated column
|
|
111
|
+
*
|
|
112
|
+
* Atlas cannot see that coming. A search block's `tsvector` is *deliberately*
|
|
113
|
+
* hidden from it (`searchExcludePatterns`) — Rebase owns that column, and an
|
|
114
|
+
* Atlas that could see it would plan a `DROP COLUMN` for it on every push,
|
|
115
|
+
* since the desired state it is given never mentions one. So Atlas plans an
|
|
116
|
+
* alter against a column whose dependant is invisible to it, PostgreSQL
|
|
117
|
+
* refuses, and because `schema apply` runs its plan in a single transaction
|
|
118
|
+
* **every unrelated statement rolls back with it**. One `varchar(255)` → `text`
|
|
119
|
+
* widening on a searched column is enough to make `rebase db push` a no-op
|
|
120
|
+
* forever, with an error that names neither the generated column nor the reason.
|
|
121
|
+
*
|
|
122
|
+
* The fix is the same one the search column's own stamp guard already
|
|
123
|
+
* prescribes when a `search` block changes: drop the generated column, let the
|
|
124
|
+
* apply through, and rebuild it from `search.sql` afterwards. It is cheap to
|
|
125
|
+
* rebuild (one table rewrite, which the `ALTER … TYPE` was going to cost
|
|
126
|
+
* anyway) and there is no other order that works — the expression cannot be
|
|
127
|
+
* altered in place at all.
|
|
128
|
+
*
|
|
129
|
+
* Everything here is side-effect free: the plan is text and the dependencies
|
|
130
|
+
* are rows someone else read. Unit-tested in
|
|
131
|
+
* `generated-column-conflicts.test.ts`.
|
|
132
|
+
*/
|
|
133
|
+
/** `"public"."posts"` / `public.posts` / `posts` → its parts. */
|
|
134
|
+
var IDENT$1 = String.raw`(?:"[^"]+"|[A-Za-z_][A-Za-z0-9_$]*)`;
|
|
135
|
+
var TABLE_RE = new RegExp(String.raw`^ALTER\s+TABLE\s+(?:ONLY\s+)?(${IDENT$1})(?:\.(${IDENT$1}))?`, "i");
|
|
136
|
+
var ALTER_COLUMN_RE = new RegExp(String.raw`\bALTER\s+(?:COLUMN\s+)?(${IDENT$1})\s+(?:SET\s+DATA\s+)?TYPE\b`, "gi");
|
|
137
|
+
var DROP_COLUMN_RE$1 = new RegExp(String.raw`\bDROP\s+COLUMN\s+(?:IF\s+EXISTS\s+)?(${IDENT$1})`, "gi");
|
|
138
|
+
var unquote = (ident) => ident.startsWith("\"") ? ident.slice(1, -1) : ident;
|
|
139
|
+
/**
|
|
140
|
+
* Strip Atlas's plan rendering from a statement.
|
|
141
|
+
*
|
|
142
|
+
* What `schema apply --dry-run` prints is not a SQL file: each statement is
|
|
143
|
+
* indented under a `-- modify "posts" table` heading and prefixed with `-> `,
|
|
144
|
+
* with an `-- ok (12µs)` line after it. `splitSqlStatements` drops the comment
|
|
145
|
+
* lines, and this drops the arrow — without it an anchored `^ALTER TABLE`
|
|
146
|
+
* matches nothing at all, which is a silent no-op rather than an error.
|
|
147
|
+
*/
|
|
148
|
+
var stripPlanMarker = (statement) => statement.replace(/^\s*->\s*/, "").trim();
|
|
149
|
+
/**
|
|
150
|
+
* Every column an Atlas plan retypes or drops, with the table it belongs to.
|
|
151
|
+
*
|
|
152
|
+
* One statement carries many clauses — Atlas emits `ALTER TABLE "public"."posts"
|
|
153
|
+
* ALTER COLUMN "title" TYPE text, ALTER COLUMN "slug" TYPE text, …` — so the
|
|
154
|
+
* table is read once per statement and the clauses are scanned within it.
|
|
155
|
+
*/
|
|
156
|
+
function parseColumnMutations(planSql) {
|
|
157
|
+
const mutations = [];
|
|
158
|
+
for (const raw of splitSqlStatements(planSql)) {
|
|
159
|
+
const statement = stripPlanMarker(raw);
|
|
160
|
+
const table = TABLE_RE.exec(statement);
|
|
161
|
+
if (!table) continue;
|
|
162
|
+
const [schema, name] = table[2] ? [unquote(table[1]), unquote(table[2])] : [void 0, unquote(table[1])];
|
|
163
|
+
const collect = (re, kind) => {
|
|
164
|
+
re.lastIndex = 0;
|
|
165
|
+
let match;
|
|
166
|
+
while ((match = re.exec(statement)) !== null) mutations.push({
|
|
167
|
+
schema,
|
|
168
|
+
table: name,
|
|
169
|
+
column: unquote(match[1]),
|
|
170
|
+
kind
|
|
171
|
+
});
|
|
172
|
+
};
|
|
173
|
+
collect(ALTER_COLUMN_RE, "type");
|
|
174
|
+
collect(DROP_COLUMN_RE$1, "drop");
|
|
175
|
+
}
|
|
176
|
+
return mutations;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The generated columns that block a plan: those reading a column it retypes
|
|
180
|
+
* or drops.
|
|
181
|
+
*
|
|
182
|
+
* A mutation with no schema matches on table name alone. That is deliberately
|
|
183
|
+
* loose — a bare `ALTER TABLE posts` resolves through `search_path` at
|
|
184
|
+
* execution time, and guessing wrong in the *permissive* direction costs a
|
|
185
|
+
* generated column that is rebuilt seconds later, while guessing wrong in the
|
|
186
|
+
* strict direction costs the whole push.
|
|
187
|
+
*/
|
|
188
|
+
function findGeneratedColumnConflicts(mutations, dependencies) {
|
|
189
|
+
const conflicts = /* @__PURE__ */ new Map();
|
|
190
|
+
for (const dependency of dependencies) for (const mutation of mutations) {
|
|
191
|
+
if (mutation.table !== dependency.table) continue;
|
|
192
|
+
if (mutation.schema !== void 0 && mutation.schema !== dependency.schema) continue;
|
|
193
|
+
if (mutation.column !== dependency.dependsOn) continue;
|
|
194
|
+
const key = `${dependency.schema}.${dependency.table}.${dependency.column}`;
|
|
195
|
+
const conflict = conflicts.get(key) ?? {
|
|
196
|
+
schema: dependency.schema,
|
|
197
|
+
table: dependency.table,
|
|
198
|
+
column: dependency.column,
|
|
199
|
+
blocking: []
|
|
200
|
+
};
|
|
201
|
+
if (!conflict.blocking.some((b) => b.column === mutation.column && b.kind === mutation.kind)) conflict.blocking.push({
|
|
202
|
+
column: mutation.column,
|
|
203
|
+
kind: mutation.kind
|
|
204
|
+
});
|
|
205
|
+
conflicts.set(key, conflict);
|
|
206
|
+
}
|
|
207
|
+
const ordered = [...conflicts.values()];
|
|
208
|
+
for (const conflict of ordered) conflict.blocking.sort((a, b) => a.column.localeCompare(b.column));
|
|
209
|
+
return ordered.sort((a, b) => `${a.schema}.${a.table}.${a.column}`.localeCompare(`${b.schema}.${b.table}.${b.column}`));
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Split the conflicts into the ones Rebase can rebuild and the ones it cannot.
|
|
213
|
+
*
|
|
214
|
+
* `managed` is decided by the very list that hid the column from Atlas: a
|
|
215
|
+
* `schema.table.column` exclude pattern means Rebase generated the column and
|
|
216
|
+
* `search.sql` will put it back. Anything else is somebody's hand-written
|
|
217
|
+
* generated column — dropping it would destroy a definition Rebase has no copy
|
|
218
|
+
* of, so it is reported and the push stops instead.
|
|
219
|
+
*/
|
|
220
|
+
function partitionByOwnership(conflicts, excludePatterns) {
|
|
221
|
+
const owned = new Set(excludePatterns);
|
|
222
|
+
const managed = [];
|
|
223
|
+
const foreign = [];
|
|
224
|
+
for (const conflict of conflicts) {
|
|
225
|
+
const target = `${conflict.schema}.${conflict.table}.${conflict.column}`;
|
|
226
|
+
(owned.has(target) ? managed : foreign).push(conflict);
|
|
227
|
+
}
|
|
228
|
+
return {
|
|
229
|
+
managed,
|
|
230
|
+
foreign
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* `ALTER TABLE … DROP COLUMN …` for each conflict, in catalogue order.
|
|
235
|
+
*
|
|
236
|
+
* `ifExists` is for the migration path, where the statement is written now and
|
|
237
|
+
* runs later against a database nobody can inspect: on a fresh one the column
|
|
238
|
+
* does not exist yet (the migration is about to create the table), on a live
|
|
239
|
+
* one it does, and the same file has to survive both.
|
|
240
|
+
*/
|
|
241
|
+
function dropGeneratedColumnStatements(conflicts, opts = {}) {
|
|
242
|
+
const guard = opts.ifExists ? "IF EXISTS " : "";
|
|
243
|
+
return conflicts.map((c) => `ALTER TABLE "${c.schema}"."${c.table}" DROP COLUMN ${guard}"${c.column}";`);
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* The preamble a migration needs when it retypes a column a search block reads.
|
|
247
|
+
*
|
|
248
|
+
* Prepended, because the drop has to precede the `ALTER COLUMN … TYPE` that
|
|
249
|
+
* PostgreSQL would otherwise refuse. The column comes back at the end of the
|
|
250
|
+
* same migration: `db generate` appends `search.sql`, whose
|
|
251
|
+
* `ADD COLUMN IF NOT EXISTS` rebuilds the column, its index and its stamp.
|
|
252
|
+
*/
|
|
253
|
+
function migrationDropPreamble(conflicts) {
|
|
254
|
+
if (conflicts.length === 0) return "";
|
|
255
|
+
return [
|
|
256
|
+
"-- Rebase: generated columns removed so the statements below can run.",
|
|
257
|
+
"-- PostgreSQL refuses to retype or drop a column while a GENERATED",
|
|
258
|
+
"-- ALWAYS AS … STORED expression reads it.",
|
|
259
|
+
...conflicts.map((c) => {
|
|
260
|
+
const reads = c.blocking.map((b) => `${b.column} (${b.kind})`).join(", ");
|
|
261
|
+
return `-- ${describeConflict(c)} reads ${reads}`;
|
|
262
|
+
}),
|
|
263
|
+
"-- The search DDL appended at the end of this migration rebuilds them.",
|
|
264
|
+
...dropGeneratedColumnStatements(conflicts, { ifExists: true }),
|
|
265
|
+
""
|
|
266
|
+
].join("\n");
|
|
267
|
+
}
|
|
268
|
+
/** `public.posts.search_vector`, the way every message here names one. */
|
|
269
|
+
function describeConflict(conflict) {
|
|
270
|
+
return `${conflict.schema}.${conflict.table}.${conflict.column}`;
|
|
271
|
+
}
|
|
272
|
+
//#endregion
|
|
102
273
|
//#region src/schema/carved-out-migration.ts
|
|
103
274
|
/**
|
|
104
275
|
* Keep the objects Rebase carved out of Atlas's view out of the migrations
|
|
@@ -943,7 +1114,11 @@ function latestMigrationVersion() {
|
|
|
943
1114
|
* @returns true when a new migration survives and may be appended to.
|
|
944
1115
|
*/
|
|
945
1116
|
async function stripCarvedOutFromNewestMigration(collectionsPath) {
|
|
946
|
-
const patterns = [
|
|
1117
|
+
const patterns = [
|
|
1118
|
+
...await getSearchExcludes(collectionsPath),
|
|
1119
|
+
...await getVectorExcludes(collectionsPath),
|
|
1120
|
+
...await getTriggerExcludes(collectionsPath)
|
|
1121
|
+
];
|
|
947
1122
|
if (patterns.length === 0) return true;
|
|
948
1123
|
const newest = listMigrationFiles().at(-1);
|
|
949
1124
|
if (!newest) return false;
|
|
@@ -997,7 +1172,7 @@ async function dbCommand(subcommand, rawArgs) {
|
|
|
997
1172
|
return;
|
|
998
1173
|
}
|
|
999
1174
|
if (subcommand === "backup" || subcommand === "restore" || subcommand === "backups") {
|
|
1000
|
-
const { backupCommand, restoreCommand, backupsCommand } = await import("./backup-cli-
|
|
1175
|
+
const { backupCommand, restoreCommand, backupsCommand } = await import("./backup-cli-DSpQyqcG.js");
|
|
1001
1176
|
if (subcommand === "backup" && backupActionOf(rawArgs) === "list") await backupsCommand(rawArgs);
|
|
1002
1177
|
else if (subcommand === "backup") await backupCommand(rawArgs);
|
|
1003
1178
|
else if (subcommand === "restore") await restoreCommand(rawArgs);
|
|
@@ -1054,9 +1229,21 @@ async function dbCommand(subcommand, rawArgs) {
|
|
|
1054
1229
|
}
|
|
1055
1230
|
const searchContent = readSearchDdl();
|
|
1056
1231
|
if (searchContent) {
|
|
1232
|
+
const { searchColumnDependencies } = await import("./generate-postgres-ddl-logic-CR2xcS7e.js").then((n) => n.o);
|
|
1233
|
+
const migrationConflicts = findGeneratedColumnConflicts(parseColumnMutations(migrationContent), searchColumnDependencies(await loadCollectionsForCli(collectionsPath)));
|
|
1234
|
+
const preamble = migrationDropPreamble(migrationConflicts);
|
|
1235
|
+
if (preamble) {
|
|
1236
|
+
migrationContent = `${preamble}\n${migrationContent}`;
|
|
1237
|
+
for (const conflict of migrationConflicts) out(chalk.gray(` ✓ ${describeConflict(conflict)} is dropped and rebuilt inside the migration`));
|
|
1238
|
+
}
|
|
1057
1239
|
migrationContent = `${migrationContent}\n\n${searchContent}`;
|
|
1058
1240
|
out(chalk.gray(" ✓ Appended search DDL to the migration"));
|
|
1059
1241
|
}
|
|
1242
|
+
const triggersContent = readTriggersDdl();
|
|
1243
|
+
if (triggersContent) {
|
|
1244
|
+
migrationContent = `${migrationContent}\n\n${triggersContent}`;
|
|
1245
|
+
out(chalk.gray(" ✓ Appended `updated_at` triggers to the migration"));
|
|
1246
|
+
}
|
|
1060
1247
|
fs.writeFileSync(newestMigrationFile, migrationContent, "utf-8");
|
|
1061
1248
|
const policiesFile = path.resolve(process.cwd(), "drizzle", "policies.sql");
|
|
1062
1249
|
if (fs.existsSync(policiesFile)) {
|
|
@@ -1076,7 +1263,7 @@ async function dbCommand(subcommand, rawArgs) {
|
|
|
1076
1263
|
} catch (err) {
|
|
1077
1264
|
outWarn(chalk.yellow(` ⚠️ Failed to append policies or re-hash migration: ${err instanceof Error ? err.message : String(err)}`));
|
|
1078
1265
|
}
|
|
1079
|
-
if (!wroteNewMigration) out(chalk.gray(" ℹ No migration written — nothing in this change is visible to Atlas.\n Search, vector and RLS DDL are applied by `rebase db push`, and at
|
|
1266
|
+
if (!wroteNewMigration) out(chalk.gray(" ℹ No migration written — nothing in this change is visible to Atlas.\n Search, vector, trigger and RLS DDL are applied by `rebase db push`, and at\n boot by the schema ensure. For a migration-only deployment, add\n drizzle/search.sql, drizzle/vector.sql, drizzle/triggers.sql and\n drizzle/policies.sql to a migration by hand."));
|
|
1080
1267
|
out("");
|
|
1081
1268
|
out(` You can now run ${chalk.bold.green("rebase db migrate")} to apply the migrations to your database.`);
|
|
1082
1269
|
out("");
|
|
@@ -1102,6 +1289,7 @@ async function dbCommand(subcommand, rawArgs) {
|
|
|
1102
1289
|
"--dry-run"
|
|
1103
1290
|
], collectionsPath, { captureStdout: true });
|
|
1104
1291
|
const destructive = detectDestructiveStatements(plan);
|
|
1292
|
+
const { managed: rebuildable, foreign: unowned } = partitionByOwnership(databaseUrl ? findGeneratedColumnConflicts(parseColumnMutations(plan), await queryGeneratedColumnDependencies(databaseUrl)) : [], collectionsPath ? await getSearchExcludes(collectionsPath) : []);
|
|
1105
1293
|
if (dryRun) {
|
|
1106
1294
|
out(chalk.gray(" Step 3/3: --dry-run — nothing was applied."));
|
|
1107
1295
|
out("");
|
|
@@ -1110,6 +1298,14 @@ async function dbCommand(subcommand, rawArgs) {
|
|
|
1110
1298
|
out(chalk.gray(plan.trim().split("\n").map((l) => ` ${l}`).join("\n")));
|
|
1111
1299
|
} else out(chalk.green(" ✓ No changes: the database already matches these collections."));
|
|
1112
1300
|
out("");
|
|
1301
|
+
if (rebuildable.length > 0) {
|
|
1302
|
+
out(chalk.gray(` ${rebuildable.length} generated column(s) would be dropped before the apply and`));
|
|
1303
|
+
out(chalk.gray(" rebuilt from search.sql after it — Postgres cannot retype a column"));
|
|
1304
|
+
out(chalk.gray(" while one reads it:"));
|
|
1305
|
+
for (const conflict of rebuildable) out(chalk.gray(` ${describeConflict(conflict)}`));
|
|
1306
|
+
out("");
|
|
1307
|
+
}
|
|
1308
|
+
if (unowned.length > 0) outWarn(formatForeignGeneratedColumnBanner(unowned));
|
|
1113
1309
|
if (destructive.length > 0) {
|
|
1114
1310
|
outWarn(chalk.yellow(` ⚠️ ${destructive.length} of those DESTROY data:`));
|
|
1115
1311
|
for (const d of destructive) outWarn(chalk.red(` ${d.kind}: `) + chalk.gray(d.statement.replace(/\s+/g, " ")));
|
|
@@ -1121,6 +1317,10 @@ async function dbCommand(subcommand, rawArgs) {
|
|
|
1121
1317
|
out("");
|
|
1122
1318
|
return;
|
|
1123
1319
|
}
|
|
1320
|
+
if (unowned.length > 0) {
|
|
1321
|
+
outError(formatForeignGeneratedColumnBanner(unowned));
|
|
1322
|
+
process.exit(1);
|
|
1323
|
+
}
|
|
1124
1324
|
const allowDestructive = argsList["--allow-destructive"] === true || argsList["--yes"] === true;
|
|
1125
1325
|
const decision = decidePushSafety({
|
|
1126
1326
|
destructiveCount: destructive.length,
|
|
@@ -1147,17 +1347,30 @@ async function dbCommand(subcommand, rawArgs) {
|
|
|
1147
1347
|
}
|
|
1148
1348
|
} else outWarn(chalk.yellow(" Proceeding because --allow-destructive was passed."));
|
|
1149
1349
|
}
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1350
|
+
if (rebuildable.length > 0 && databaseUrl) {
|
|
1351
|
+
for (const conflict of rebuildable) out(chalk.gray(` Dropping ${describeConflict(conflict)} — it reads a column this push retypes.`));
|
|
1352
|
+
await dropGeneratedColumns(databaseUrl, dropGeneratedColumnStatements(rebuildable));
|
|
1353
|
+
}
|
|
1354
|
+
try {
|
|
1355
|
+
await runAtlas("schema", [
|
|
1356
|
+
"apply",
|
|
1357
|
+
"--to",
|
|
1358
|
+
"file://drizzle/schema.sql",
|
|
1359
|
+
"--auto-approve"
|
|
1360
|
+
], collectionsPath);
|
|
1361
|
+
} catch (err) {
|
|
1362
|
+
if (rebuildable.length > 0 && databaseUrl) {
|
|
1363
|
+
out(chalk.gray(" The apply failed — rebuilding the generated columns it needed out of the way."));
|
|
1364
|
+
await applySearchDdl(databaseUrl);
|
|
1365
|
+
}
|
|
1366
|
+
throw err;
|
|
1367
|
+
}
|
|
1156
1368
|
out("");
|
|
1157
1369
|
if (databaseUrl) {
|
|
1158
1370
|
await ensureAuthTables(databaseUrl, collectionsPath);
|
|
1159
1371
|
await applyVectorDdl(databaseUrl);
|
|
1160
1372
|
await applySearchDdl(databaseUrl);
|
|
1373
|
+
await applyTriggersDdl(databaseUrl);
|
|
1161
1374
|
await applyPolicies(databaseUrl);
|
|
1162
1375
|
await reconcilePolicies(databaseUrl, collectionsPath);
|
|
1163
1376
|
await ensureRlsUserRole(databaseUrl);
|
|
@@ -1218,8 +1431,8 @@ async function ensureAuthSchemaAndFunctions(databaseUrl) {
|
|
|
1218
1431
|
async function ensureAuthTables(databaseUrl, collectionsPath) {
|
|
1219
1432
|
try {
|
|
1220
1433
|
const { drizzle } = await import("drizzle-orm/node-postgres");
|
|
1221
|
-
const { ensureAuthTablesExist } = await import("./ensure-tables-
|
|
1222
|
-
const { loadCollections } = await import("./doctor-
|
|
1434
|
+
const { ensureAuthTablesExist } = await import("./ensure-tables-CYMtuuOd.js").then((n) => n.n);
|
|
1435
|
+
const { loadCollections } = await import("./doctor-D5SrGJ5P.js").then((n) => n.t);
|
|
1223
1436
|
const { Client } = await import("pg");
|
|
1224
1437
|
const authCollection = (await loadCollections(path.resolve(process.cwd(), collectionsPath))).find((c) => {
|
|
1225
1438
|
const a = c.auth;
|
|
@@ -1246,7 +1459,7 @@ async function ensureRlsUserRole(databaseUrl) {
|
|
|
1246
1459
|
const schemas = ["public", "rebase"];
|
|
1247
1460
|
let rls;
|
|
1248
1461
|
try {
|
|
1249
|
-
rls = await import("./rls-enforcement-
|
|
1462
|
+
rls = await import("./rls-enforcement-BV12vBwQ.js").then((n) => n.a);
|
|
1250
1463
|
} catch (err) {
|
|
1251
1464
|
outError(chalk.red(`\n ✗ Could not load the RLS provisioning module: ${err instanceof Error ? err.message : String(err)}`));
|
|
1252
1465
|
return;
|
|
@@ -1331,8 +1544,8 @@ async function applyPolicies(databaseUrl) {
|
|
|
1331
1544
|
*/
|
|
1332
1545
|
async function reconcilePolicies(databaseUrl, collectionsPath) {
|
|
1333
1546
|
try {
|
|
1334
|
-
const { checkPolicyDrift, dropOrphanedPolicies, formatPolicyDrift, hasDrift } = await import("./policy-drift-
|
|
1335
|
-
const { loadCollections } = await import("./doctor-
|
|
1547
|
+
const { checkPolicyDrift, dropOrphanedPolicies, formatPolicyDrift, hasDrift } = await import("./policy-drift-B0GDRh7_.js").then((n) => n.a);
|
|
1548
|
+
const { loadCollections } = await import("./doctor-D5SrGJ5P.js").then((n) => n.t);
|
|
1336
1549
|
const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
|
|
1337
1550
|
const { Client } = await import("pg");
|
|
1338
1551
|
const client = new Client({ connectionString: databaseUrl });
|
|
@@ -1414,7 +1627,7 @@ async function branchCommand(rawArgs) {
|
|
|
1414
1627
|
process.exit(1);
|
|
1415
1628
|
}
|
|
1416
1629
|
const { DatabasePoolManager } = await import("./databasePoolManager-Bj5FbeAs.js").then((n) => n.n);
|
|
1417
|
-
const { BranchService } = await import("./BranchService-
|
|
1630
|
+
const { BranchService } = await import("./BranchService-W3DMfcZZ.js").then((n) => n.n);
|
|
1418
1631
|
const { drizzle } = await import("drizzle-orm/node-postgres");
|
|
1419
1632
|
const { Pool } = await import("pg");
|
|
1420
1633
|
const pool = new Pool({
|
|
@@ -1705,6 +1918,7 @@ async function runAtlas(domain, args, collectionsPath, opts = {}) {
|
|
|
1705
1918
|
if (collectionsPath && acceptsExcludeFlag(domain, args)) {
|
|
1706
1919
|
excludes.push(...await getSearchExcludes(collectionsPath));
|
|
1707
1920
|
excludes.push(...await getVectorExcludes(collectionsPath));
|
|
1921
|
+
excludes.push(...await getTriggerExcludes(collectionsPath));
|
|
1708
1922
|
try {
|
|
1709
1923
|
excludes.push(...await getTableExcludes(databaseUrl, collectionsPath));
|
|
1710
1924
|
} catch (err) {
|
|
@@ -1839,8 +2053,8 @@ async function schemaStaleCommand(rawArgs) {
|
|
|
1839
2053
|
const schemaFile = path.resolve(process.cwd(), outputPath);
|
|
1840
2054
|
const fix = Boolean(argsList["--fix"]);
|
|
1841
2055
|
const generatedExists = fs.existsSync(schemaFile);
|
|
1842
|
-
const { loadCollections } = await import("./doctor-
|
|
1843
|
-
const { findLegacyForeignKeyNames, staleVerdict } = await import("./generated-schema-staleness-
|
|
2056
|
+
const { loadCollections } = await import("./doctor-D5SrGJ5P.js").then((n) => n.t);
|
|
2057
|
+
const { findLegacyForeignKeyNames, staleVerdict } = await import("./generated-schema-staleness-DRQe2BpC.js").then((n) => n.r);
|
|
1844
2058
|
let stale = [];
|
|
1845
2059
|
let unreadable;
|
|
1846
2060
|
if (generatedExists) try {
|