@rebasepro/server-postgres 0.29.0 → 0.29.1
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-JiYJ_n9E.js → BranchService-BIIBF5ZL.js} +3 -3
- package/dist/{BranchService-JiYJ_n9E.js.map → BranchService-BIIBF5ZL.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +27 -9
- package/dist/PostgresBootstrapper.d.ts +14 -0
- package/dist/{backup-cli-D_aKXPyX.js → backup-cli-QcOpmRpQ.js} +3 -3
- package/dist/{backup-cli-D_aKXPyX.js.map → backup-cli-QcOpmRpQ.js.map} +1 -1
- package/dist/{boot-ddl-D4W9o9xE.js → boot-ddl-BSNpEUOS.js} +2 -2
- package/dist/{boot-ddl-D4W9o9xE.js.map → boot-ddl-BSNpEUOS.js.map} +1 -1
- package/dist/{cli-console-DPdZCWTi.js → cli-console-DTsm96lW.js} +5 -5
- package/dist/{cli-console-DPdZCWTi.js.map → cli-console-DTsm96lW.js.map} +1 -1
- package/dist/{cli-errors-D8s4z_3g.js → cli-errors-DwqFRIWz.js} +49 -6
- package/dist/{cli-errors-D8s4z_3g.js.map → cli-errors-DwqFRIWz.js.map} +1 -1
- package/dist/cli.js +81 -41
- package/dist/cli.js.map +1 -1
- package/dist/database-preflight-D5JtPt8i.js +151 -0
- package/dist/database-preflight-D5JtPt8i.js.map +1 -0
- package/dist/db-subcommands.d.ts +1 -1
- package/dist/{deferred-index-build-F2GWu009.js → deferred-index-build-B8feKnUj.js} +12 -8
- package/dist/deferred-index-build-B8feKnUj.js.map +1 -0
- package/dist/{doctor-_g2tHRtG.js → doctor-BaR11xUe.js} +6 -6
- package/dist/{doctor-_g2tHRtG.js.map → doctor-BaR11xUe.js.map} +1 -1
- package/dist/{ensure-collection-policies-DUpWJb5D.js → ensure-collection-policies-85HiG-k1.js} +8 -8
- package/dist/{ensure-collection-policies-DUpWJb5D.js.map → ensure-collection-policies-85HiG-k1.js.map} +1 -1
- package/dist/{ensure-collection-tables-BK--gDo6.js → ensure-collection-tables-DR_WcxLA.js} +15 -10
- package/dist/ensure-collection-tables-DR_WcxLA.js.map +1 -0
- package/dist/{ensure-tables-Bx1DYarz.js → ensure-tables-Dh5UP_Zs.js} +4 -4
- package/dist/{ensure-tables-Bx1DYarz.js.map → ensure-tables-Dh5UP_Zs.js.map} +1 -1
- package/dist/{enum-labels-kept-DyFE4Gaq.js → enum-labels-kept-DSU8lAnd.js} +3 -3
- package/dist/{enum-labels-kept-DyFE4Gaq.js.map → enum-labels-kept-DSU8lAnd.js.map} +1 -1
- package/dist/{generate-drizzle-schema-taNTu3xv.js → generate-drizzle-schema-5spbTyQ6.js} +2 -2
- package/dist/{generate-drizzle-schema-taNTu3xv.js.map → generate-drizzle-schema-5spbTyQ6.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js → generate-drizzle-schema-logic-C5FB7Fpo.js} +2 -2
- package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js.map → generate-drizzle-schema-logic-C5FB7Fpo.js.map} +1 -1
- package/dist/{generate-files-DbwU8Btx.js → generate-files-Bl3_D_oP.js} +3 -3
- package/dist/{generate-files-DbwU8Btx.js.map → generate-files-Bl3_D_oP.js.map} +1 -1
- package/dist/{generate-postgres-ddl-logic-ISVgsP34.js → generate-postgres-ddl-logic-BC3JA93M.js} +3 -3
- package/dist/{generate-postgres-ddl-logic-ISVgsP34.js.map → generate-postgres-ddl-logic-BC3JA93M.js.map} +1 -1
- package/dist/{generated-schema-diff-4lOC0g1_.js → generated-schema-diff-Jm93vyJB.js} +12 -4
- package/dist/generated-schema-diff-Jm93vyJB.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.es.js +20 -12
- package/dist/index.es.js.map +1 -1
- package/dist/{migrate-baseline-BeepEphh.js → migrate-baseline-BfHmq3vN.js} +49 -4
- package/dist/{migrate-baseline-BeepEphh.js.map → migrate-baseline-BfHmq3vN.js.map} +1 -1
- package/dist/{migrate-policy-stamps-cYMJ_9Ha.js → migrate-policy-stamps-B4k1ggma.js} +6 -6
- package/dist/{migrate-policy-stamps-cYMJ_9Ha.js.map → migrate-policy-stamps-B4k1ggma.js.map} +1 -1
- package/dist/{open-rebase-CTNBmmH8.js → open-rebase-CiO_sjMT.js} +465 -80
- package/dist/open-rebase-CiO_sjMT.js.map +1 -0
- package/dist/open-rebase.d.ts +6 -1
- package/dist/{pg-error-utils-BLOVXK67.js → pg-error-utils-D1Nc0UML.js} +2 -2
- package/dist/{pg-error-utils-BLOVXK67.js.map → pg-error-utils-D1Nc0UML.js.map} +1 -1
- package/dist/{plan-schema-CMNWvqIa.js → plan-schema-BYxOzflz.js} +89 -9
- package/dist/plan-schema-BYxOzflz.js.map +1 -0
- package/dist/{policy-drift-IjD2AUD-.js → policy-drift-DKuTJHfc.js} +2 -2
- package/dist/{policy-drift-IjD2AUD-.js.map → policy-drift-DKuTJHfc.js.map} +1 -1
- package/dist/{push-index-prebuild-CIvajIrL.js → push-index-prebuild-bqXimSZz.js} +4 -4
- package/dist/{push-index-prebuild-CIvajIrL.js.map → push-index-prebuild-bqXimSZz.js.map} +1 -1
- package/dist/{push-kept-defaults-CLbsuSmo.js → push-kept-defaults-CN9R8cHf.js} +2 -2
- package/dist/{push-kept-defaults-CLbsuSmo.js.map → push-kept-defaults-CN9R8cHf.js.map} +1 -1
- package/dist/{push-legacy-renames-DeW_HTLJ.js → push-legacy-renames-CU_UYPbz.js} +4 -4
- package/dist/{push-legacy-renames-DeW_HTLJ.js.map → push-legacy-renames-CU_UYPbz.js.map} +1 -1
- package/dist/{push-policy-plan--oRXOj4X.js → push-policy-plan-JcyK94bc.js} +4 -4
- package/dist/{push-policy-plan--oRXOj4X.js.map → push-policy-plan-JcyK94bc.js.map} +1 -1
- package/dist/{render-ddl-CzVcbbR1.js → render-ddl-DCdVP-pQ.js} +27 -10
- package/dist/render-ddl-DCdVP-pQ.js.map +1 -0
- package/dist/request-role-cli-DSdRtvgH.js +260 -0
- package/dist/request-role-cli-DSdRtvgH.js.map +1 -0
- package/dist/request-role-cli.d.ts +86 -0
- package/dist/request-role-migration-D9BZ5Uba.js +150 -0
- package/dist/request-role-migration-D9BZ5Uba.js.map +1 -0
- package/dist/rls-enforcement-BO618rnr.js +992 -0
- package/dist/rls-enforcement-BO618rnr.js.map +1 -0
- package/dist/rls-settings-De5NoHHy.js +211 -0
- package/dist/rls-settings-De5NoHHy.js.map +1 -0
- package/dist/schema/doctor-cli.js +144 -6
- package/dist/schema/doctor-cli.js.map +1 -1
- package/dist/schema/doctor-database.d.ts +27 -0
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/introspect-db.js +1 -1
- package/dist/schema/plan/diff-plan.d.ts +6 -1
- package/dist/schema/plan/render-ddl.d.ts +10 -3
- package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
- package/dist/schema/plan/types.d.ts +15 -0
- package/dist/schema/plan/updated-at-trigger.d.ts +1 -1
- package/dist/schema/plan/view-names.d.ts +6 -0
- package/dist/schema/rls-bootstrap-sql.d.ts +23 -0
- package/dist/security/caller-sql-columns.d.ts +60 -0
- package/dist/security/caller-sql.d.ts +8 -0
- package/dist/security/database-preflight.d.ts +24 -0
- package/dist/security/request-role-migration.d.ts +36 -0
- package/dist/security/rls-enforcement.d.ts +191 -21
- package/dist/security/rls-settings.d.ts +177 -0
- package/dist/services/dataService.d.ts +2 -0
- package/dist/services/realtimeService.d.ts +3 -0
- package/dist/services/view-access.d.ts +2 -2
- package/dist/view-names-Dscp6--B.js +24 -0
- package/dist/view-names-Dscp6--B.js.map +1 -0
- package/dist/{websocket-D2y88dOa.js → websocket-B33YjKhs.js} +3 -3
- package/dist/{websocket-D2y88dOa.js.map → websocket-B33YjKhs.js.map} +1 -1
- package/package.json +7 -7
- package/dist/deferred-index-build-F2GWu009.js.map +0 -1
- package/dist/ensure-collection-tables-BK--gDo6.js.map +0 -1
- package/dist/generated-schema-diff-4lOC0g1_.js.map +0 -1
- package/dist/open-rebase-CTNBmmH8.js.map +0 -1
- package/dist/plan-schema-CMNWvqIa.js.map +0 -1
- package/dist/render-ddl-CzVcbbR1.js.map +0 -1
- package/dist/rls-enforcement-jZTv1yci.js +0 -534
- package/dist/rls-enforcement-jZTv1yci.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"push-kept-defaults-
|
|
1
|
+
{"version":3,"file":"push-kept-defaults-CN9R8cHf.js","names":[],"sources":["../src/schema/push-kept-defaults.ts"],"sourcesContent":["/**\n * The DEFAULTs `db push` keeps because a property says the database owns them.\n *\n * `databaseDefault: true` declares a DEFAULT somebody else wrote: a DBA's\n * `now()`, a migration's `'X-' || gen_random_uuid()`. The planner writes no\n * DEFAULT for it, since it has no expression to write, so `schema.sql` holds\n * the column without one. Atlas reads that file as the whole desired state and\n * planned `ALTER COLUMN … DROP DEFAULT`. The API kept letting creates through\n * without the field, and the database then refused them on NOT NULL.\n *\n * Atlas has no way to leave one column's DEFAULT alone: `--exclude` names\n * objects, and a DEFAULT is not one. So the desired state is made to agree with\n * the database instead. Before Atlas plans, the live DEFAULT of each such\n * column is read and appended to `schema.sql` as `ALTER TABLE … SET DEFAULT`,\n * and Atlas finds nothing to change.\n *\n * Two kinds are left out, because Atlas already does something else with them:\n *\n * - a DEFAULT reading a sequence (`nextval(…)`). Atlas does not manage\n * sequences and leaves those DEFAULTs alone, and the sequence does not exist\n * in the scratch database Atlas loads `schema.sql` into.\n * - a DEFAULT calling a function or operator the database defines (an\n * extension's `uuid_generate_v4()`, a project's own function). The scratch\n * database has none of them, and Atlas refuses such a column whether or not\n * it is in `schema.sql`; adding it would only change the error.\n */\nimport { declaredDatabaseExtensions, type CollectionConfig, type Property } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { resolveColumnName } from \"./column-plan-helpers\";\nimport type { Queryable } from \"./ensure-collection-tables\";\n\n/** A column whose DEFAULT the collections leave to the database. */\nexport interface DatabaseOwnedDefaultColumn {\n schema: string;\n table: string;\n column: string;\n}\n\n/** A DEFAULT the database holds for one of those columns, as SQL. */\nexport interface KeptDefault extends DatabaseOwnedDefaultColumn {\n expression: string;\n}\n\n/**\n * Every column declared `databaseDefault: true` that the planner writes no\n * DEFAULT for. An id strategy or `autoValue` writes one of its own, and that\n * one is the planner's to keep.\n */\nexport function databaseOwnedDefaultColumns(collections: CollectionConfig[]): DatabaseOwnedDefaultColumn[] {\n const declared = collections.filter(collection =>\n Object.values(collection.properties ?? {}).some(prop => isDatabaseOwned(prop)));\n if (declared.length === 0) return [];\n\n const plan = planSchema(collections, { databaseExtensions: declaredDatabaseExtensions() });\n const found: DatabaseOwnedDefaultColumn[] = [];\n for (const table of plan.tables) {\n const collection = declared.find(each => each.slug === table.slug);\n if (!collection) continue;\n for (const [key, prop] of Object.entries(collection.properties ?? {})) {\n if (!isDatabaseOwned(prop)) continue;\n const name = resolveColumnName(key, prop);\n const column = table.columns.find(each => each.column === name);\n if (!column || column.default || column.generated) continue;\n found.push({ schema: table.schema, table: table.table, column: name });\n }\n }\n return found;\n}\n\nconst isDatabaseOwned = (prop: unknown): prop is Property =>\n typeof prop === \"object\" && prop !== null &&\n (prop as { databaseDefault?: unknown }).databaseDefault === true;\n\n/**\n * Every column DEFAULT outside the system schemas, and whether Atlas can carry\n * it (see the module comment for the two it cannot).\n *\n * Rendered with only `pg_catalog` on the search path, so anything outside it\n * comes back schema-qualified and reads the same in whichever database\n * `schema.sql` is loaded into.\n */\nconst LIVE_DEFAULTS_SQL = `\n SELECT n.nspname AS \"schema\",\n c.relname AS \"table\",\n a.attname AS \"column\",\n pg_get_expr(d.adbin, d.adrelid) AS \"expression\",\n EXISTS (\n SELECT 1\n FROM pg_depend dep\n WHERE dep.classid = 'pg_attrdef'::regclass\n AND dep.objid = d.oid\n AND (\n (dep.refclassid = 'pg_class'::regclass\n AND EXISTS (SELECT 1 FROM pg_class s WHERE s.oid = dep.refobjid AND s.relkind = 'S'))\n OR (dep.refclassid IN ('pg_proc'::regclass, 'pg_operator'::regclass)\n AND dep.refobjid >= 16384)\n )\n ) AS \"uncarried\"\n FROM pg_attrdef d\n JOIN pg_attribute a ON a.attrelid = d.adrelid AND a.attnum = d.adnum\n JOIN pg_class c ON c.oid = d.adrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE NOT a.attisdropped\n AND a.attgenerated = ''\n AND n.nspname NOT IN ('pg_catalog', 'information_schema')\n AND n.nspname NOT LIKE 'pg\\\\_%'\n`;\n\ninterface LiveDefaultRow extends KeptDefault {\n uncarried: boolean;\n}\n\n/**\n * The live DEFAULTs of `columns` that the desired state must carry so Atlas\n * plans no `DROP DEFAULT`. A column with no DEFAULT, or one Atlas cannot carry,\n * is not listed.\n *\n * Read in a transaction of its own, so the search path it narrows goes back\n * when it ends.\n */\nexport async function readKeptDefaults(client: Queryable, columns: DatabaseOwnedDefaultColumn[]): Promise<KeptDefault[]> {\n if (columns.length === 0) return [];\n const wanted = new Set(columns.map(keyOf));\n let rows: LiveDefaultRow[];\n await client.query(\"BEGIN READ ONLY\");\n try {\n await client.query(\"SET LOCAL search_path TO pg_catalog\");\n rows = (await client.query<LiveDefaultRow>(LIVE_DEFAULTS_SQL)).rows;\n } finally {\n await client.query(\"ROLLBACK\");\n }\n return rows\n .filter(row => wanted.has(keyOf(row)) && !row.uncarried && row.expression)\n .map(({ schema, table, column, expression }) => ({ schema, table, column, expression }))\n .sort((a, b) => keyOf(a).localeCompare(keyOf(b)));\n}\n\nconst keyOf = (column: DatabaseOwnedDefaultColumn): string => `${column.schema}\\u0000${column.table}\\u0000${column.column}`;\n\nconst ident = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\n/** What is appended to `schema.sql`: one `SET DEFAULT` per kept DEFAULT. */\nexport function keptDefaultStatements(kept: KeptDefault[]): string[] {\n return kept.map(({ schema, table, column, expression }) =>\n `ALTER TABLE ${ident(schema)}.${ident(table)} ALTER COLUMN ${ident(column)} SET DEFAULT ${expression};`);\n}\n\n/** `schema.sql` with the kept DEFAULTs appended, under a comment saying why. */\nexport function withKeptDefaults(desiredSql: string, kept: KeptDefault[]): string {\n if (kept.length === 0) return desiredSql;\n return `${desiredSql.replace(/\\s*$/, \"\\n\")}\\n` +\n \"-- DEFAULTs the database holds for columns declared `databaseDefault: true`,\\n\" +\n \"-- read before planning so the push leaves them as they are.\\n\" +\n `${keptDefaultStatements(kept).join(\"\\n\")}\\n`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,4BAA4B,aAA+D;CACvG,MAAM,WAAW,YAAY,QAAO,eAChC,OAAO,OAAO,WAAW,cAAc,CAAC,CAAC,CAAC,CAAC,MAAK,SAAQ,gBAAgB,IAAI,CAAC,CAAC;CAClF,IAAI,SAAS,WAAW,GAAG,OAAO,CAAC;CAEnC,MAAM,OAAO,WAAW,aAAa,EAAE,oBAAoB,2BAA2B,EAAE,CAAC;CACzF,MAAM,QAAsC,CAAC;CAC7C,KAAK,MAAM,SAAS,KAAK,QAAQ;EAC7B,MAAM,aAAa,SAAS,MAAK,SAAQ,KAAK,SAAS,MAAM,IAAI;EACjE,IAAI,CAAC,YAAY;EACjB,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,WAAW,cAAc,CAAC,CAAC,GAAG;GACnE,IAAI,CAAC,gBAAgB,IAAI,GAAG;GAC5B,MAAM,OAAO,kBAAkB,KAAK,IAAI;GACxC,MAAM,SAAS,MAAM,QAAQ,MAAK,SAAQ,KAAK,WAAW,IAAI;GAC9D,IAAI,CAAC,UAAU,OAAO,WAAW,OAAO,WAAW;GACnD,MAAM,KAAK;IAAE,QAAQ,MAAM;IAAQ,OAAO,MAAM;IAAO,QAAQ;GAAK,CAAC;EACzE;CACJ;CACA,OAAO;AACX;AAEA,IAAM,mBAAmB,SACrB,OAAO,SAAS,YAAY,SAAS,QACpC,KAAu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1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
|
-
import { n as planSchema } from "./plan-schema-
|
|
4
|
-
import { s as diffPlanAgainstCatalogue } from "./deferred-index-build-
|
|
5
|
-
import { i as readExistingSchema } from "./ensure-collection-tables-
|
|
3
|
+
import { n as planSchema } from "./plan-schema-BYxOzflz.js";
|
|
4
|
+
import { s as diffPlanAgainstCatalogue } from "./deferred-index-build-B8feKnUj.js";
|
|
5
|
+
import { i as readExistingSchema } from "./ensure-collection-tables-DR_WcxLA.js";
|
|
6
6
|
import { declaredDatabaseExtensions } from "@rebasepro/types";
|
|
7
7
|
//#region src/schema/push-legacy-renames.ts
|
|
8
8
|
/**
|
|
@@ -31,4 +31,4 @@ async function legacyForeignKeyRenames(client, collections) {
|
|
|
31
31
|
//#endregion
|
|
32
32
|
export { legacyForeignKeyRenames };
|
|
33
33
|
|
|
34
|
-
//# sourceMappingURL=push-legacy-renames-
|
|
34
|
+
//# sourceMappingURL=push-legacy-renames-CU_UYPbz.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"push-legacy-renames-
|
|
1
|
+
{"version":3,"file":"push-legacy-renames-CU_UYPbz.js","names":[],"sources":["../src/schema/push-legacy-renames.ts"],"sourcesContent":["/**\n * The relation columns an aged database still holds under the name Rebase\n * derived before 0.13 (`categorie_id`, `people_id`), for `db push` to rename\n * before Atlas plans.\n *\n * Boot renames them losslessly (`diff-plan.ts`, `renameLegacyColumn`). Push\n * runs Atlas, which sees only \"drop `categorie_id`, add `category_id` NOT\n * NULL\": it listed the links as destructive changes to approve, and with\n * `--allow-destructive` dropped them. A pipeline that runs only `db push`\n * could not upgrade an aged database at all. Renaming first — the same\n * metadata-only statement boot runs — leaves Atlas nothing to plan.\n */\nimport { declaredDatabaseExtensions, type CollectionConfig } from \"@rebasepro/types\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { diffPlanAgainstCatalogue, type LegacyForeignKey } from \"./plan/diff-plan\";\nimport { readExistingSchema, type Queryable } from \"./ensure-collection-tables\";\n\nexport interface LegacyRename extends LegacyForeignKey {\n /** `ALTER TABLE … RENAME COLUMN …;` */\n sql: string;\n}\n\nexport async function legacyForeignKeyRenames(client: Queryable, collections: CollectionConfig[]): Promise<LegacyRename[]> {\n const schema = planSchema(collections, { databaseExtensions: declaredDatabaseExtensions() });\n const schemas = Array.from(new Set(schema.tables.map(table => table.schema)));\n const existing = await readExistingSchema(client, schemas, { probeTables: () => [] });\n const plan = diffPlanAgainstCatalogue(schema, existing);\n return plan.legacyForeignKeys.map(legacy => {\n const action = plan.actions.find(a => a.kind === \"rename-column\" && a.target === `${legacy.table}.${legacy.expected}`);\n return { ...legacy, sql: action?.sql ?? \"\" };\n }).filter(rename => rename.sql !== \"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsBA,eAAsB,wBAAwB,QAAmB,aAA0D;CACvH,MAAM,SAAS,WAAW,aAAa,EAAE,oBAAoB,2BAA2B,EAAE,CAAC;CAG3F,MAAM,OAAO,yBAAyB,QAAQ,MADvB,mBAAmB,QAD1B,MAAM,KAAK,IAAI,IAAI,OAAO,OAAO,KAAI,UAAS,MAAM,MAAM,CAAC,CACzB,GAAS,EAAE,mBAAmB,CAAC,EAAE,CAAC,CAC9B;CACtD,OAAO,KAAK,kBAAkB,KAAI,WAAU;EACxC,MAAM,SAAS,KAAK,QAAQ,MAAK,MAAK,EAAE,SAAS,mBAAmB,EAAE,WAAW,GAAG,OAAO,MAAM,GAAG,OAAO,UAAU;EACrH,OAAO;GAAE,GAAG;GAAQ,KAAK,QAAQ,OAAO;EAAG;CAC/C,CAAC,CAAC,CAAC,QAAO,WAAU,OAAO,QAAQ,EAAE;AACzC"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
|
-
import { n as generatePostgresPoliciesDdl } from "./generate-postgres-ddl-logic-
|
|
4
|
-
import { a as parseExpectedPolicies, o as partitionOrphans, t as checkPolicyDrift } from "./policy-drift-
|
|
5
|
-
import { probeRenderedPolicies, readPolicyStamps, tablesRlsWouldEnable } from "./ensure-collection-policies-
|
|
3
|
+
import { n as generatePostgresPoliciesDdl } from "./generate-postgres-ddl-logic-BC3JA93M.js";
|
|
4
|
+
import { a as parseExpectedPolicies, o as partitionOrphans, t as checkPolicyDrift } from "./policy-drift-DKuTJHfc.js";
|
|
5
|
+
import { probeRenderedPolicies, readPolicyStamps, tablesRlsWouldEnable } from "./ensure-collection-policies-85HiG-k1.js";
|
|
6
6
|
//#region src/schema/push-policy-plan.ts
|
|
7
7
|
var keyOf = (p) => `${p.schema}.${p.table}.${p.name}`;
|
|
8
8
|
/** What a stamp that no longer matches says. */
|
|
@@ -124,4 +124,4 @@ async function underSearchPath(client, searchPath, read) {
|
|
|
124
124
|
//#endregion
|
|
125
125
|
export { formatPolicyPushPlan, planPolicyPush, summarizePolicyPushPlan, underSearchPath };
|
|
126
126
|
|
|
127
|
-
//# sourceMappingURL=push-policy-plan
|
|
127
|
+
//# sourceMappingURL=push-policy-plan-JcyK94bc.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"push-policy-plan--oRXOj4X.js","names":[],"sources":["../src/schema/push-policy-plan.ts"],"sourcesContent":["/**\n * What `rebase db push` will do to row-level security, read before it does it.\n *\n * Atlas has no model for a policy: its free tier neither plans nor reads one.\n * So its plan, which was everything `db push --dry-run` showed, never named\n * one. After `schema introspect` on a database whose tables had policies of\n * their own and no admin baseline, the dry run said \"No changes: the database\n * already matches these collections\", and the push then created eight\n * `<table>_default_admin_*` policies that let an admin read and write every\n * row.\n *\n * The plan is the push's own steps, read instead of run:\n *\n * - **RLS switched on:** the tables `lockCollectionTables` switches on\n * ({@link tablesRlsWouldEnable}).\n * - **Policies created and replaced:** `policies.sql`, which DROPs and CREATEs\n * every declared policy, against the database as `checkPolicyDrift` reads\n * it: by name, `TO` list, command, mode and which clauses there are. Text\n * is compared through the stamp the push and every boot write\n * ({@link readPolicyStamps}), which is what catches a rule whose SQL changed\n * under the same name. Where the stamp does not match, or there is none (a\n * policy `db migrate` or a hand made), the policy is made again under a probe\n * name and rolled back ({@link probeRenderedPolicies}): one Postgres would\n * store exactly as it is now is no change. Only one that could not be probed\n * is listed as unstamped.\n * - **Policies dropped and kept:** {@link partitionOrphans}, which is how the\n * push's reconcile step decides.\n */\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport {\n checkPolicyDrift,\n parseExpectedPolicies,\n partitionOrphans,\n type PolicyRef,\n type Queryable\n} from \"../security/policy-drift\";\nimport { generatePostgresPoliciesDdl } from \"./generate-postgres-ddl-logic\";\nimport { probeRenderedPolicies, readPolicyStamps, tablesRlsWouldEnable } from \"./ensure-collection-policies\";\n\nexport interface PolicyPushPlan {\n /** Declared tables in the database with row-level security off, as `schema.table`: the push switches it on. */\n enableRls: string[];\n /** Declared policies the database does not have: the push creates them. */\n create: PolicyRef[];\n /** Declared policies the database has under the same name, defined otherwise: the push replaces them. */\n replace: { policy: PolicyRef; why: string[] }[];\n /** Policies an earlier push generated from a rule edited since: the push drops them. */\n drop: PolicyRef[];\n /** Policies no collection describes, which the push leaves in force. */\n keep: PolicyRef[];\n /** Declared policies the database has with no stamp of Rebase's: re-created from their rules, changed or not. */\n unstamped: PolicyRef[];\n}\n\nconst keyOf = (p: PolicyRef): string => `${p.schema}.${p.table}.${p.name}`;\n\n/** What a stamp that no longer matches says. */\nconst STALE = \"its rule, or the policy itself, has changed since Rebase wrote it\";\n\n/** What a policy with no stamp, whose rule stores something else, says. */\nconst UNSTAMPED_DIFFERS = \"it carries no stamp of Rebase's, and its rule defines it otherwise\";\n\n/**\n * Read the plan.\n *\n * @param options.searchPath the `search_path` the stamps were written under\n * when the connection's own differs — the one `db push` stamps under.\n * See {@link readPolicyStamps}.\n */\nexport async function planPolicyPush(\n client: Queryable,\n collections: CollectionConfig[],\n options: { searchPath?: string } = {}\n): Promise<PolicyPushPlan> {\n const drift = await checkPolicyDrift(client, collections);\n const { dropped, kept } = partitionOrphans(drift, collections);\n const enableRls = await tablesRlsWouldEnable(client, collections);\n const stamps = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, collections));\n\n const replace = drift.diverged.map(d => ({ policy: d.expected, why: d.differences }));\n const settled = new Set([...drift.missing, ...drift.diverged.map(d => d.expected)].map(keyOf));\n const unsure: { policy: PolicyRef; state: \"stale\" | \"unstamped\" }[] = [];\n for (const policy of parseExpectedPolicies(generatePostgresPoliciesDdl(collections))) {\n if (settled.has(keyOf(policy))) continue;\n const state = stamps.get(`${policy.schema}.${policy.table}`)?.get(policy.name);\n if (state === \"stale\" || state === \"unstamped\") unsure.push({ policy, state });\n }\n // What the stamp cannot say, asked of Postgres: would the push store the\n // definition that is there? A policy it would re-create exactly is no change.\n const rendersAsStored = unsure.length === 0\n ? new Map<string, boolean>()\n : await probeRenderedPolicies(client, collections, unsure.map(entry => entry.policy), { searchPath: options.searchPath });\n const unstamped: PolicyRef[] = [];\n for (const { policy, state } of unsure) {\n const same = rendersAsStored.get(keyOf(policy));\n if (same === true) continue;\n if (state === \"stale\") replace.push({ policy, why: [STALE] });\n else if (same === false) replace.push({ policy, why: [UNSTAMPED_DIFFERS] });\n else unstamped.push(policy);\n }\n\n return { enableRls, create: drift.missing, replace, drop: dropped, keep: kept, unstamped };\n}\n\n/** Whether the push would change any row-level security. Kept and unstamped policies are not changes. */\nexport function policyPlanChanges(plan: PolicyPushPlan): boolean {\n return plan.enableRls.length + plan.create.length + plan.replace.length + plan.drop.length > 0;\n}\n\nconst describe = (p: PolicyRef): string => `${p.schema}.${p.table} → \"${p.name}\" (${p.command} TO ${p.roles.join(\", \")})`;\n\n/**\n * The plan as `db push --dry-run` prints it: `changes`, what the push does,\n * and `notes`, what it leaves or cannot tell. Both empty when there is\n * nothing to say.\n */\nexport function formatPolicyPushPlan(plan: PolicyPushPlan): { changes: string[]; notes: string[] } {\n const changes: string[] = [];\n if (policyPlanChanges(plan)) {\n changes.push(\" Planned row-level security changes:\");\n for (const table of plan.enableRls) changes.push(` switch RLS on ${table}`);\n for (const p of plan.create) changes.push(` create policy ${describe(p)}`);\n for (const { policy, why } of plan.replace) changes.push(` replace policy ${describe(policy)}: ${why.join(\"; \")}`);\n for (const p of plan.drop) changes.push(` drop policy ${describe(p)}, left by a rule edited since`);\n }\n\n const notes: string[] = [];\n if (plan.unstamped.length > 0) {\n notes.push(` ${plan.unstamped.length} declared ${plan.unstamped.length === 1 ? \"policy carries\" : \"policies carry\"} ` +\n \"no stamp of Rebase's, so the push re-creates each from its rule\");\n notes.push(\" and cannot tell beforehand whether that changes it:\");\n for (const p of plan.unstamped) notes.push(` ${describe(p)}`);\n }\n if (plan.keep.length > 0) {\n notes.push(\" Policies in the database that no collection describes, which the push leaves in force:\");\n for (const p of plan.keep) notes.push(` ${describe(p)}`);\n }\n return { changes, notes };\n}\n\n/** One line for the push itself: the counts, or `null` when it changes no row-level security. */\nexport function summarizePolicyPushPlan(plan: PolicyPushPlan): string | null {\n if (!policyPlanChanges(plan)) return null;\n const count = (n: number, one: string, many: string): string => `${n} ${n === 1 ? one : many}`;\n const parts = [\n plan.create.length > 0 ? count(plan.create.length, \"policy to create\", \"policies to create\") : \"\",\n plan.replace.length > 0 ? `${plan.replace.length} to replace` : \"\",\n plan.drop.length > 0 ? `${plan.drop.length} to drop` : \"\",\n plan.enableRls.length > 0 ? `RLS to switch on for ${count(plan.enableRls.length, \"table\", \"tables\")}` : \"\"\n ].filter(Boolean);\n return ` Row-level security: ${parts.join(\", \")}. \\`rebase db push --dry-run\\` lists them.`;\n}\n\n/**\n * Run `read` under `searchPath`, set for one transaction and gone after it, or\n * as the connection is when there is none to set.\n */\nexport async function underSearchPath<T>(client: Queryable, searchPath: string | undefined, read: () => Promise<T>): Promise<T> {\n if (!searchPath) return read();\n await client.query(\"BEGIN\");\n try {\n await client.query(`SET LOCAL search_path TO ${searchPath}`);\n const result = await read();\n await client.query(\"CO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[],"sources":["../src/schema/push-policy-plan.ts"],"sourcesContent":["/**\n * What `rebase db push` will do to row-level security, read before it does it.\n *\n * Atlas has no model for a policy: its free tier neither plans nor reads one.\n * So its plan, which was everything `db push --dry-run` showed, never named\n * one. After `schema introspect` on a database whose tables had policies of\n * their own and no admin baseline, the dry run said \"No changes: the database\n * already matches these collections\", and the push then created eight\n * `<table>_default_admin_*` policies that let an admin read and write every\n * row.\n *\n * The plan is the push's own steps, read instead of run:\n *\n * - **RLS switched on:** the tables `lockCollectionTables` switches on\n * ({@link tablesRlsWouldEnable}).\n * - **Policies created and replaced:** `policies.sql`, which DROPs and CREATEs\n * every declared policy, against the database as `checkPolicyDrift` reads\n * it: by name, `TO` list, command, mode and which clauses there are. Text\n * is compared through the stamp the push and every boot write\n * ({@link readPolicyStamps}), which is what catches a rule whose SQL changed\n * under the same name. Where the stamp does not match, or there is none (a\n * policy `db migrate` or a hand made), the policy is made again under a probe\n * name and rolled back ({@link probeRenderedPolicies}): one Postgres would\n * store exactly as it is now is no change. Only one that could not be probed\n * is listed as unstamped.\n * - **Policies dropped and kept:** {@link partitionOrphans}, which is how the\n * push's reconcile step decides.\n */\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport {\n checkPolicyDrift,\n parseExpectedPolicies,\n partitionOrphans,\n type PolicyRef,\n type Queryable\n} from \"../security/policy-drift\";\nimport { generatePostgresPoliciesDdl } from \"./generate-postgres-ddl-logic\";\nimport { probeRenderedPolicies, readPolicyStamps, tablesRlsWouldEnable } from \"./ensure-collection-policies\";\n\nexport interface PolicyPushPlan {\n /** Declared tables in the database with row-level security off, as `schema.table`: the push switches it on. */\n enableRls: string[];\n /** Declared policies the database does not have: the push creates them. */\n create: PolicyRef[];\n /** Declared policies the database has under the same name, defined otherwise: the push replaces them. */\n replace: { policy: PolicyRef; why: string[] }[];\n /** Policies an earlier push generated from a rule edited since: the push drops them. */\n drop: PolicyRef[];\n /** Policies no collection describes, which the push leaves in force. */\n keep: PolicyRef[];\n /** Declared policies the database has with no stamp of Rebase's: re-created from their rules, changed or not. */\n unstamped: PolicyRef[];\n}\n\nconst keyOf = (p: PolicyRef): string => `${p.schema}.${p.table}.${p.name}`;\n\n/** What a stamp that no longer matches says. */\nconst STALE = \"its rule, or the policy itself, has changed since Rebase wrote it\";\n\n/** What a policy with no stamp, whose rule stores something else, says. */\nconst UNSTAMPED_DIFFERS = \"it carries no stamp of Rebase's, and its rule defines it otherwise\";\n\n/**\n * Read the plan.\n *\n * @param options.searchPath the `search_path` the stamps were written under\n * when the connection's own differs — the one `db push` stamps under.\n * See {@link readPolicyStamps}.\n */\nexport async function planPolicyPush(\n client: Queryable,\n collections: CollectionConfig[],\n options: { searchPath?: string } = {}\n): Promise<PolicyPushPlan> {\n const drift = await checkPolicyDrift(client, collections);\n const { dropped, kept } = partitionOrphans(drift, collections);\n const enableRls = await tablesRlsWouldEnable(client, collections);\n const stamps = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, collections));\n\n const replace = drift.diverged.map(d => ({ policy: d.expected, why: d.differences }));\n const settled = new Set([...drift.missing, ...drift.diverged.map(d => d.expected)].map(keyOf));\n const unsure: { policy: PolicyRef; state: \"stale\" | \"unstamped\" }[] = [];\n for (const policy of parseExpectedPolicies(generatePostgresPoliciesDdl(collections))) {\n if (settled.has(keyOf(policy))) continue;\n const state = stamps.get(`${policy.schema}.${policy.table}`)?.get(policy.name);\n if (state === \"stale\" || state === \"unstamped\") unsure.push({ policy, state });\n }\n // What the stamp cannot say, asked of Postgres: would the push store the\n // definition that is there? A policy it would re-create exactly is no change.\n const rendersAsStored = unsure.length === 0\n ? new Map<string, boolean>()\n : await probeRenderedPolicies(client, collections, unsure.map(entry => entry.policy), { searchPath: options.searchPath });\n const unstamped: PolicyRef[] = [];\n for (const { policy, state } of unsure) {\n const same = rendersAsStored.get(keyOf(policy));\n if (same === true) continue;\n if (state === \"stale\") replace.push({ policy, why: [STALE] });\n else if (same === false) replace.push({ policy, why: [UNSTAMPED_DIFFERS] });\n else unstamped.push(policy);\n }\n\n return { enableRls, create: drift.missing, replace, drop: dropped, keep: kept, unstamped };\n}\n\n/** Whether the push would change any row-level security. Kept and unstamped policies are not changes. */\nexport function policyPlanChanges(plan: PolicyPushPlan): boolean {\n return plan.enableRls.length + plan.create.length + plan.replace.length + plan.drop.length > 0;\n}\n\nconst describe = (p: PolicyRef): string => `${p.schema}.${p.table} → \"${p.name}\" (${p.command} TO ${p.roles.join(\", \")})`;\n\n/**\n * The plan as `db push --dry-run` prints it: `changes`, what the push does,\n * and `notes`, what it leaves or cannot tell. Both empty when there is\n * nothing to say.\n */\nexport function formatPolicyPushPlan(plan: PolicyPushPlan): { changes: string[]; notes: string[] } {\n const changes: string[] = [];\n if (policyPlanChanges(plan)) {\n changes.push(\" Planned row-level security changes:\");\n for (const table of plan.enableRls) changes.push(` switch RLS on ${table}`);\n for (const p of plan.create) changes.push(` create policy ${describe(p)}`);\n for (const { policy, why } of plan.replace) changes.push(` replace policy ${describe(policy)}: ${why.join(\"; \")}`);\n for (const p of plan.drop) changes.push(` drop policy ${describe(p)}, left by a rule edited since`);\n }\n\n const notes: string[] = [];\n if (plan.unstamped.length > 0) {\n notes.push(` ${plan.unstamped.length} declared ${plan.unstamped.length === 1 ? \"policy carries\" : \"policies carry\"} ` +\n \"no stamp of Rebase's, so the push re-creates each from its rule\");\n notes.push(\" and cannot tell beforehand whether that changes it:\");\n for (const p of plan.unstamped) notes.push(` ${describe(p)}`);\n }\n if (plan.keep.length > 0) {\n notes.push(\" Policies in the database that no collection describes, which the push leaves in force:\");\n for (const p of plan.keep) notes.push(` ${describe(p)}`);\n }\n return { changes, notes };\n}\n\n/** One line for the push itself: the counts, or `null` when it changes no row-level security. */\nexport function summarizePolicyPushPlan(plan: PolicyPushPlan): string | null {\n if (!policyPlanChanges(plan)) return null;\n const count = (n: number, one: string, many: string): string => `${n} ${n === 1 ? one : many}`;\n const parts = [\n plan.create.length > 0 ? count(plan.create.length, \"policy to create\", \"policies to create\") : \"\",\n plan.replace.length > 0 ? `${plan.replace.length} to replace` : \"\",\n plan.drop.length > 0 ? `${plan.drop.length} to drop` : \"\",\n plan.enableRls.length > 0 ? `RLS to switch on for ${count(plan.enableRls.length, \"table\", \"tables\")}` : \"\"\n ].filter(Boolean);\n return ` Row-level security: ${parts.join(\", \")}. \\`rebase db push --dry-run\\` lists them.`;\n}\n\n/**\n * Run `read` under `searchPath`, set for one transaction and gone after it, or\n * as the connection is when there is none to set.\n */\nexport async function underSearchPath<T>(client: Queryable, searchPath: string | undefined, read: () => Promise<T>): Promise<T> {\n if (!searchPath) return read();\n await client.query(\"BEGIN\");\n try {\n await client.query(`SET LOCAL search_path TO ${searchPath}`);\n const result = await read();\n await client.query(\"COMMIT\");\n return result;\n } catch (err) {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n throw err;\n }\n}\n"],"mappings":";;;;;;AAsDA,IAAM,SAAS,MAAyB,GAAG,EAAE,OAAO,GAAG,EAAE,MAAM,GAAG,EAAE;;AAGpE,IAAM,QAAQ;;AAGd,IAAM,oBAAoB;;;;;;;;AAS1B,eAAsB,eAClB,QACA,aACA,UAAmC,CAAC,GACb;CACvB,MAAM,QAAQ,MAAM,iBAAiB,QAAQ,WAAW;CACxD,MAAM,EAAE,SAAS,SAAS,iBAAiB,OAAO,WAAW;CAC7D,MAAM,YAAY,MAAM,qBAAqB,QAAQ,WAAW;CAChE,MAAM,SAAS,MAAM,gBAAgB,QAAQ,QAAQ,kBAAkB,iBAAiB,QAAQ,WAAW,CAAC;CAE5G,MAAM,UAAU,MAAM,SAAS,KAAI,OAAM;EAAE,QAAQ,EAAE;EAAU,KAAK,EAAE;CAAY,EAAE;CACpF,MAAM,UAAU,IAAI,IAAI,CAAC,GAAG,MAAM,SAAS,GAAG,MAAM,SAAS,KAAI,MAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC;CAC7F,MAAM,SAAgE,CAAC;CACvE,KAAK,MAAM,UAAU,sBAAsB,4BAA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AC,CAAC,OAAO,OACuB,CAAA,CAAM,KAAK,IAAI,EAAE;AACrD;;;;;AAMA,eAAsB,gBAAmB,QAAmB,YAAgC,MAAoC;CAC5H,IAAI,CAAC,YAAY,OAAO,KAAK;CAC7B,MAAM,OAAO,MAAM,OAAO;CAC1B,IAAI;EACA,MAAM,OAAO,MAAM,4BAA4B,YAAY;EAC3D,MAAM,SAAS,MAAM,KAAK;EAC1B,MAAM,OAAO,MAAM,QAAQ;EAC3B,OAAO;CACX,SAAS,KAAK;EACV,MAAM,OAAO,MAAM,UAAU,CAAC,CAAC,YAAY,KAAA,CAAS;EACpD,MAAM;CACV;AACJ"}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { c as searchColumnDefinition, f as searchExtensionStatements, g as searchStampGuards, h as searchIndexStatements, m as searchIndexNames, o as fuzzyColumnDefinition, p as searchHelperFunctions, u as searchColumnStamps } from "./search-column-BM-GV6vH.js";
|
|
4
|
+
import { n as VIEW_ROWS_COMMENT_PREFIX, r as viewRowsName } from "./view-names-Dscp6--B.js";
|
|
4
5
|
import { a as vectorDimensionGuard, c as vectorExtensionStatement, d as vectorIndexStatements, i as vectorColumnDefinition, l as vectorIndexNames, o as vectorExtensionDeclared, t as VECTOR_EXTENSION_OPT_IN } from "./vector-index-DsQ3V2d2.js";
|
|
5
6
|
import { o as atlasExcludePattern, u as collectionIndexStatements } from "./source-fZb92pN8.js";
|
|
6
|
-
import { a as triggerStatements, r as quoteSqlLiteral } from "./plan-schema-
|
|
7
|
+
import { a as triggerStatements, r as quoteSqlLiteral } from "./plan-schema-BYxOzflz.js";
|
|
8
|
+
import { REBASE_USER_ROLE } from "@rebasepro/common";
|
|
7
9
|
//#region src/schema/plan/render-ddl.ts
|
|
8
10
|
/**
|
|
9
11
|
* The SQL files, rendered from a {@link SchemaPlan}.
|
|
@@ -338,7 +340,8 @@ function renderTriggersDdl(plan) {
|
|
|
338
340
|
if (tables.length === 0) return "";
|
|
339
341
|
let ddl = "-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\n";
|
|
340
342
|
ddl += "--\n";
|
|
341
|
-
ddl += "-- `updated_at` triggers, for the properties declaring `autoValue: \"on_update\"
|
|
343
|
+
ddl += "-- `updated_at` triggers, for the properties declaring `autoValue: \"on_update\"`,\n";
|
|
344
|
+
ddl += "-- and the triggers that keep a row in its tenant.\n";
|
|
342
345
|
ddl += "-- Applied by Rebase, not by Atlas — a trigger is a function plus a binding,\n";
|
|
343
346
|
ddl += "-- and Atlas's free tier refuses to parse a desired state containing one.\n\n";
|
|
344
347
|
for (const statement of plan.functions.filter(isTriggerFunction)) ddl += `${statement}\n\n`;
|
|
@@ -365,16 +368,27 @@ function dollarTag(text) {
|
|
|
365
368
|
/**
|
|
366
369
|
* The statements that create one view as planned, comment included, for
|
|
367
370
|
* `EXECUTE`. A plain view runs as the caller (`security_invoker`), so the
|
|
368
|
-
* policies of the tables it reads decide what each caller sees
|
|
369
|
-
*
|
|
370
|
-
*
|
|
371
|
+
* policies of the tables it reads decide what each caller sees.
|
|
372
|
+
*
|
|
373
|
+
* A materialized view is two objects (see `view-names.ts`): its rows, stored
|
|
374
|
+
* under {@link viewRowsName} with a unique index on the id columns (which
|
|
375
|
+
* `REFRESH … CONCURRENTLY` needs), and the gate under the collection's name —
|
|
376
|
+
* a `security_barrier` view that reads them with the owner's rights and serves
|
|
377
|
+
* them to the collection's roles and to the server (no uid). It reads the
|
|
378
|
+
* settings directly rather than through `rebase.roles()`, which a first boot
|
|
379
|
+
* creates after the views. It carries each row's `xmin`, for `fingerprint()`;
|
|
380
|
+
* the catalogue reader leaves that column out of the collection.
|
|
371
381
|
*/
|
|
372
382
|
function viewCreateStatements(view) {
|
|
373
383
|
const qualified = `${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`;
|
|
374
|
-
|
|
375
|
-
const
|
|
376
|
-
|
|
377
|
-
statements
|
|
384
|
+
if (!view.materialized) return [`CREATE VIEW ${qualified} WITH (security_invoker = true) AS\n${view.query}`, `COMMENT ON VIEW ${qualified} IS '${viewComment(view)}'`];
|
|
385
|
+
const stored = `${quoteIdentifier(view.schema)}.${quoteIdentifier(viewRowsName(view.name))}`;
|
|
386
|
+
const roles = view.roles.map((role) => `'${role.replace(/'/g, "''")}'`).join(", ");
|
|
387
|
+
const statements = [`CREATE MATERIALIZED VIEW ${stored} AS\n${view.query}\nWITH DATA`];
|
|
388
|
+
if (view.idColumns.length > 0) statements.push(`CREATE UNIQUE INDEX ${quoteIdentifier(`${view.name}_rebase_id`)} ON ${stored} (${view.idColumns.map(quoteIdentifier).join(", ")})`);
|
|
389
|
+
statements.push(...view.indexes);
|
|
390
|
+
statements.push(`COMMENT ON MATERIALIZED VIEW ${stored} IS '${VIEW_ROWS_COMMENT_PREFIX}${view.hash}'`, `REVOKE ALL ON ${stored} FROM PUBLIC`, `CREATE VIEW ${qualified} WITH (security_barrier = true) AS\nSELECT rows.*, rows.xmin AS xmin FROM ${stored} rows\nWHERE NULLIF(current_setting('app.uid', true), '') IS NULL
|
|
391
|
+
OR string_to_array(COALESCE(current_setting('app.user_roles', true), ''), ',') && ARRAY[${roles || "NULL"}]::text[]`, `COMMENT ON VIEW ${qualified} IS '${viewComment(view)}'`);
|
|
378
392
|
return statements;
|
|
379
393
|
}
|
|
380
394
|
/**
|
|
@@ -417,11 +431,14 @@ function renderViewsDdl(plan) {
|
|
|
417
431
|
ddl += " END IF;\n";
|
|
418
432
|
}
|
|
419
433
|
for (const view of plan.views) {
|
|
434
|
+
const rows = `${quoteIdentifier(view.schema)}.${quoteIdentifier(viewRowsName(view.name))}`;
|
|
420
435
|
ddl += ` IF ${regclass(view)} IS NULL THEN\n`;
|
|
436
|
+
if (view.materialized) ddl += ` IF to_regclass(${literal(rows)}) IS NOT NULL THEN EXECUTE ${literal(`DROP MATERIALIZED VIEW ${rows}`)}; END IF;\n`;
|
|
421
437
|
for (const statement of viewCreateStatements(view)) {
|
|
422
438
|
const tag = dollarTag(statement);
|
|
423
439
|
ddl += ` EXECUTE ${tag}${statement}${tag};\n`;
|
|
424
440
|
}
|
|
441
|
+
if (view.materialized) ddl += ` IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(REBASE_USER_ROLE)}) THEN EXECUTE ${literal(`REVOKE ALL ON ${rows} FROM ${REBASE_USER_ROLE}`)}; END IF;\n`;
|
|
425
442
|
ddl += " END IF;\n";
|
|
426
443
|
}
|
|
427
444
|
ddl += "END\n$rebase_views$;\n";
|
|
@@ -430,4 +447,4 @@ function renderViewsDdl(plan) {
|
|
|
430
447
|
//#endregion
|
|
431
448
|
export { renderPoliciesDdl as a, renderPrimaryKeyConstraint as c, renderVectorDdl as d, renderViewsDdl as f, vectorExcludePatternsOf as h, renderPgType as i, renderSearchDdl as l, triggerExcludePatternsOf as m, renderDenyingPolicyStatements as n, renderPolicyStatements as o, searchExcludePatternsOf as p, renderEnableRls as r, renderPostgresDdl as s, renderColumnDefinition as t, renderTriggersDdl as u };
|
|
432
449
|
|
|
433
|
-
//# sourceMappingURL=render-ddl-
|
|
450
|
+
//# sourceMappingURL=render-ddl-DCdVP-pQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"render-ddl-DCdVP-pQ.js","names":[],"sources":["../src/schema/plan/render-ddl.ts"],"sourcesContent":["/**\n * The SQL files, rendered from a {@link SchemaPlan}.\n *\n * Four files, because Atlas owns exactly one of them:\n *\n * - `schema.sql` — the desired state Atlas diffs the database against.\n * - `policies.sql` — the RLS policies. Atlas has no model for a policy.\n * - `search.sql` — the generated `tsvector` column, its GIN index and the\n * IMMUTABLE helpers its expression calls. Atlas's free tier refuses to\n * *parse* a file containing a function, and it wipes the dev database it\n * diffs against, so a helper seeded there is gone by the time the plan runs.\n * - `vector.sql` — the `vector` columns and their ANN indexes. Atlas cannot\n * *execute* these: it materialises `schema.sql` in a dev database that is\n * created empty and emptied again on every run, so `VECTOR(384)` resolves\n * against a database that structurally cannot have pgvector.\n * - `triggers.sql` — `autoValue: \"on_update\"`, which is a function plus a\n * binding, so it is out for the same reason search is.\n *\n * Everything not in `schema.sql` is excluded from Atlas's view by pattern\n * (`…ExcludePatterns` below) and applied by Rebase — at push time by the CLI,\n * at boot by the schema ensure. Without the excludes a desired state that omits\n * an object reads to Atlas as an instruction to drop it.\n */\nimport {\n fuzzyColumnDefinition,\n searchColumnDefinition,\n searchColumnStamps,\n searchExtensionStatements,\n searchHelperFunctions,\n searchIndexNames,\n searchIndexStatements,\n searchStampGuards\n} from \"../search-column\";\nimport {\n VECTOR_EXTENSION_OPT_IN,\n vectorColumnDefinition,\n vectorDimensionGuard,\n vectorExtensionDeclared,\n vectorExtensionStatement,\n vectorIndexNames,\n vectorIndexStatements\n} from \"../vector-index\";\nimport { atlasExcludePattern } from \"../atlas-exclude\";\nimport { collectionIndexStatements } from \"../collection-index\";\nimport { quoteSqlLiteral } from \"./plan-schema\";\nimport { triggerStatements } from \"./updated-at-trigger\";\nimport { VIEW_ROWS_COMMENT_PREFIX, viewRowsName } from \"./view-names\";\nimport { REBASE_USER_ROLE } from \"@rebasepro/common\";\nimport type { ColumnPlan, PgType, PolicyPlan, SchemaPlan, TablePlan, ViewPlan } from \"./types\";\n\n/** What `schema.sql` may leave out, because another file owns it. */\nexport interface DdlRenderOptions {\n /** RLS policies. `false` puts them in `policies.sql` alone. */\n includePolicies?: boolean;\n /** The search column, its helpers and its index. See `search.sql`. */\n includeSearch?: boolean;\n /** The vector columns and their ANN indexes. See `vector.sql`. */\n includeVector?: boolean;\n}\n\n/**\n * A {@link PgType} as Postgres spells it.\n *\n * The one place. `getSqlColumnType` and `getDrizzleColumn` each carried their\n * own ladder and disagreed about `VARCHAR` widths, about `geopoint`, and about\n * whether an `increment` id honours `columnType`.\n */\nexport const renderPgType = (type: PgType): string => {\n switch (type.kind) {\n case \"text\": return \"TEXT\";\n case \"varchar\": return `VARCHAR(${type.length})`;\n case \"char\": return `CHAR(${type.length})`;\n case \"uuid\": return \"UUID\";\n case \"enum\": return `\"${type.schema}\".\"${type.name}\"`;\n case \"smallint\": return \"SMALLINT\";\n case \"integer\": return \"INTEGER\";\n case \"bigint\": return \"BIGINT\";\n case \"smallserial\": return \"SMALLSERIAL\";\n case \"serial\": return \"SERIAL\";\n case \"bigserial\": return \"BIGSERIAL\";\n case \"real\": return \"REAL\";\n case \"doublePrecision\": return \"DOUBLE PRECISION\";\n case \"numeric\":\n if (type.precision === undefined) return \"NUMERIC\";\n return type.scale === undefined\n ? `NUMERIC(${type.precision})`\n : `NUMERIC(${type.precision}, ${type.scale})`;\n case \"boolean\": return \"BOOLEAN\";\n case \"timestamptz\": return \"TIMESTAMP WITH TIME ZONE\";\n case \"date\": return \"DATE\";\n case \"time\": return \"TIME\";\n case \"json\": return \"JSON\";\n case \"jsonb\": return \"JSONB\";\n case \"vector\": return `VECTOR(${type.dimensions})`;\n case \"bytea\": return \"BYTEA\";\n case \"tsvector\": return \"tsvector\";\n case \"array\": return `${renderPgType(type.of)}[]`;\n }\n};\n\n/**\n * Everything after the column name, in one order for every SQL emitter.\n *\n * `CREATE TABLE` and `ADD COLUMN` used to assemble this separately, which is\n * how a required relation column came out `NOT NULL` after `db push` and\n * nullable after a boot-ensure. `identity` is part of the type rather than a\n * DEFAULT, which is why it is rendered here and not in the DEFAULT slot.\n */\nexport const renderColumnDefinition = (column: ColumnPlan): string => {\n // `auth-users-columns` is the single description of what an auth user\n // table's columns must be, and it hands over a rendered definition.\n if (column.sqlDefinition) return column.sqlDefinition;\n\n if (column.generated) {\n return `${renderPgType(column.type)} GENERATED ALWAYS AS (${column.generated.expression}) STORED`;\n }\n\n let definition = renderPgType(column.type);\n if (column.default?.kind === \"identity\") definition += \" GENERATED BY DEFAULT AS IDENTITY\";\n if (column.primaryKey) definition += \" PRIMARY KEY\";\n if (column.unique) definition += \" UNIQUE\";\n if (column.default && column.default.kind !== \"identity\") {\n definition += ` DEFAULT ${column.default.kind === \"sql\" ? column.default.expression : column.default.sql}`;\n }\n if (!column.nullable && !column.primaryKey) definition += \" NOT NULL\";\n return definition;\n};\n\n/**\n * `PRIMARY KEY (\"a\", \"b\")`, the clause a composite key takes inside a\n * `CREATE TABLE`. Shared by `schema.sql` and boot-ensure's `CREATE TABLE`, so\n * the two cannot list the columns differently.\n */\nexport const renderPrimaryKeyConstraint = (table: Pick<TablePlan, \"primaryKey\">): string =>\n `PRIMARY KEY (${table.primaryKey.map(c => `\"${c}\"`).join(\", \")})`;\n\n/** `\"col\" TYPE …`, as it appears inside a `CREATE TABLE`. */\nconst renderColumn = (column: ColumnPlan): string =>\n `\"${column.column}\" ${renderColumnDefinition(column)}`;\n\n// ── Policies ─────────────────────────────────────────────────────────────────\n\n/**\n * One policy as its `DROP` / `CREATE` pair — each a complete statement.\n *\n * This is the primitive the boot-time RLS applier runs one statement at a time\n * (the runtime's DB handle speaks the extended query protocol, which forbids\n * multiple commands in one execute), while `db push` writes the joined string.\n */\nexport const renderPolicyStatements = (\n table: Pick<TablePlan, \"schema\" | \"table\">,\n policy: PolicyPlan\n): string[] => {\n const target = `\"${table.schema}\".\"${table.table}\"`;\n let create = `CREATE POLICY \"${policy.name}\" ON ${target} AS ${policy.mode.toUpperCase()} ` +\n `FOR ${policy.operation.toUpperCase()} TO ${policy.roles.map(r => `\"${r}\"`).join(\", \")}`;\n if (policy.using) create += ` USING (${policy.using})`;\n if (policy.withCheck) create += ` WITH CHECK (${policy.withCheck})`;\n // The one policy an older naming stored this rule's operations under —\n // see `PolicyPlan.supersedes`. In the same per-table transaction, so a\n // request sees the old policy or the new ones, never neither.\n const superseded = (policy.supersedes ?? []).map(name => `DROP POLICY IF EXISTS \"${name}\" ON ${target};`);\n return [...superseded, `DROP POLICY IF EXISTS \"${policy.name}\" ON ${target};`, `${create};`];\n};\n\n/**\n * A restrictive policy, under its own name, command and roles, that passes no\n * row: `USING (false)` / `WITH CHECK (false)` for the clauses its command takes.\n *\n * What the boot applier puts in place of a restrictive policy whose own\n * `CREATE` failed. A restrictive policy is a gate ANDed over every permissive\n * one, so its absence does not deny — it opens whatever the permissive policies\n * grant. Standing in for it with a gate nothing passes keeps the failure on\n * the denying side until the rule can be created.\n */\nexport const renderDenyingPolicyStatements = (\n table: Pick<TablePlan, \"schema\" | \"table\">,\n policy: PolicyPlan\n): string[] => {\n const target = `\"${table.schema}\".\"${table.table}\"`;\n let create = `CREATE POLICY \"${policy.name}\" ON ${target} AS RESTRICTIVE ` +\n `FOR ${policy.operation.toUpperCase()} TO ${policy.roles.map(r => `\"${r}\"`).join(\", \")}`;\n if (policy.operation !== \"insert\") create += \" USING (false)\";\n if (policy.operation !== \"select\" && policy.operation !== \"delete\") create += \" WITH CHECK (false)\";\n return [`DROP POLICY IF EXISTS \"${policy.name}\" ON ${target};`, `${create};`];\n};\n\n/** `ALTER TABLE … ENABLE ROW LEVEL SECURITY;` — every generated table is locked. */\nexport const renderEnableRls = (table: Pick<TablePlan, \"schema\" | \"table\">): string =>\n `ALTER TABLE \"${table.schema}\".\"${table.table}\" ENABLE ROW LEVEL SECURITY;`;\n\nconst statementsToDdl = (statements: string[]): string => statements.map(s => `${s}\\n`).join(\"\");\n\n// ── schema.sql ───────────────────────────────────────────────────────────────\n\nexport function renderPostgresDdl(plan: SchemaPlan, options: DdlRenderOptions = {}): string {\n const includePolicies = options.includePolicies !== false;\n const includeSearch = options.includeSearch !== false;\n const includeVector = options.includeVector !== false;\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\\n\";\n\n // 1. Custom schemas.\n //\n // `rebase` is unconditional and load-bearing. The RLS helper functions live\n // in it, so the migration preamble creates it — which puts it in Atlas's\n // replayed state, and anything in that state but absent from this desired\n // schema gets a `DROP SCHEMA … CASCADE` planned against it. That would take\n // the auth tables.\n plan.schemas.forEach(schema => { ddl += `CREATE SCHEMA IF NOT EXISTS \"${schema}\";\\n`; });\n if (plan.schemas.length > 0) ddl += \"\\n\";\n\n // 1b. Search support, for collections that opted in.\n //\n // Extensions and helper functions come before every CREATE TABLE because a\n // generated column's expression is resolved at creation time: a table whose\n // search column calls `rebase_search_text` cannot be created before that\n // function exists. Both are `IF NOT EXISTS` / `OR REPLACE`, so a file\n // replayed against a live database is a no-op here.\n const searchTables = plan.tables.filter(t => t.search);\n if (searchTables.length > 0) {\n if (!includeSearch) {\n ddl += \"-- Full-text search support lives in `search.sql`, applied separately.\\n\\n\";\n } else {\n const extensions = Array.from(new Set(searchTables.flatMap(t => searchExtensionStatements(t.search!))));\n const helpers = Array.from(new Set(searchTables.flatMap(t => searchHelperFunctions(t.search!))));\n ddl += \"-- Full-text search support (collections declaring a `search` block)\\n\";\n extensions.forEach(s => { ddl += `${s}\\n`; });\n if (extensions.length > 0) ddl += \"\\n\";\n helpers.forEach(s => { ddl += `${s}\\n\\n`; });\n }\n }\n\n // 1c. Vector support. Only ever a note, never a statement — unlike 1b.\n // `CREATE EXTENSION vector` is the one thing this file must never carry\n // whichever way the flag goes: Atlas rejects an extension in a desired\n // state as a paid feature.\n if (!includeVector && plan.tables.some(t => t.vectorColumns.length > 0)) {\n ddl += \"-- Vector columns and their ANN indexes live in `vector.sql`, applied separately.\\n\\n\";\n }\n\n // 1d. `autoValue: \"on_update\"`. A trigger is a function plus a binding, so\n // it is out of Atlas's sight for the reason search is — and out\n // unconditionally, because `schema.sql` has no flag that would make Atlas\n // able to read one.\n if (plan.tables.some(t => t.triggers.length > 0)) {\n ddl += \"-- `autoValue: \\\"on_update\\\"` triggers live in `triggers.sql`, applied separately.\\n\\n\";\n }\n\n // 2. Enum types.\n plan.enums.forEach(enumPlan => {\n ddl += `CREATE TYPE \"${enumPlan.schema}\".\"${enumPlan.name}\" AS ENUM (${enumPlan.labels.map(quoteSqlLiteral).join(\", \")});\\n`;\n });\n if (ddl.endsWith(\";\\n\")) ddl += \"\\n\";\n\n // 3. Tables, in the plan's order — each collection, then any junction its\n // relations imply.\n const fkStatements: string[] = [];\n // Indexes follow the tables for the same reason the FK constraints do: the\n // table has to exist first.\n const indexStatements: string[] = [];\n // Policies are emitted after every CREATE TABLE, like the FK constraints: a\n // policy may reference other tables (a junction's derived policies always\n // reference both endpoints; `policy.existsIn` references a join table), and\n // CREATE POLICY validates those relations at creation time.\n const policyStatements: string[] = [];\n\n for (const table of plan.tables) {\n const emitted = table.columns.filter(column => {\n // A vector column is not Atlas's — `vector.sql` adds it. Filtered\n // here rather than upstream so the column keeps its place in the\n // generator's order when it *is* included, which is what the\n // derived-names contract renders.\n if (!includeVector && column.type.kind === \"vector\") return false;\n if (!includeSearch && column.source.kind === \"search\") return false;\n // A declared property already emits this column (an explicit\n // `postId` beside the `belongsTo` that uses it); the relation\n // contributes only the constraint.\n if (column.columnOwnedByProperty) return false;\n return true;\n });\n\n ddl += `CREATE TABLE \"${table.schema}\".\"${table.table}\" (\\n`;\n const lines = emitted.map(column => ` ${renderColumn(column)}`);\n // A key over several columns — a junction's two endpoints, or a\n // collection with several `isId` properties — is one table constraint;\n // a single-column key is already inline on its column.\n if (table.primaryKey.length > 1) {\n lines.push(` ${renderPrimaryKeyConstraint(table)}`);\n }\n ddl += lines.join(\",\\n\");\n ddl += \"\\n);\\n\\n\";\n\n for (const column of table.columns) {\n if (column.foreignKey) fkStatements.push(`${column.foreignKey.sql};`);\n }\n\n if (includeSearch && table.search) {\n indexStatements.push(...searchIndexStatements(table.search));\n }\n // ANN indexes are emitted with the other indexes rather than inline,\n // because `CREATE INDEX` is a statement and a column definition is not\n // — and because a column too wide for pgvector to index still needs its\n // column. Absent alongside their column when vector is carved out.\n if (includeVector && table.vector) {\n indexStatements.push(...vectorIndexStatements(table.vector));\n for (const skip of table.vector.skipped) {\n indexStatements.push(`-- No ANN index on \"${skip.schema}\".\"${skip.table}\".\"${skip.column}\": ${skip.reason}`);\n }\n }\n // The collection's own `indexes:` block. Last of the three index\n // producers, and the only one the developer wrote deliberately rather\n // than getting as a side effect of another feature.\n indexStatements.push(...collectionIndexStatements(table.indexes));\n\n if (includePolicies) {\n // No FORCE: authenticated requests run as the non-owner\n // `rebase_user` role, which plain ENABLE already binds. The owner\n // (server context) must bypass — it is the trusted plane.\n ddl += `${renderEnableRls(table)}\\n`;\n ddl += \"\\n\";\n for (const policy of table.policies) {\n policyStatements.push(statementsToDdl(renderPolicyStatements(table, policy)));\n }\n }\n }\n\n // Indexes before foreign keys. Today every FK targets a primary key created\n // inline, so the order is safe by accident; the moment a declared\n // `unique: true` index can back an FK target, a constraint emitted first\n // would reference an index that does not exist yet.\n if (indexStatements.length > 0) {\n ddl += \"-- Indexes\\n\";\n ddl += indexStatements.join(\"\\n\") + \"\\n\\n\";\n }\n\n if (fkStatements.length > 0) {\n ddl += \"-- Foreign Key Constraints\\n\";\n ddl += fkStatements.join(\"\\n\") + \"\\n\\n\";\n }\n\n if (policyStatements.length > 0) {\n ddl += \"-- Row Level Security Policies\\n\";\n ddl += policyStatements.join(\"\");\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n// ── policies.sql ─────────────────────────────────────────────────────────────\n\nexport function renderPoliciesDdl(plan: SchemaPlan): string {\n let ddl = \"-- This file contains RLS policies generated by Rebase. Applied separately from migrations.\\n\\n\";\n\n // Collections first, then the junctions no collection declares — the order\n // the boot-time applier plans them in.\n for (const table of plan.tables.filter(t => t.kind === \"collection\")) {\n ddl += `${renderEnableRls(table)}\\n`;\n ddl += \"\\n\";\n if (table.policies.length === 0) continue;\n let announced: string | undefined;\n for (const policy of table.policies) {\n // Say which policies the author did not write. They are permissive,\n // so they OR with the declared rules and widen the final ACL beyond\n // what `securityRules` reads like — and re-appear after any manual\n // DROP, because a push asserts the declared state. Once per *rule*:\n // one rule with four operations is one thing the author did not\n // write, not four.\n if (policy.injected && policy.ruleKey !== announced) {\n ddl += \"-- Injected by Rebase (not from this collection's securityRules).\\n\";\n ddl += `-- Set \\`disableDefaultPolicies: true\\` on \"${table.slug}\" to drop these and own its RLS outright.\\n`;\n }\n announced = policy.ruleKey;\n ddl += statementsToDdl(renderPolicyStatements(table, policy));\n }\n ddl += \"\\n\";\n }\n\n for (const table of plan.tables.filter(t => t.kind === \"junction\")) {\n ddl += `${renderEnableRls(table)}\\n`;\n ddl += \"\\n\";\n if (table.policies.length === 0) continue;\n const declaringSlugs = (table.declaringSlugs ?? []).join('\", \"');\n ddl += `-- Derived by Rebase for the junction \"${table.table}\" (no collection declares it).\\n`;\n ddl += \"-- Reads require both endpoint rows to be visible; writes follow the update\\n\";\n ddl += `-- rules of \"${declaringSlugs}\". Set \\`disableDefaultPolicies: true\\` on the\\n`;\n ddl += \"-- declaring collection(s) to drop these and police the junction yourself.\\n\";\n for (const policy of table.policies) {\n ddl += statementsToDdl(renderPolicyStatements(table, policy));\n }\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n// ── search.sql ───────────────────────────────────────────────────────────────\n\nexport function renderSearchDdl(plan: SchemaPlan): string {\n const tables = plan.tables.filter(t => t.search);\n if (tables.length === 0) return \"\";\n\n const extensions = Array.from(new Set(tables.flatMap(t => searchExtensionStatements(t.search!))));\n const helpers = Array.from(new Set(tables.flatMap(t => searchHelperFunctions(t.search!))));\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- Full-text search for the collections declaring a `search` block.\\n\";\n ddl += \"-- Applied by Rebase, not by Atlas — see generatePostgresSearchDdl.\\n\\n\";\n\n extensions.forEach(s => { ddl += `${s}\\n`; });\n if (extensions.length > 0) ddl += \"\\n\";\n helpers.forEach(s => { ddl += `${s}\\n\\n`; });\n\n for (const table of tables) {\n const spec = table.search!;\n const target = `\"${table.schema}\".\"${table.table}\"`;\n // ADD COLUMN IF NOT EXISTS rather than the inline definition the\n // CREATE TABLE would use: by the time this runs the table exists,\n // whether Atlas just created it or it has been live for a year. The\n // guard first, because `ADD COLUMN IF NOT EXISTS` is a no-op against an\n // existing column — without it the file would report success, leave the\n // old expression in place, and then stamp it as current.\n searchStampGuards(spec).forEach(s => { ddl += `${s}\\n`; });\n ddl += `ALTER TABLE ${target} ADD COLUMN IF NOT EXISTS ${searchColumnDefinition(spec)};\\n`;\n const fuzzy = fuzzyColumnDefinition(spec);\n if (fuzzy) ddl += `ALTER TABLE ${target} ADD COLUMN IF NOT EXISTS ${fuzzy};\\n`;\n searchColumnStamps(spec).forEach(s => { ddl += `${s.sql}\\n`; });\n searchIndexStatements(spec).forEach(s => { ddl += `${s}\\n`; });\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n/**\n * Glob patterns telling Atlas to leave an object alone.\n *\n * Fully qualified, `schema.table.object`, matching the include list. The\n * two-part form is what Atlas wants when the connection URL scopes it to one\n * schema and is *silently ignored* otherwise: it reads `posts.search_vector` as\n * a table named `search_vector` in a schema named `posts`, matches nothing, and\n * reports no error for the pattern that never fired. Each name is spelled by\n * `atlasExcludePattern`, so one holding a `.` or glob syntax still matches.\n */\nexport const searchExcludePatternsOf = (plan: SchemaPlan): string[] => {\n const patterns: string[] = [];\n for (const table of plan.tables) {\n if (!table.search) continue;\n for (const column of table.columns) {\n if (column.source.kind !== \"search\") continue;\n patterns.push(atlasExcludePattern(table.schema, table.table, column.column));\n }\n for (const index of searchIndexNames(table.search)) {\n patterns.push(atlasExcludePattern(table.schema, table.table, index));\n }\n }\n return patterns;\n};\n\n// ── vector.sql ───────────────────────────────────────────────────────────────\n\nexport function renderVectorDdl(plan: SchemaPlan): string {\n const tables = plan.tables.filter(t => t.vectorColumns.length > 0);\n if (tables.length === 0) return \"\";\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- Vector columns and their ANN indexes, for the collections declaring a\\n\";\n ddl += \"-- `vector` property. Applied by Rebase, not by Atlas — see\\n\";\n ddl += \"-- generatePostgresVectorDdl.\\n\\n\";\n // The note is not decoration. Someone reading this file after a failed push\n // is looking for the reason the type does not exist, and \"no CREATE\n // EXTENSION here\" is invisible unless it is written down.\n ddl += vectorExtensionDeclared(plan.options.databaseExtensions)\n ? `${vectorExtensionStatement()}\\n\\n`\n : \"-- pgvector is not installed from here: no database declared it. To let Rebase\\n\" +\n `-- install it, add ${VECTOR_EXTENSION_OPT_IN} in config/resources.ts.\\n` +\n \"-- Otherwise install it once by hand; the column below needs the type either way.\\n\\n\";\n\n for (const table of tables) {\n const target = `\"${table.schema}\".\"${table.table}\"`;\n for (const spec of table.vectorColumns) {\n // Guard before the ADD, so a changed `dimensions` is reported\n // rather than skipped over — see `vectorDimensionGuard`.\n ddl += `${vectorDimensionGuard(spec)}\\n`;\n ddl += `ALTER TABLE ${target} ADD COLUMN IF NOT EXISTS ${vectorColumnDefinition(spec)};\\n`;\n }\n if (table.vector) {\n vectorIndexStatements(table.vector).forEach(s => { ddl += `${s}\\n`; });\n for (const skip of table.vector.skipped) {\n ddl += `-- No ANN index on \"${skip.schema}\".\"${skip.table}\".\"${skip.column}\": ${skip.reason}\\n`;\n }\n }\n ddl += \"\\n\";\n }\n\n return ddl;\n}\n\n/** @see searchExcludePatternsOf */\nexport const vectorExcludePatternsOf = (plan: SchemaPlan): string[] => {\n const patterns: string[] = [];\n for (const table of plan.tables) {\n const names = [\n ...table.vectorColumns.map(spec => spec.column),\n ...(table.vector ? vectorIndexNames(table.vector) : [])\n ];\n for (const name of names) patterns.push(atlasExcludePattern(table.schema, table.table, name));\n }\n return patterns;\n};\n\n// ── triggers.sql ─────────────────────────────────────────────────────────────\n\n/**\n * `autoValue: \"on_update\"`, as the file Rebase applies itself.\n *\n * Empty when nothing declares one — the caller writes no file then, and removes\n * a stale one.\n */\nexport function renderTriggersDdl(plan: SchemaPlan): string {\n const tables = plan.tables.filter(t => t.triggers.length > 0);\n if (tables.length === 0) return \"\";\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- `updated_at` triggers, for the properties declaring `autoValue: \\\"on_update\\\"`,\\n\";\n ddl += \"-- and the triggers that keep a row in its tenant.\\n\";\n ddl += \"-- Applied by Rebase, not by Atlas — a trigger is a function plus a binding,\\n\";\n ddl += \"-- and Atlas's free tier refuses to parse a desired state containing one.\\n\\n\";\n\n for (const statement of plan.functions.filter(isTriggerFunction)) {\n ddl += `${statement}\\n\\n`;\n }\n for (const table of tables) {\n for (const trigger of table.triggers) {\n triggerStatements(trigger).forEach(s => { ddl += `${s}\\n`; });\n }\n ddl += \"\\n\";\n }\n return ddl;\n}\n\nconst isTriggerFunction = (statement: string): boolean => statement.includes(\"RETURNS trigger\");\n\n/** @see searchExcludePatternsOf */\nexport const triggerExcludePatternsOf = (plan: SchemaPlan): string[] =>\n plan.tables.flatMap(table => table.triggers.map(t => atlasExcludePattern(table.schema, table.table, t.name)));\n\nconst quoteIdentifier = (name: string): string => `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\n/** The comment a view Rebase created carries: `rebase:view:<hash>`. */\nexport const viewComment = (view: ViewPlan): string => `rebase:view:${view.hash}`;\n\n/** A dollar-quote tag the text does not contain, so the text can be quoted whole. */\nfunction dollarTag(text: string): string {\n let tag = \"$rebase_view$\";\n for (let i = 1; text.includes(tag); i++) tag = `$rebase_view_${i}$`;\n return tag;\n}\n\n/**\n * The statements that create one view as planned, comment included, for\n * `EXECUTE`. A plain view runs as the caller (`security_invoker`), so the\n * policies of the tables it reads decide what each caller sees.\n *\n * A materialized view is two objects (see `view-names.ts`): its rows, stored\n * under {@link viewRowsName} with a unique index on the id columns (which\n * `REFRESH … CONCURRENTLY` needs), and the gate under the collection's name —\n * a `security_barrier` view that reads them with the owner's rights and serves\n * them to the collection's roles and to the server (no uid). It reads the\n * settings directly rather than through `rebase.roles()`, which a first boot\n * creates after the views. It carries each row's `xmin`, for `fingerprint()`;\n * the catalogue reader leaves that column out of the collection.\n */\nexport function viewCreateStatements(view: ViewPlan): string[] {\n const qualified = `${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`;\n if (!view.materialized) {\n return [\n `CREATE VIEW ${qualified} WITH (security_invoker = true) AS\\n${view.query}`,\n `COMMENT ON VIEW ${qualified} IS '${viewComment(view)}'`\n ];\n }\n const stored = `${quoteIdentifier(view.schema)}.${quoteIdentifier(viewRowsName(view.name))}`;\n const roles = view.roles.map(role => `'${role.replace(/'/g, \"''\")}'`).join(\", \");\n const statements = [`CREATE MATERIALIZED VIEW ${stored} AS\\n${view.query}\\nWITH DATA`];\n if (view.idColumns.length > 0) {\n statements.push(`CREATE UNIQUE INDEX ${quoteIdentifier(`${view.name}_rebase_id`)} ON ${stored} (${view.idColumns.map(quoteIdentifier).join(\", \")})`);\n }\n statements.push(...view.indexes);\n statements.push(\n `COMMENT ON MATERIALIZED VIEW ${stored} IS '${VIEW_ROWS_COMMENT_PREFIX}${view.hash}'`,\n `REVOKE ALL ON ${stored} FROM PUBLIC`,\n `CREATE VIEW ${qualified} WITH (security_barrier = true) AS\\n` +\n `SELECT rows.*, rows.xmin AS xmin FROM ${stored} rows\\n` +\n \"WHERE NULLIF(current_setting('app.uid', true), '') IS NULL\\n\" +\n ` OR string_to_array(COALESCE(current_setting('app.user_roles', true), ''), ',') && ARRAY[${roles || \"NULL\"}]::text[]`,\n `COMMENT ON VIEW ${qualified} IS '${viewComment(view)}'`\n );\n return statements;\n}\n\n/**\n * `views.sql`: the views of the collections that declare one, as the file\n * Rebase applies itself — Atlas manages no views on its free tier.\n *\n * Idempotent, in two passes. The first drops, last first, every view whose\n * comment no longer matches its plan and every view that reads one of those\n * (Postgres will not drop a view another still reads, and will not change a\n * view's columns in place); the second creates, in order, every view that is\n * not there. A view that is up to date is left alone, rows and all. A table or\n * a view Rebase did not create under the same name is refused, never dropped.\n *\n * Empty when no collection declares a view.\n */\nexport function renderViewsDdl(plan: SchemaPlan): string {\n if (plan.views.length === 0) return \"\";\n const literal = (text: string) => `'${text.replace(/'/g, \"''\")}'`;\n const regclass = (view: ViewPlan) => `to_regclass(${literal(`${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`)})`;\n const stale = (view: ViewPlan) =>\n `(${regclass(view)} IS NOT NULL AND obj_description(${regclass(view)}, 'pg_class') IS DISTINCT FROM ${literal(viewComment(view))})`;\n // Every planned view a view reads, directly or through another.\n const readsOf = (view: ViewPlan, seen = new Set<string>()): ViewPlan[] =>\n view.dependsOn.flatMap(name => {\n if (seen.has(name)) return [];\n seen.add(name);\n const target = plan.views.find(other => other.qualified === name);\n return target ? [target, ...readsOf(target, seen)] : [];\n });\n\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\";\n ddl += \"--\\n\";\n ddl += \"-- The views of the collections that declare `view`. Applied by Rebase, not by Atlas.\\n\\n\";\n ddl += \"DO $rebase_views$\\nDECLARE\\n kind \\\"char\\\";\\n note text;\\nBEGIN\\n\";\n for (const view of [...plan.views].reverse()) {\n const qualified = `${quoteIdentifier(view.schema)}.${quoteIdentifier(view.name)}`;\n const reasons = [view, ...readsOf(view)].map(stale).join(\"\\n OR \");\n ddl += ` SELECT c.relkind, obj_description(c.oid, 'pg_class') INTO kind, note FROM pg_class c WHERE c.oid = ${regclass(view)};\\n`;\n ddl += \" IF kind IS NOT NULL AND (kind NOT IN ('v', 'm') OR note IS NULL OR note NOT LIKE 'rebase:view:%') THEN\\n\";\n ddl += ` RAISE EXCEPTION 'Rebase will not replace %: it is a table or a view Rebase did not create. Rename or drop it, or give the collection another table.', ${literal(view.qualified)};\\n`;\n ddl += \" END IF;\\n\";\n ddl += ` IF ${reasons} THEN\\n`;\n ddl += ` IF kind = 'm' THEN EXECUTE ${literal(`DROP MATERIALIZED VIEW ${qualified}`)}; ELSE EXECUTE ${literal(`DROP VIEW ${qualified}`)}; END IF;\\n`;\n ddl += \" END IF;\\n\";\n }\n for (const view of plan.views) {\n const rows = `${quoteIdentifier(view.schema)}.${quoteIdentifier(viewRowsName(view.name))}`;\n ddl += ` IF ${regclass(view)} IS NULL THEN\\n`;\n // A gate that is gone leaves its rows: they are this view's, recomputed below.\n if (view.materialized) {\n ddl += ` IF to_regclass(${literal(rows)}) IS NOT NULL THEN EXECUTE ${literal(`DROP MATERIALIZED VIEW ${rows}`)}; END IF;\\n`;\n }\n for (const statement of viewCreateStatements(view)) {\n const tag = dollarTag(statement);\n ddl += ` EXECUTE ${tag}${statement}${tag};\\n`;\n }\n if (view.materialized) {\n ddl += ` IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(REBASE_USER_ROLE)}) THEN EXECUTE ${literal(`REVOKE ALL ON ${rows} FROM ${REBASE_USER_ROLE}`)}; END IF;\\n`;\n }\n ddl += \" END IF;\\n\";\n }\n ddl += \"END\\n$rebase_views$;\\n\";\n return ddl;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,IAAa,gBAAgB,SAAyB;CAClD,QAAQ,KAAK,MAAb;EACI,KAAK,QAAQ,OAAO;EACpB,KAAK,WAAW,OAAO,WAAW,KAAK,OAAO;EAC9C,KAAK,QAAQ,OAAO,QAAQ,KAAK,OAAO;EACxC,KAAK,QAAQ,OAAO;EACpB,KAAK,QAAQ,OAAO,IAAI,KAAK,OAAO,KAAK,KAAK,KAAK;EACnD,KAAK,YAAY,OAAO;EACxB,KAAK,WAAW,OAAO;EACvB,KAAK,UAAU,OAAO;EACtB,KAAK,eAAe,OAAO;EAC3B,KAAK,UAAU,OAAO;EACtB,KAAK,aAAa,OAAO;EACzB,KAAK,QAAQ,OAAO;EACpB,KAAK,mBAAmB,OAAO;EAC/B,KAAK;GACD,IAAI,KAAK,cAAc,KAAA,GAAW,OAAO;GACzC,OAAO,KAAK,UAAU,KAAA,IAChB,WAAW,KAAK,UAAU,KAC1B,WAAW,KAAK,UAAU,IAAI,KAAK,MAAM;EACnD,KAAK,WAAW,OAAO;EACvB,KAAK,eAAe,OAAO;EAC3B,KAAK,QAAQ,OAAO;EACpB,KAAK,QAAQ,OAAO;EACpB,KAAK,QAAQ,OAAO;EACpB,KAAK,SAAS,OAAO;EACrB,KAAK,UAAU,OAAO,UAAU,KAAK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AO,GAAG,gBAAgB,KAAK,MAAM,EAAE,GAAG,gBAAgB,aAAa,KAAK,IAAI,CAAC;EACvF,OAAO,UAAU,SAAS,IAAI,EAAE;EAEhC,IAAI,KAAK,cACL,OAAO,0BAA0B,QAAQ,IAAI,EAAE,6BAA6B,QAAQ,0BAA0B,MAAM,EAAE;EAE1H,KAAK,MAAM,aAAa,qBAAqB,IAAI,GAAG;GAChD,MAAM,MAAM,UAAU,SAAS;GAC/B,OAAO,mBAAmB,MAAM,YAAY,IAAI;EACpD;EACA,IAAI,KAAK,cACL,OAAO,6DAA6D,QAAQ,gBAAgB,EAAE,iBAAiB,QAAQ,iBAAiB,KAAK,QAAQ,kBAAkB,EAAE;EAE7K,OAAO;CACX;CACA,OAAO;CACP,OAAO;AACX"}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from "module";
|
|
2
|
+
__createRequire(import.meta.url);
|
|
3
|
+
import { i as __exportAll, t as promptConfirm } from "./cli-prompt-DXG0yk-h.js";
|
|
4
|
+
import { it as redactConnectionPasswords } from "./cli-errors-DwqFRIWz.js";
|
|
5
|
+
import { a as outWarn, i as outError, r as out, t as chalk } from "./source-fZb92pN8.js";
|
|
6
|
+
import { _ as closestWord, y as parseCommandFlags } from "./migrate-baseline-BfHmq3vN.js";
|
|
7
|
+
import { n as resolveRlsSettings } from "./rls-settings-De5NoHHy.js";
|
|
8
|
+
import { REBASE_USER_ROLE } from "@rebasepro/common";
|
|
9
|
+
//#region src/request-role-cli.ts
|
|
10
|
+
var request_role_cli_exports = /* @__PURE__ */ __exportAll({
|
|
11
|
+
PROVISION_FLAGS: () => PROVISION_FLAGS,
|
|
12
|
+
REQUEST_ROLE_ACTIONS: () => REQUEST_ROLE_ACTIONS,
|
|
13
|
+
REQUEST_ROLE_FLAGS: () => REQUEST_ROLE_FLAGS,
|
|
14
|
+
REQUEST_ROLE_SCHEMAS: () => REQUEST_ROLE_SCHEMAS,
|
|
15
|
+
asSqlScript: () => asSqlScript,
|
|
16
|
+
parseProvisionLine: () => parseProvisionLine,
|
|
17
|
+
parseRequestRoleLine: () => parseRequestRoleLine,
|
|
18
|
+
parseRoleList: () => parseRoleList,
|
|
19
|
+
provisionCommand: () => provisionCommand,
|
|
20
|
+
renderMigrationPlan: () => renderMigrationPlan,
|
|
21
|
+
renderProvisionScript: () => renderProvisionScript,
|
|
22
|
+
renderRevokeOld: () => renderRevokeOld,
|
|
23
|
+
requestRoleCommand: () => requestRoleCommand,
|
|
24
|
+
requestRoleReminder: () => requestRoleReminder,
|
|
25
|
+
resolveMigrationRoles: () => resolveMigrationRoles
|
|
26
|
+
});
|
|
27
|
+
/**
|
|
28
|
+
* The schemas both commands provision in: the ones `db push` and `db migrate`
|
|
29
|
+
* provision the request role in after a schema change.
|
|
30
|
+
*/
|
|
31
|
+
var REQUEST_ROLE_SCHEMAS = ["public", "rebase"];
|
|
32
|
+
/** The actions `rebase db request-role` answers. */
|
|
33
|
+
var REQUEST_ROLE_ACTIONS = ["migrate"];
|
|
34
|
+
/** The flags of `rebase db request-role migrate`. Named `…FLAGS` so the docs verifier reads them. */
|
|
35
|
+
var REQUEST_ROLE_FLAGS = {
|
|
36
|
+
"--to": String,
|
|
37
|
+
"--dry-run": Boolean,
|
|
38
|
+
"--yes": Boolean,
|
|
39
|
+
"-y": "--yes"
|
|
40
|
+
};
|
|
41
|
+
/** The flags of `rebase db provision`. */
|
|
42
|
+
var PROVISION_FLAGS = { "--print": Boolean };
|
|
43
|
+
/**
|
|
44
|
+
* `"app_prod_user, app_prod_anon"` → `["app_prod_user", "app_prod_anon"]`.
|
|
45
|
+
* Each name is checked by the same rule the `rls.requestRole` setting uses, so
|
|
46
|
+
* a name the server would refuse at boot is refused here, before anything runs.
|
|
47
|
+
*/
|
|
48
|
+
function parseRoleList(value, flag) {
|
|
49
|
+
const roles = Array.from(new Set(value.split(",").map((r) => r.trim()).filter(Boolean)));
|
|
50
|
+
if (roles.length === 0) throw new Error(`${flag} needs at least one role name, e.g. ${flag} app_prod_user.`);
|
|
51
|
+
for (const role of roles) try {
|
|
52
|
+
resolveRlsSettings({ requestRole: role });
|
|
53
|
+
} catch (err) {
|
|
54
|
+
throw new Error(`${flag} ${role}: ${err instanceof Error ? err.message.replace(/^[^:]*:\s*/, "") : String(err)}`);
|
|
55
|
+
}
|
|
56
|
+
return roles;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Parse a `rebase db request-role <action> …` line — `["db", "request-role",
|
|
60
|
+
* "migrate", …]`. Throws, with nothing run, on a missing or unknown action, an
|
|
61
|
+
* undeclared flag, a stray word or a missing or unusable `--to`.
|
|
62
|
+
*/
|
|
63
|
+
function parseRequestRoleLine(rawArgs) {
|
|
64
|
+
const action = rawArgs[2];
|
|
65
|
+
if (action === void 0 || action.startsWith("-")) throw new Error("`rebase db request-role` needs an action: `rebase db request-role migrate --to <role[,role]>`. Nothing was run.");
|
|
66
|
+
if (!REQUEST_ROLE_ACTIONS.some((known) => known === action)) {
|
|
67
|
+
const near = closestWord(action, REQUEST_ROLE_ACTIONS);
|
|
68
|
+
throw new Error(`\`rebase db request-role\` has no action "${redactConnectionPasswords(action)}"` + (near ? ` — did you mean ${near}?` : `. It takes: ${REQUEST_ROLE_ACTIONS.join(", ")}.`) + " Nothing was run.");
|
|
69
|
+
}
|
|
70
|
+
const args = parseCommandFlags(REQUEST_ROLE_FLAGS, [...rawArgs.slice(3)], "db request-role migrate");
|
|
71
|
+
if (args._.length > 0) throw new Error(`\`rebase db request-role migrate\` takes no argument "${redactConnectionPasswords(args._[0])}". Name the new role(s) with --to. Nothing was run.`);
|
|
72
|
+
const to = args["--to"];
|
|
73
|
+
if (to === void 0) throw new Error("`rebase db request-role migrate` needs --to <role[,role]>: the role(s) requests should run as from now on. Nothing was run.");
|
|
74
|
+
return {
|
|
75
|
+
action: "migrate",
|
|
76
|
+
to: parseRoleList(to, "--to"),
|
|
77
|
+
dryRun: args["--dry-run"] === true,
|
|
78
|
+
yes: args["--yes"] === true
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Parse a `rebase db provision …` line. `--print` is required: the command
|
|
83
|
+
* shows the SQL and runs none of it — a server boot, `db push` and
|
|
84
|
+
* `db migrate` are what provision.
|
|
85
|
+
*/
|
|
86
|
+
function parseProvisionLine(rawArgs) {
|
|
87
|
+
const args = parseCommandFlags(PROVISION_FLAGS, [...rawArgs.slice(2)], "db provision");
|
|
88
|
+
if (args._.length > 0) throw new Error(`\`rebase db provision\` takes no argument "${redactConnectionPasswords(args._[0])}". Nothing was run.`);
|
|
89
|
+
if (args["--print"] !== true) throw new Error("`rebase db provision` prints the SQL and runs none of it: pass --print. A server boot, `rebase db push` and `rebase db migrate` provision the request role themselves. Nothing was run.");
|
|
90
|
+
return { print: true };
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Which roles a migration moves from and to. From is what this database
|
|
94
|
+
* recorded, or `rebase_user` — every database provisioned before the setting
|
|
95
|
+
* existed ran as it. `null` when the two are the same set, in any order:
|
|
96
|
+
* there is nothing to move.
|
|
97
|
+
*/
|
|
98
|
+
function resolveMigrationRoles(recorded, to) {
|
|
99
|
+
const from = recorded && recorded.length > 0 ? [...recorded] : [REBASE_USER_ROLE];
|
|
100
|
+
return from.length === to.length && from.every((role) => to.includes(role)) ? null : {
|
|
101
|
+
from,
|
|
102
|
+
to: [...to]
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
var quoted = (roles) => roles.map((r) => `"${r}"`).join(", ");
|
|
106
|
+
/** What `db request-role migrate` says before it runs, or instead of running with `--dry-run`. */
|
|
107
|
+
function renderMigrationPlan(plan, roles, dryRun) {
|
|
108
|
+
const lines = [];
|
|
109
|
+
lines.push(` Requests in this database run as ${quoted(roles.from)}. This moves them to ${quoted(roles.to)}.`);
|
|
110
|
+
lines.push(chalk.gray(" Grants are re-issued in this database only; the old role is left as it is, because another database may use it."));
|
|
111
|
+
lines.push("");
|
|
112
|
+
lines.push(dryRun ? " Would run, in one transaction:" : " Will run, in one transaction:");
|
|
113
|
+
lines.push(chalk.gray(` -- create ${quoted(roles.to)} if missing (NOLOGIN NOSUPERUSER NOBYPASSRLS NOINHERIT), and let this connection switch to it`));
|
|
114
|
+
if (plan.statements.length === 0) lines.push(chalk.gray(` -- ${quoted(roles.from)} holds no grants here: nothing to copy`));
|
|
115
|
+
for (const statement of plan.statements) lines.push(` ${statement};`);
|
|
116
|
+
lines.push(chalk.gray(` -- record ${quoted(roles.to)} in rebase.schema_meta (request_roles)`));
|
|
117
|
+
if (dryRun) {
|
|
118
|
+
lines.push("");
|
|
119
|
+
lines.push(...renderRevokeOld(plan, roles.from));
|
|
120
|
+
}
|
|
121
|
+
return lines;
|
|
122
|
+
}
|
|
123
|
+
/** The statements that take the old role's grants back here, for the operator to run once satisfied. */
|
|
124
|
+
function renderRevokeOld(plan, from) {
|
|
125
|
+
if (plan.revokeOld.length === 0) return [chalk.gray(` ${quoted(from)} holds no grants in this database, so there is nothing to take back.`)];
|
|
126
|
+
return [` Run these once you no longer need ${quoted(from)} in this database:`, ...plan.revokeOld.map((statement) => ` ${statement};`)];
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* The prose `appRoleSetupInstructions` opens with, as SQL comments, and the SQL
|
|
130
|
+
* after it as it is — so the output of `db provision --print` can be piped
|
|
131
|
+
* into `psql` whole.
|
|
132
|
+
*/
|
|
133
|
+
function asSqlScript(instructions) {
|
|
134
|
+
const split = instructions.indexOf("\n\n");
|
|
135
|
+
if (split === -1) return instructions;
|
|
136
|
+
return [...instructions.slice(0, split).split("\n").map((line) => `-- ${line}`.trimEnd()), instructions.slice(split + 2)].join("\n");
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The whole `db provision --print` script: for each request role, the SQL that
|
|
140
|
+
* creates it and lets the connection switch to it, plus the grants the
|
|
141
|
+
* `grants` mode makes schema-wide. Runs nothing.
|
|
142
|
+
*/
|
|
143
|
+
function renderProvisionScript(connectionRole, settings, sqlFor) {
|
|
144
|
+
const parts = [
|
|
145
|
+
"-- Request role setup for this database, as a database administrator would run it.",
|
|
146
|
+
`-- Connection role: "${connectionRole}". Request role(s): ${quoted(settings.roles)}. grants: ${settings.grants}. provisionRole: ${settings.provisionRole}.`,
|
|
147
|
+
"-- Printed by `rebase db provision --print`; nothing was run. Every statement is safe to re-run."
|
|
148
|
+
];
|
|
149
|
+
if (settings.grants === "managed") parts.push("-- grants: managed — no schema-wide grants here; once the connection can switch, a boot grants each table Rebase serves.");
|
|
150
|
+
else if (settings.grants === "none") parts.push("-- grants: none — Rebase grants nothing; grant the request role the tables it should reach yourself.");
|
|
151
|
+
for (const role of settings.roles) parts.push("", `-- ── "${role}" ──`, asSqlScript(sqlFor(role)));
|
|
152
|
+
return parts.join("\n");
|
|
153
|
+
}
|
|
154
|
+
function databaseUrlOrExit() {
|
|
155
|
+
const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;
|
|
156
|
+
if (!databaseUrl) {
|
|
157
|
+
outError(chalk.red("✗ DATABASE_URL is not set. Make sure your .env file is configured."));
|
|
158
|
+
process.exit(1);
|
|
159
|
+
}
|
|
160
|
+
return databaseUrl;
|
|
161
|
+
}
|
|
162
|
+
/** `rebase db provision --print`. */
|
|
163
|
+
async function provisionCommand(rawArgs) {
|
|
164
|
+
parseProvisionLine(rawArgs);
|
|
165
|
+
const databaseUrl = databaseUrlOrExit();
|
|
166
|
+
const { withAppClient } = await import("./cli-errors-DwqFRIWz.js").then((n) => n.v);
|
|
167
|
+
const { appRoleSetupInstructions, readRecordedRequestRoles } = await import("./rls-enforcement-BO618rnr.js").then((n) => n.v);
|
|
168
|
+
const { cliRlsSettings } = await import("./rls-settings-De5NoHHy.js").then((n) => n.a);
|
|
169
|
+
out(await withAppClient(databaseUrl, async (client) => {
|
|
170
|
+
const run = async (text) => (await client.query(text)).rows;
|
|
171
|
+
const [who] = await run("SELECT current_user AS role");
|
|
172
|
+
const connectionRole = String(who?.role ?? "");
|
|
173
|
+
const settings = cliRlsSettings(await readRecordedRequestRoles(run));
|
|
174
|
+
const present = await run(`SELECT nspname FROM pg_namespace WHERE nspname IN (${REQUEST_ROLE_SCHEMAS.map((s) => `'${s}'`).join(", ")})`);
|
|
175
|
+
const schemas = REQUEST_ROLE_SCHEMAS.filter((schema) => present.some((row) => row.nspname === schema));
|
|
176
|
+
return renderProvisionScript(connectionRole, settings, (role) => appRoleSetupInstructions(connectionRole, schemas, role, settings.grants));
|
|
177
|
+
}));
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* The confirmation `db request-role migrate` asks for. `--yes` skips it; with
|
|
181
|
+
* no terminal nobody can answer, so it refuses and names `--yes`.
|
|
182
|
+
*/
|
|
183
|
+
async function confirmMigration(yes) {
|
|
184
|
+
if (yes) return true;
|
|
185
|
+
if (!process.stdin.isTTY) {
|
|
186
|
+
outError(chalk.red(" ✗ Nothing was changed: there is no terminal to confirm on."));
|
|
187
|
+
outError(chalk.gray(" Re-run with --yes, or with --dry-run to see the plan."));
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
const confirmed = await promptConfirm(chalk.yellow(" Type 'yes' to move this database to the new request role(s): "));
|
|
191
|
+
if (!confirmed) out(chalk.gray(" Aborted. No changes were made."));
|
|
192
|
+
return confirmed;
|
|
193
|
+
}
|
|
194
|
+
/** `rebase db request-role migrate --to <role[,role]> [--dry-run] [--yes]`. */
|
|
195
|
+
async function requestRoleCommand(rawArgs) {
|
|
196
|
+
const line = parseRequestRoleLine(rawArgs);
|
|
197
|
+
const databaseUrl = databaseUrlOrExit();
|
|
198
|
+
const { withAppClient } = await import("./cli-errors-DwqFRIWz.js").then((n) => n.v);
|
|
199
|
+
const { AppRoleSetupError, readRecordedRequestRoles } = await import("./rls-enforcement-BO618rnr.js").then((n) => n.v);
|
|
200
|
+
const { migrateRequestRoles, planRequestRoleMigration } = await import("./request-role-migration-D9BZ5Uba.js");
|
|
201
|
+
out("");
|
|
202
|
+
out(chalk.bold(" rebase db request-role migrate"));
|
|
203
|
+
out("");
|
|
204
|
+
await withAppClient(databaseUrl, async (client) => {
|
|
205
|
+
const run = async (text) => (await client.query(text)).rows;
|
|
206
|
+
const roles = resolveMigrationRoles(await readRecordedRequestRoles(run), line.to);
|
|
207
|
+
if (!roles) {
|
|
208
|
+
out(chalk.green(` ✓ Requests in this database already run as ${quoted(line.to)}. Nothing to do.`));
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const plan = await planRequestRoleMigration(run, roles.from, roles.to);
|
|
212
|
+
for (const text of renderMigrationPlan(plan, roles, line.dryRun)) out(text);
|
|
213
|
+
out("");
|
|
214
|
+
if (line.dryRun) {
|
|
215
|
+
out(chalk.gray(" Dry run: nothing was changed."));
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (!await confirmMigration(line.yes)) {
|
|
219
|
+
process.exitCode = 1;
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
let applied;
|
|
223
|
+
await client.query("BEGIN");
|
|
224
|
+
try {
|
|
225
|
+
applied = await migrateRequestRoles(run, {
|
|
226
|
+
from: roles.from,
|
|
227
|
+
to: roles.to,
|
|
228
|
+
schemas: REQUEST_ROLE_SCHEMAS
|
|
229
|
+
});
|
|
230
|
+
await client.query("COMMIT");
|
|
231
|
+
} catch (err) {
|
|
232
|
+
await client.query("ROLLBACK").catch(() => void 0);
|
|
233
|
+
if (err instanceof AppRoleSetupError) {
|
|
234
|
+
outError(chalk.red(` ✗ Nothing was changed: ${err.message.slice(0, -err.instructions.length).trimEnd()}`));
|
|
235
|
+
outError(chalk.gray(err.instructions));
|
|
236
|
+
process.exitCode = 1;
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
throw err;
|
|
240
|
+
}
|
|
241
|
+
out(chalk.green(` ✓ Requests in this database now run as ${quoted(roles.to)} (${applied.statements.length} grant(s) re-issued).`));
|
|
242
|
+
out("");
|
|
243
|
+
for (const text of renderRevokeOld(applied, roles.from)) out(text);
|
|
244
|
+
out("");
|
|
245
|
+
outWarn(chalk.yellow(` ${requestRoleReminder(roles.to)}`));
|
|
246
|
+
out("");
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* What to change on the servers once the database has moved: a boot configured
|
|
251
|
+
* for other roles than the recorded ones refuses to start. One role fits the
|
|
252
|
+
* environment variable; several need the setting in code.
|
|
253
|
+
*/
|
|
254
|
+
function requestRoleReminder(to) {
|
|
255
|
+
return `Set ${to.length === 1 ? `REBASE_RLS_REQUEST_ROLE=${to[0]} (or rls.requestRole: "${to[0]}" in the driver config)` : `rls.requestRole in the driver config (a { anonymous, signedIn } map, or a function with rls.requestRoles: [${to.map((r) => `"${r}"`).join(", ")}])`} on every server that uses this database: a boot configured for other roles refuses to start.`;
|
|
256
|
+
}
|
|
257
|
+
//#endregion
|
|
258
|
+
export { parseRequestRoleLine as n, request_role_cli_exports as r, parseProvisionLine as t };
|
|
259
|
+
|
|
260
|
+
//# sourceMappingURL=request-role-cli-DSdRtvgH.js.map
|