@rebasepro/server-postgres 0.29.2 → 0.29.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/{BranchService-X9R505mP.js → BranchService-CrXvcES2.js} +3 -3
  2. package/dist/{BranchService-X9R505mP.js.map → BranchService-CrXvcES2.js.map} +1 -1
  3. package/dist/PostgresBootstrapper.d.ts +7 -0
  4. package/dist/{backup-cli-CwiJEp_J.js → backup-cli-CTKCOLpX.js} +3 -3
  5. package/dist/{backup-cli-CwiJEp_J.js.map → backup-cli-CTKCOLpX.js.map} +1 -1
  6. package/dist/{boot-ddl-CbZj9ovZ.js → boot-ddl-CqGIwSYx.js} +2 -2
  7. package/dist/{boot-ddl-CbZj9ovZ.js.map → boot-ddl-CqGIwSYx.js.map} +1 -1
  8. package/dist/{cli-console-DDkNetCz.js → cli-console-DBPw-oAz.js} +5 -5
  9. package/dist/{cli-console-DDkNetCz.js.map → cli-console-DBPw-oAz.js.map} +1 -1
  10. package/dist/{cli-errors-C73Qy7WJ.js → cli-errors-DYTxnLbW.js} +5 -5
  11. package/dist/{cli-errors-C73Qy7WJ.js.map → cli-errors-DYTxnLbW.js.map} +1 -1
  12. package/dist/cli.js +62 -42
  13. package/dist/cli.js.map +1 -1
  14. package/dist/{database-preflight-DIauc8i5.js → database-preflight-iBpT7-vv.js} +2 -2
  15. package/dist/{database-preflight-DIauc8i5.js.map → database-preflight-iBpT7-vv.js.map} +1 -1
  16. package/dist/{deferred-index-build-DDdnjaOW.js → deferred-index-build-BCU9RoHK.js} +6 -6
  17. package/dist/{deferred-index-build-DDdnjaOW.js.map → deferred-index-build-BCU9RoHK.js.map} +1 -1
  18. package/dist/{doctor-DwMXljiq.js → doctor-Kg1oUK0Q.js} +6 -6
  19. package/dist/{doctor-DwMXljiq.js.map → doctor-Kg1oUK0Q.js.map} +1 -1
  20. package/dist/{ensure-collection-policies-DJsOMpaI.js → ensure-collection-policies-Bo-_fDAy.js} +12 -12
  21. package/dist/ensure-collection-policies-Bo-_fDAy.js.map +1 -0
  22. package/dist/{ensure-collection-tables-h1mUO7Uu.js → ensure-collection-tables-DCJINkT_.js} +9 -9
  23. package/dist/{ensure-collection-tables-h1mUO7Uu.js.map → ensure-collection-tables-DCJINkT_.js.map} +1 -1
  24. package/dist/{ensure-tables-CUqYgMvo.js → ensure-tables-BPGaGh0y.js} +4 -4
  25. package/dist/{ensure-tables-CUqYgMvo.js.map → ensure-tables-BPGaGh0y.js.map} +1 -1
  26. package/dist/{enum-labels-kept-z7ustOl_.js → enum-labels-kept-YAgOZS4I.js} +3 -3
  27. package/dist/{enum-labels-kept-z7ustOl_.js.map → enum-labels-kept-YAgOZS4I.js.map} +1 -1
  28. package/dist/{generate-drizzle-schema-BIUqhSzh.js → generate-drizzle-schema-DcrFr7YX.js} +2 -2
  29. package/dist/{generate-drizzle-schema-BIUqhSzh.js.map → generate-drizzle-schema-DcrFr7YX.js.map} +1 -1
  30. package/dist/{generate-drizzle-schema-logic-BBXjxm5z.js → generate-drizzle-schema-logic-LTLZvt6r.js} +2 -2
  31. package/dist/{generate-drizzle-schema-logic-BBXjxm5z.js.map → generate-drizzle-schema-logic-LTLZvt6r.js.map} +1 -1
  32. package/dist/{generate-files-BkiRFoV1.js → generate-files-CsaVzatS.js} +3 -3
  33. package/dist/{generate-files-BkiRFoV1.js.map → generate-files-CsaVzatS.js.map} +1 -1
  34. package/dist/{generate-postgres-ddl-logic-G9PvjHrr.js → generate-postgres-ddl-logic-Dg0bcENZ.js} +39 -6
  35. package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +1 -0
  36. package/dist/{generated-schema-diff-D2soazQU.js → generated-schema-diff-By4dxyTH.js} +2 -2
  37. package/dist/{generated-schema-diff-D2soazQU.js.map → generated-schema-diff-By4dxyTH.js.map} +1 -1
  38. package/dist/index.es.js +12 -12
  39. package/dist/{migrate-baseline-CveNQli3.js → migrate-baseline-CmWXL7qx.js} +2 -2
  40. package/dist/{migrate-baseline-CveNQli3.js.map → migrate-baseline-CmWXL7qx.js.map} +1 -1
  41. package/dist/{migrate-policy-stamps-C4qbQ0jK.js → migrate-policy-stamps-BN_Qad6c.js} +6 -6
  42. package/dist/{migrate-policy-stamps-C4qbQ0jK.js.map → migrate-policy-stamps-BN_Qad6c.js.map} +1 -1
  43. package/dist/{open-rebase-Cvid3iwR.js → open-rebase-40paQfVW.js} +31 -24
  44. package/dist/{open-rebase-Cvid3iwR.js.map → open-rebase-40paQfVW.js.map} +1 -1
  45. package/dist/{pg-error-utils-80uTIHQs.js → pg-error-utils-DJHjCF7-.js} +2 -2
  46. package/dist/{pg-error-utils-80uTIHQs.js.map → pg-error-utils-DJHjCF7-.js.map} +1 -1
  47. package/dist/{plan-schema-CMhNYEYF.js → plan-schema-vJd3UEmT.js} +24 -9
  48. package/dist/plan-schema-vJd3UEmT.js.map +1 -0
  49. package/dist/{policy-drift-Bx6663KD.js → policy-drift-C-m0uWHH.js} +53 -8
  50. package/dist/policy-drift-C-m0uWHH.js.map +1 -0
  51. package/dist/{push-index-adoption-C-TpM445.js → push-index-adoption-Cp7oZxSl.js} +3 -3
  52. package/dist/{push-index-adoption-C-TpM445.js.map → push-index-adoption-Cp7oZxSl.js.map} +1 -1
  53. package/dist/{push-index-prebuild-xbpgZEJK.js → push-index-prebuild-DbwKGtQT.js} +4 -4
  54. package/dist/{push-index-prebuild-xbpgZEJK.js.map → push-index-prebuild-DbwKGtQT.js.map} +1 -1
  55. package/dist/{push-kept-defaults-D-JEv0Gn.js → push-kept-defaults-CLcgsEPt.js} +2 -2
  56. package/dist/{push-kept-defaults-D-JEv0Gn.js.map → push-kept-defaults-CLcgsEPt.js.map} +1 -1
  57. package/dist/{push-legacy-renames-7UKspspl.js → push-legacy-renames-BthD0E9W.js} +4 -4
  58. package/dist/{push-legacy-renames-7UKspspl.js.map → push-legacy-renames-BthD0E9W.js.map} +1 -1
  59. package/dist/{push-policy-plan-BOw5PtU8.js → push-policy-plan-BgcrroxQ.js} +3 -3
  60. package/dist/{push-policy-plan-BOw5PtU8.js.map → push-policy-plan-BgcrroxQ.js.map} +1 -1
  61. package/dist/{render-ddl-Di-fTGti.js → render-ddl-Ci3S_SoI.js} +23 -5
  62. package/dist/render-ddl-Ci3S_SoI.js.map +1 -0
  63. package/dist/{request-role-cli-Bxxskru9.js → request-role-cli-Dy1EgJU9.js} +8 -8
  64. package/dist/{request-role-cli-Bxxskru9.js.map → request-role-cli-Dy1EgJU9.js.map} +1 -1
  65. package/dist/{request-role-migration-BCW4v0rq.js → request-role-migration-GHTJnPMV.js} +2 -2
  66. package/dist/{request-role-migration-BCW4v0rq.js.map → request-role-migration-GHTJnPMV.js.map} +1 -1
  67. package/dist/{rls-bootstrap-sql-CxszeSc7.js → rls-bootstrap-sql-kPX4-MB1.js} +18 -3
  68. package/dist/rls-bootstrap-sql-kPX4-MB1.js.map +1 -0
  69. package/dist/{rls-enforcement-CyUCPDH8.js → rls-enforcement-Cc_UhOxb.js} +109 -6
  70. package/dist/rls-enforcement-Cc_UhOxb.js.map +1 -0
  71. package/dist/schema/doctor-cli.js +7 -7
  72. package/dist/schema/ensure-collection-policies.d.ts +8 -0
  73. package/dist/schema/generate-drizzle-schema.js +1 -1
  74. package/dist/schema/generate-postgres-ddl-logic.d.ts +9 -0
  75. package/dist/schema/generate-postgres-ddl.js +1 -1
  76. package/dist/schema/introspect-db.js +1 -1
  77. package/dist/schema/plan/types.d.ts +13 -0
  78. package/dist/schema/rls-bootstrap-sql.d.ts +6 -0
  79. package/dist/security/policy-drift.d.ts +13 -1
  80. package/dist/security/rls-enforcement.d.ts +31 -0
  81. package/dist/{websocket-BSYV_KSw.js → websocket-B7ex6AQM.js} +3 -3
  82. package/dist/{websocket-BSYV_KSw.js.map → websocket-B7ex6AQM.js.map} +1 -1
  83. package/package.json +7 -7
  84. package/dist/ensure-collection-policies-DJsOMpaI.js.map +0 -1
  85. package/dist/generate-postgres-ddl-logic-G9PvjHrr.js.map +0 -1
  86. package/dist/plan-schema-CMhNYEYF.js.map +0 -1
  87. package/dist/policy-drift-Bx6663KD.js.map +0 -1
  88. package/dist/render-ddl-Di-fTGti.js.map +0 -1
  89. package/dist/rls-bootstrap-sql-CxszeSc7.js.map +0 -1
  90. package/dist/rls-enforcement-CyUCPDH8.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rebasepro/server-postgres",
3
- "version": "0.29.2",
3
+ "version": "0.29.3",
4
4
  "description": "PostgreSQL data source backend implementation for Rebase with Drizzle ORM",
5
5
  "keywords": [
6
6
  "cms",
@@ -50,11 +50,11 @@
50
50
  "execa": "^9.6.1",
51
51
  "pg": "^8.22.0",
52
52
  "ws": "^8.21.1",
53
- "@rebasepro/codegen": "0.29.2",
54
- "@rebasepro/types": "0.29.2",
55
- "@rebasepro/server": "0.29.2",
56
- "@rebasepro/utils": "0.29.2",
57
- "@rebasepro/common": "0.29.2"
53
+ "@rebasepro/codegen": "0.29.3",
54
+ "@rebasepro/common": "0.29.3",
55
+ "@rebasepro/types": "0.29.3",
56
+ "@rebasepro/utils": "0.29.3",
57
+ "@rebasepro/server": "0.29.3"
58
58
  },
59
59
  "devDependencies": {
60
60
  "@electric-sql/pglite": "0.5.6",
@@ -70,7 +70,7 @@
70
70
  "typescript": "^6.0.3",
71
71
  "vite": "^8.1.5",
72
72
  "vitest": "^4.1.11",
73
- "@rebasepro/client": "0.29.2"
73
+ "@rebasepro/client": "0.29.3"
74
74
  },
75
75
  "gitHead": "d935eefa5aa8d1009a2398cfac2c1e4ee9aeb6b6",
76
76
  "publishConfig": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"ensure-collection-policies-DJsOMpaI.js","names":[],"sources":["../src/schema/ensure-collection-policies.ts"],"sourcesContent":["/**\n * Applying a bundle's RLS policies to a database at boot, idempotently.\n *\n * ## Why this exists\n *\n * {@link ensureCollectionTables} creates the collection *tables* a managed\n * runtime boots against, but a table with row-level security disabled and no\n * policies is not servable: authenticated requests run as the restricted\n * `rebase_user` role, so a read with no `SELECT` policy returns nothing (a\n * public collection answered 401) and a write with no `INSERT`/`UPDATE` policy\n * is denied. The policies live in the collections' `securityRules`; nothing at\n * boot applied them. `rebase db push` does — but it drives Atlas against a\n * local `DATABASE_URL`, and a managed tenant's database is reachable only from\n * inside the cluster, by the runtime that is already connected to it. So the\n * runtime is the only thing that *can* apply them, and this is where it does.\n *\n * ## Why this is safe to run on every boot\n *\n * Every statement is idempotent: `ENABLE ROW LEVEL SECURITY` is only issued for\n * a table the catalogue reports RLS-off (on one that has it, it changes nothing\n * and still queues for an ACCESS EXCLUSIVE lock), and each policy is a `DROP\n * POLICY IF EXISTS` immediately followed by a `CREATE POLICY`, so re-applying\n * asserts exactly the declared state. It adds\n * and replaces; it never drops data. (It does not *reconcile* — a policy a\n * previous push left behind under an old name is not removed here; that stays a\n * `db push` / `db migrate` concern, alongside destructive schema changes.)\n *\n * ## A table whose policies are already the declared ones is left alone\n *\n * Every policy this module writes carries a stamp, `COMMENT ON POLICY … IS\n * 'rebase:<hash>'` (see {@link policyStampSql}). The hash covers the\n * `CREATE POLICY` statement that was rendered *and* the definition Postgres\n * stored for it — command, mode, roles, and the deparsed `USING` / `WITH\n * CHECK` — as read back in the same transaction. A boot recomputes it from the\n * statement it would run now and the definition the catalogue holds now, and\n * re-applies a table only when that differs for any of its policies, a declared\n * policy is missing, a superseded one is still there, or RLS is off.\n *\n * So both halves of \"the declared state\" still win: a rule whose compiled SQL\n * changed (a new rule under the same name, a compiler change) misses on the\n * first half, and a policy someone altered by hand — `ALTER POLICY`, a\n * different role list — misses on the second, and either is re-applied exactly\n * as every boot used to re-apply everything. A boot that changes nothing runs\n * two catalogue reads here, no DDL and takes no table lock. It used to drop and\n * re-create every policy, one ACCESS EXCLUSIVE lock per table: about 1 s at 200\n * collections, and under a `pg_dump` up to the whole retry budget.\n *\n * A policy without a stamp — written by `db push`, by hand, or by a release\n * that predates stamps — counts as different, so the first boot after either\n * re-applies its table once and stamps it. Nothing else reads the comment:\n * drift checks, `doctor`, rls-check and Studio compare names, roles, commands\n * and clauses, never descriptions.\n *\n * Unlike table creation, a failure here is not fatal: RLS stays enabled, so a\n * table whose policies could not be applied fails **closed** (denies) rather\n * than leaking rows. One collection's policy failing (e.g. a rule that\n * references a table a real migration has not created yet) must not crash-loop\n * the whole deployment and take the other collections' working routes down with\n * it. Failures are reported loudly and per-table so the operator can see\n * exactly which collection is not yet servable and why.\n */\nimport { createHash } from \"node:crypto\";\nimport { REBASE_ADMIN_ROLE, type CollectionConfig } from \"@rebasepro/types\";\nimport { toPostgresIdentifier } from \"@rebasepro/utils\";\nimport { planCollectionPolicies, type CollectionPolicyPlan } from \"./generate-postgres-ddl-logic\";\nimport { isGeneratedPolicyName } from \"../security/policy-drift\";\nimport { describeDriverError, type Queryable } from \"./ensure-collection-tables\";\nimport { assertSafeIdentifier } from \"./plan/diff-plan\";\nimport { quoteSqlLiteral } from \"./generate-postgres-ddl-logic\";\nimport { revokeUserRoleSql } from \"../security/rls-enforcement\";\nimport { ensureAdminPolicyRole } from \"./rls-bootstrap-sql\";\nimport {\n atomicBatch,\n isLockTimeout,\n isMultiStatementRefusal,\n resolveBootLockOptions,\n sleep,\n type BootLockOptions,\n type ResolvedBootLockOptions\n} from \"./boot-ddl\";\n\nexport interface PolicyEnsureResult {\n /** `CREATE POLICY` statements that ran successfully. */\n policiesApplied: number;\n /** Tables that had RLS enabled — including the {@link unchanged} ones, which already had it. */\n tablesSecured: number;\n /**\n * Tables whose policies were already exactly the declared ones, RLS on, by\n * the stamp each policy carries — left alone: no statement, no lock.\n */\n unchanged: number;\n /** Declared tables absent from the database — left to a real migration. */\n skipped: { table: string; reason: string }[];\n /**\n * Tables that have RLS on but did not get every policy. They deny — RLS\n * with no matching policy is deny-all — so they are safe but not servable.\n */\n failures: { table: string; error: string }[];\n /**\n * Tables RLS could not be enabled on, whose DML grant was withdrawn instead.\n *\n * This state had no name, and that was the bug: `ENABLE ROW LEVEL SECURITY`\n * failing was recorded as a `failure` and reported with the same \"it stays\n * locked (denies)\" wording as a failed policy — but the two are opposites.\n * A policy statement failing leaves RLS on and the table denying. `enableRls`\n * failing leaves RLS *off*, and the schema-wide grant to the user role has\n * already been made by `ensureRlsEnforcement`, so the table is readable and\n * writable by every authenticated request with no row filtering at all.\n */\n unsecured: { table: string; error: string; grantWithdrawn: boolean }[];\n /**\n * Generated policies removed because no current rule produces them.\n *\n * A policy's name embeds a hash of the rule's semantics, so editing a rule\n * does not update a policy — it creates a new one and abandons the old.\n * Postgres ORs permissive policies, so the abandoned one keeps granting:\n * a `USING (true)` tightened to an owner check went on admitting everyone,\n * forever, while the deploy logged success.\n *\n * `db push` reconciles this, and cannot reach a managed tenant's in-cluster\n * database — which is the reason this module exists. So boot has to do it.\n */\n orphansDropped: number;\n /**\n * Tables whose policies were not re-applied because another session held\n * the table's lock for every attempt — a long transaction, a report, a\n * dump. Each table's policy statements run in one transaction, so a table\n * here was left exactly as it was: RLS on, its existing policies in force.\n * `rulesChanged` says whether those differ from the declared ones by name\n * (a rule whose policy is missing, or an orphan still granting), in which\n * case the new rules are not in force on this table until a later boot.\n */\n deferred: { table: string; error: string; rulesChanged: boolean }[];\n /**\n * Tables whose collection declares no rule of its own and which still held\n * generated rule policies, all of them dropped: the generated policies, by\n * name, the boot is to warn about.\n *\n * An edited rule supersedes its old policy, and that drop is the point of\n * {@link PolicyEnsureResult.orphansDropped}. A collection with no rule at\n * all is something else: what a collection looks like when the\n * `defaultSecurityRules` its directory's index declares never reached it —\n * an array handed to a backend without them. Dropping is still right (the\n * declared state wins, and the table is left admin-only rather than open),\n * but it changes who can read the table on every server sharing the\n * database, so it is not done in silence.\n */\n rulesDropped: { table: string; policies: string[] }[];\n}\n\nconst isCreatePolicy = (statement: string): boolean => /^\\s*CREATE POLICY/i.test(statement);\n\n/**\n * The name a `CREATE POLICY` statement's policy is stored under, or undefined\n * for any other statement.\n *\n * Postgres keeps the first 63 bytes of an identifier, and a rule's policy name\n * can be longer (`<table>_<op>_<hash>_<i>` on a 48-byte table is 65). Every\n * name read back from the catalogue is the stored one, so the plan's names are\n * compared in that form too. Compared as written, the policy just created was\n * not among the planned names, matched the generated shape once cut, and the\n * next boot dropped it as an orphan — a restrictive gate included, leaving the\n * grants beside it to answer alone.\n */\nconst createdPolicyName = (statement: string): string | undefined => {\n const match = /^\\s*CREATE POLICY\\s+\"([^\"]+)\"/i.exec(statement);\n return match ? toPostgresIdentifier(match[1]) : undefined;\n};\n\n/** The policy names a plan creates, as Postgres stores them. */\nconst plannedPolicyNames = (plan: CollectionPolicyPlan): Set<string> => {\n const expected = new Set<string>();\n for (const statement of plan.policyStatements) {\n const name = createdPolicyName(statement);\n if (name) expected.add(name);\n }\n return expected;\n};\n\n/**\n * Generated policies on this table that the current plan does not produce.\n *\n * Scoped hard, because dropping a policy is destructive: only this one table,\n * only names matching the generated `<table>_<op>_<sha1>` shape, and only names\n * absent from the plan. A hand-written policy, or one belonging to another\n * table, is never touched — `isGeneratedPolicyName` is the same predicate `db\n * push` uses to draw that line.\n *\n * Computed from the names read before anything is applied. The plan only ever\n * drops and re-creates its own names, so \"present before, not planned\" is the\n * same set the old read-after-apply found.\n */\nconst orphansOf = (plan: CollectionPolicyPlan, present: readonly string[]): string[] => {\n const expected = plannedPolicyNames(plan);\n return present.filter(name => !expected.has(name) && isGeneratedPolicyName(name, plan.table));\n};\n\nconst dropPolicySql = (plan: CollectionPolicyPlan, name: string): string =>\n `DROP POLICY IF EXISTS \"${name}\" ON \"${plan.schema}\".\"${plan.table}\"`;\n\n/** What every policy stamp starts with. See {@link policyStampSql}. */\nexport const POLICY_STAMP_PREFIX = \"rebase:\";\n\nconst sha256Hex = (text: string): string => createHash(\"sha256\").update(text, \"utf8\").digest(\"hex\");\n\n/** The same digest, computed by Postgres: hex SHA-256 of the text's UTF-8 bytes. */\nconst sha256Sql = (expression: string): string => `encode(sha256(convert_to(${expression}, 'UTF8')), 'hex')`;\n\n/**\n * The definition Postgres holds for the `pg_policy` row aliased `p`, as one\n * text: command, permissive/restrictive, the role OIDs, and the deparsed\n * `USING` and `WITH CHECK` (`-` for an absent clause, so absent and empty\n * differ). Everything `ALTER POLICY` can change, and everything a `CREATE\n * POLICY` sets.\n *\n * Read back with `pg_get_expr`, whose spelling depends on `search_path` (a\n * name on the path prints unqualified). The stamp is written and checked by\n * the same boot connections, so the two agree; a process with a different\n * path would only disagree, and re-apply — what every boot did before stamps.\n */\nconst liveDefinitionSql = (p: string): string =>\n `concat_ws(E'\\\\n', ${p}.polcmd::text, ${p}.polpermissive::text, ${p}.polroles::text, ` +\n `coalesce(pg_get_expr(${p}.polqual, ${p}.polrelid), '-'), ` +\n `coalesce(pg_get_expr(${p}.polwithcheck, ${p}.polrelid), '-'))`;\n\n/** The stamp a policy rendered as `renderedHash` carries when its stored definition hashes to `liveHash`. */\nconst stampOf = (renderedHash: string, liveHash: string): string =>\n `${POLICY_STAMP_PREFIX}${sha256Hex(`${renderedHash}:${liveHash}`)}`;\n\n/** The policies a plan creates, by name, each with the hash of its `CREATE POLICY` statement. */\nconst renderedHashes = (plan: CollectionPolicyPlan): Map<string, string> => {\n const hashes = new Map<string, string>();\n for (const statement of plan.policyStatements) {\n const name = createdPolicyName(statement);\n if (name) hashes.set(name, sha256Hex(statement.trim()));\n }\n return hashes;\n};\n\n/**\n * One statement that stamps every policy the plan just created on its table:\n * `COMMENT ON POLICY … IS 'rebase:<hash>'`, the hash taken over the rendered\n * statement's hash and the definition Postgres stored — read back here, after\n * the `CREATE`s, in the same transaction. A `DO` block because the stored\n * definition is only known once the policy exists, and a `COMMENT` takes a\n * literal. One line, and it names only this table.\n *\n * `undefined` for a table the plan gives no policies.\n *\n * @param only the names to stamp, when not every policy on the table is known\n * to be what its statement makes — see `stampPoliciesStoredAsRendered`.\n */\nexport function policyStampSql(plan: CollectionPolicyPlan, only?: ReadonlySet<string>): string | undefined {\n const hashes = new Map([...renderedHashes(plan)].filter(([name]) => !only || only.has(name)));\n if (hashes.size === 0) return undefined;\n const target = `\"${plan.schema}\".\"${plan.table}\"`;\n const values = [...hashes].map(([name, hash]) => `(${quoteSqlLiteral(name)}, '${hash}')`).join(\", \");\n const stamp = `${quoteSqlLiteral(POLICY_STAMP_PREFIX)} || ${sha256Sql(`s.rendered || ':' || ${sha256Sql(liveDefinitionSql(\"p\"))}`)}`;\n return \"DO $rebase_policy_stamp$ DECLARE r record; BEGIN \" +\n `FOR r IN SELECT p.polname AS name, ${stamp} AS stamp FROM pg_policy p ` +\n `JOIN (VALUES ${values}) AS s(name, rendered) ON s.name = p.polname ` +\n `WHERE p.polrelid = ${quoteSqlLiteral(target)}::regclass LOOP ` +\n `EXECUTE 'COMMENT ON POLICY ' || quote_ident(r.name) || ${quoteSqlLiteral(` ON ${target} IS `)} || quote_literal(r.stamp); ` +\n \"END LOOP; END $rebase_policy_stamp$;\";\n}\n\n/** One policy as the catalogue has it. */\ninterface LivePolicy {\n /** Its comment — a stamp, when this module wrote it. */\n stamp: string | null;\n /** Hex SHA-256 of {@link liveDefinitionSql}. */\n live: string;\n}\n\n/**\n * Every policy on every table in the declared schemas — name, stamp and a hash\n * of its stored definition — in one read. It replaced a `pg_policies` query\n * per table, and later the name-only read that preceded stamps.\n */\nasync function readLivePolicies(client: Queryable, schemas: string[]): Promise<Map<string, Map<string, LivePolicy>>> {\n const policies = new Map<string, Map<string, LivePolicy>>();\n if (schemas.length === 0) return policies;\n const inList = schemas.map(schema => `'${assertSafeIdentifier(schema, \"schema name\")}'`).join(\", \");\n const { rows } = await client.query<{\n schemaname: string; tablename: string; policyname: string; stamp?: string | null; live?: string | null;\n }>(\n `SELECT n.nspname AS schemaname, c.relname AS tablename, p.polname AS policyname,\n obj_description(p.oid, 'pg_policy') AS stamp, ${sha256Sql(liveDefinitionSql(\"p\"))} AS live\n FROM pg_policy p\n JOIN pg_class c ON c.oid = p.polrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname IN (${inList})`\n );\n for (const row of rows) {\n const key = `${row.schemaname}.${row.tablename}`;\n if (!policies.has(key)) policies.set(key, new Map());\n policies.get(key)!.set(row.policyname, { stamp: row.stamp ?? null, live: row.live ?? \"\" });\n }\n return policies;\n}\n\n/**\n * Whether every policy the plan declares is on the table, stamped for exactly\n * the statement the plan would run and exactly the definition it holds now.\n */\nconst policiesAreCurrent = (plan: CollectionPolicyPlan, present: Map<string, LivePolicy>): boolean => {\n for (const [name, renderedHash] of renderedHashes(plan)) {\n const policy = present.get(name);\n if (!policy || policy.stamp !== stampOf(renderedHash, policy.live)) return false;\n }\n return true;\n};\n\n/**\n * What its stamp says of a declared policy the database has: written by Rebase\n * from the statement the plan renders now and still holding that definition\n * (`current`), stamped once but changed since — the rule's SQL, or the policy\n * by hand (`stale`), or carrying no stamp at all, so nothing tells whether a\n * re-apply changes it (`unstamped`).\n */\nexport type PolicyStampState = \"current\" | \"stale\" | \"unstamped\";\n\n/**\n * Every declared policy the database holds, by `schema.table`, then name, with\n * its {@link PolicyStampState}. The comparison a boot makes to leave a table\n * alone, read for each policy instead of each table.\n *\n * The stored definition is read with `pg_get_expr`, whose spelling depends on\n * `search_path`: call it under the path the stamps were written under (a\n * boot's, `public` unless the URL pins one), or a current stamp reads stale.\n */\nexport async function readPolicyStamps(\n client: Queryable,\n collections: CollectionConfig[],\n options: { adminRoleAvailable?: boolean } = {}\n): Promise<Map<string, Map<string, PolicyStampState>>> {\n // Stamped from the statement the boot or the push rendered: `TO public`\n // for the server-or-admin policies where the admin switch is not live.\n const plans = planCollectionPolicies(collections, { adminRoleAvailable: options.adminRoleAvailable });\n const live = await readLivePolicies(client, Array.from(new Set(plans.map(p => p.schema))));\n const states = new Map<string, Map<string, PolicyStampState>>();\n for (const plan of plans) {\n const present = live.get(plan.qualified);\n if (!present) continue;\n const table = new Map<string, PolicyStampState>();\n for (const [name, renderedHash] of renderedHashes(plan)) {\n const policy = present.get(name);\n if (!policy) continue;\n table.set(name, policy.stamp === null || !policy.stamp.startsWith(POLICY_STAMP_PREFIX)\n ? \"unstamped\"\n : policy.stamp === stampOf(renderedHash, policy.live) ? \"current\" : \"stale\");\n }\n states.set(plan.qualified, table);\n }\n return states;\n}\n\n/** The name a probed policy is made under, in a transaction nothing commits. */\nconst PROBE_POLICY = \"rebase_policy_probe\";\n\n/**\n * For each of `policies`, whether the `CREATE POLICY` the plan renders for it\n * stores the definition the database holds now: made under a probe name on\n * the same table, read back, compared with the one there, and rolled back.\n *\n * What a stamp cannot answer. A stamp covers the statement as rendered, so a\n * rule whose text differs from the one that made the policy reads as changed\n * though Postgres would store the same thing: `schema introspect` writes a role\n * rule back as its deparsed SQL, and every such policy was planned as a\n * replacement of itself. A policy `db migrate` created has no stamp at all.\n *\n * One short transaction per policy, which takes the table's lock for as long\n * as it lasts and gives up on it after two seconds. A policy that could not be\n * probed — no statement for it, a lock not granted, a rule that does not\n * parse — is left out of the answer, and the caller keeps what the stamp said.\n * Keyed `schema.table.name`.\n */\nexport async function probeRenderedPolicies(\n client: Queryable,\n collections: CollectionConfig[],\n policies: readonly { schema: string; table: string; name: string }[],\n options: { searchPath?: string; adminRoleAvailable?: boolean } = {}\n): Promise<Map<string, boolean>> {\n const statements = new Map<string, string>();\n for (const plan of planCollectionPolicies(collections, { adminRoleAvailable: options.adminRoleAvailable })) {\n for (const statement of plan.policyStatements) {\n const name = createdPolicyName(statement);\n if (name) statements.set(`${plan.schema}.${plan.table}.${name}`, statement.trim());\n }\n }\n const answers = new Map<string, boolean>();\n for (const policy of policies) {\n const key = `${policy.schema}.${policy.table}.${policy.name}`;\n const statement = statements.get(key);\n if (!statement) continue;\n const probe = statement.replace(/^(\\s*CREATE POLICY\\s+)\"[^\"]+\"/i, `$1\"${PROBE_POLICY}\"`);\n const target = `\"${policy.schema.replace(/\"/g, '\"\"')}\".\"${policy.table.replace(/\"/g, '\"\"')}\"`;\n // Literals rather than parameters: a boot's `Queryable` takes none.\n const definition = (name: string): string =>\n `(SELECT ${liveDefinitionSql(\"p\")} FROM pg_policy p ` +\n `WHERE p.polrelid = ${quoteSqlLiteral(target)}::regclass AND p.polname = ${quoteSqlLiteral(name)})`;\n try {\n await client.query(\"BEGIN\");\n await client.query(\"SET LOCAL lock_timeout = '2s'\");\n if (options.searchPath) await client.query(`SET LOCAL search_path TO ${options.searchPath}`);\n await client.query(probe);\n const { rows } = await client.query<{ same: boolean | null }>(\n `SELECT ${definition(PROBE_POLICY)} IS NOT DISTINCT FROM ${definition(policy.name)} AS same`\n );\n if (typeof rows[0]?.same === \"boolean\") answers.set(key, rows[0].same);\n } catch {\n // Not probed; see above.\n } finally {\n await client.query(\"ROLLBACK\").catch(() => undefined);\n }\n }\n return answers;\n}\n\n/**\n * Every declared schema's tables, and whether each has row-level security on.\n *\n * One catalogue read for the whole step. It replaced a full `readExistingSchema`\n * — eight catalogue queries and a row probe of every table, of which only the\n * table names were used — and it carries the one fact that lets a boot leave an\n * already-locked table alone: `relrowsecurity`.\n *\n * Presence is still decided by `information_schema.columns`, as it was: the\n * same relations (views included, which have no RLS and are closed by revoking,\n * exactly as before) and the same privilege filter.\n */\nasync function readTableSecurity(client: Queryable, schemas: string[]): Promise<Map<string, { rls: boolean }>> {\n const tables = new Map<string, { rls: boolean }>();\n if (schemas.length === 0) return tables;\n const inList = schemas.map(schema => `'${assertSafeIdentifier(schema, \"schema name\")}'`).join(\", \");\n const { rows } = await client.query<{ table_schema: string; table_name: string; rls: boolean | null }>(\n `SELECT t.table_schema, t.table_name, c.relrowsecurity AS rls\n FROM (SELECT DISTINCT table_schema, table_name FROM information_schema.columns\n WHERE table_schema IN (${inList})) t\n JOIN pg_namespace n ON n.nspname = t.table_schema\n JOIN pg_class c ON c.relnamespace = n.oid AND c.relname = t.table_name`\n );\n for (const row of rows) tables.set(`${row.table_schema}.${row.table_name}`, { rls: row.rls === true });\n return tables;\n}\n\n/**\n * Whether the catalogue says RLS is on for one table, read fresh. `false` when\n * it cannot be read, which sends the caller down the fail-closed path.\n */\nasync function rlsIsOn(client: Queryable, plan: CollectionPolicyPlan): Promise<boolean> {\n try {\n const { rows } = await client.query<{ rls: boolean }>(\n `SELECT c.relrowsecurity AS rls FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ${quoteSqlLiteral(plan.schema)} AND c.relname = ${quoteSqlLiteral(plan.table)}`\n );\n return rows[0]?.rls === true;\n } catch {\n return false;\n }\n}\n\n/** What one table's `ENABLE ROW LEVEL SECURITY` came to. */\ntype TableLock =\n | { locked: true }\n | { locked: false; error: string; grantWithdrawn: boolean };\n\n/**\n * Switch RLS on for one table, or — when Postgres refuses — take the user\n * role's privileges on it back, so the table is unreachable rather than\n * unprotected.\n *\n * A table the catalogue already reports RLS-on is left alone. `ENABLE` on it\n * changes nothing, and it is not free: it queues for an `ACCESS EXCLUSIVE` lock,\n * so a boot that met a long reader held every live query on that table behind\n * it — and when the wait ended in a timeout, the catch below revoked the user\n * role's privileges on a table that had been protected all along. Every\n * replica shares the grants, so one boot during a `pg_dump` closed the\n * collection for the whole deployment until the next clean boot.\n */\nasync function lockTable(\n client: Queryable,\n plan: CollectionPolicyPlan,\n rlsOn: boolean,\n run: (sql: string) => Promise<unknown> = sql => client.query(sql)\n): Promise<TableLock> {\n if (rlsOn) return { locked: true };\n try {\n await run(plan.enableRls);\n return { locked: true };\n } catch (err) {\n // The database's own answer, not the ORM's wrapper — see\n // `describeDriverError`. This is the most consequential message in\n // the file: it is what the operator reads about a table that is now\n // denying every request, and `Failed query: <the statement>` told\n // them nothing they did not already have.\n const error = describeDriverError(err);\n // A failed statement says nothing about the state it meant to reach: a\n // lock or statement timeout, a cancelled query, a peer that enabled it\n // first. Ask the catalogue. Only a table that really is RLS-off is\n // revoked — that safety is unchanged; a read that fails counts as off.\n if (await rlsIsOn(client, plan)) return { locked: true };\n // Take the privilege back rather than serve an unprotected table.\n // This is the fail-closed step the old code assumed it already had:\n // per-table, so one collection cannot take the rest of the\n // deployment down, but leaving nothing readable without RLS.\n //\n // Quoted, like every other statement here: unquoted, Postgres folds\n // the name to lower case, so a mixed-case adopted table (`\"User\"`)\n // was revoked as `public.user` — which fails, and a table that could\n // have been closed refused the boot instead.\n return withdrawGrant(client, plan, error);\n }\n}\n\n/**\n * Take the user role's privileges on a table back, so an RLS-off table is\n * unreachable rather than unprotected. `REVOKE` waits for no table lock a\n * reader holds, so it runs as a plain statement.\n */\nasync function withdrawGrant(client: Queryable, plan: CollectionPolicyPlan, error: string): Promise<TableLock> {\n try {\n await client.query(revokeUserRoleSql(plan.schema, plan.table));\n return { locked: false, error, grantWithdrawn: true };\n } catch {\n // Reported with `grantWithdrawn: false`, which the caller escalates.\n // There is nothing else this can do to make the table safe.\n return { locked: false, error, grantWithdrawn: false };\n }\n}\n\nexport interface TableLockResult {\n /** Tables RLS is now on for. */\n locked: number;\n /** Tables it could not be switched on for. See {@link PolicyEnsureResult.unsecured}. */\n unsecured: PolicyEnsureResult[\"unsecured\"];\n}\n\n/**\n * Switch RLS on for every table the collections declare — each collection's\n * and each junction's — and do nothing else.\n *\n * The first thing `rebase db push` does once Atlas has committed. Atlas cannot\n * carry `ENABLE ROW LEVEL SECURITY` (its free tier neither plans nor reads it),\n * so a table it creates arrives with RLS off — while the user role already\n * holds DML on it through the schema's default privileges. Everything push runs\n * after Atlas can refuse: the vector, search and trigger DDL, the policies\n * themselves. Locking first means none of those failures can leave a table\n * open: RLS with no policy denies, which is a state a failed push may leave.\n *\n * A declared table that is not in the database is skipped — nothing can reach\n * a table that does not exist, and the step that creates it locks it.\n */\nexport async function lockCollectionTables(\n client: Queryable,\n collections: CollectionConfig[]\n): Promise<TableLockResult> {\n const result: TableLockResult = { locked: 0, unsecured: [] };\n for (const { plan, rls } of await declaredTablesPresent(client, collections)) {\n const lock = await lockTable(client, plan, rls);\n if (lock.locked) {\n result.locked++;\n } else {\n result.unsecured.push({ table: plan.qualified, error: lock.error, grantWithdrawn: lock.grantWithdrawn });\n }\n }\n return result;\n}\n\n/**\n * The declared tables {@link lockCollectionTables} would switch row-level\n * security on for: those in the database with it off. What `db push\n * --dry-run` lists, read the way the push's lock step reads it.\n */\nexport async function tablesRlsWouldEnable(client: Queryable, collections: CollectionConfig[]): Promise<string[]> {\n return (await declaredTablesPresent(client, collections)).filter(table => !table.rls).map(table => table.plan.qualified);\n}\n\n/** Each declared table the database has, with whether its RLS is on. */\nasync function declaredTablesPresent(\n client: Queryable,\n collections: CollectionConfig[]\n): Promise<{ plan: CollectionPolicyPlan; rls: boolean }[]> {\n const plans = planCollectionPolicies(collections);\n if (plans.length === 0) return [];\n const tables = await readTableSecurity(client, Array.from(new Set(plans.map(p => p.schema))));\n return plans.flatMap(plan => {\n const table = tables.get(plan.qualified);\n return table ? [{ plan, rls: table.rls }] : [];\n });\n}\n\n/** One declared table that exists, and what the catalogue said about it. */\ninterface TableWork {\n plan: CollectionPolicyPlan;\n rlsOn: boolean;\n orphans: string[];\n /** Whether the policy names on the table differ from the plan's. */\n rulesChanged: boolean;\n /** Whether the plan holds no generated rule of its own, so the orphans are every rule the table had. */\n declaresNoRule: boolean;\n}\n\ntype AtomicOutcome =\n | { kind: \"applied\" }\n | { kind: \"lock-timeout\"; error: string }\n | { kind: \"unsupported\" }\n | { kind: \"failed\"; error: string };\n\n/**\n * Bring the declared collections' RLS policies up to date. Returns what it did.\n *\n * Only tables that already exist are touched: the boot-time table creator runs\n * first, so anything still missing is a table this additive path did not\n * create (it creates junctions too) — one a failed boot DDL left out, or a\n * project whose schema a migration owns. Enabling RLS on a\n * non-existent table would error, so those are recorded as skipped, not failed.\n *\n * ## One transaction per table\n *\n * Each table's statements — `ENABLE` when RLS is off, every `DROP POLICY IF\n * EXISTS` / `CREATE POLICY` pair, the orphan drops — go to Postgres as one\n * string, which it runs as one transaction (see `boot-ddl`). Before, each was\n * its own autocommit: at 240 tables, 4,080 commits and 4,080 ACCESS EXCLUSIVE\n * lock acquisitions per boot, 6–22 s on a disk that really flushes. And between\n * a policy's DROP and its CREATE, every other replica evaluated the table with\n * that policy missing — a user's continuous reads of their own row came back\n * empty once per boot (measured, Postgres 18). Now a concurrent request sees the\n * old policies or the new ones, never neither.\n *\n * If the transaction fails for any reason but a lock timeout, the table is\n * applied again one statement at a time — so a rule that cannot be created (a\n * function a migration has not added yet) leaves the table in a deny-leaning\n * partial state rather than rolling back to the old, possibly looser,\n * policies. Deny-leaning holds for restrictive rules too: they are applied\n * first, and one that cannot be created is replaced by a restrictive policy\n * that passes nothing, never left out from under the grants.\n *\n * ## Lock budget\n *\n * The transaction runs under `lock_timeout` (`boot-ddl`), so a table that a\n * long transaction, a report or a dump is holding costs live traffic one\n * second, not the statement timeout. A contended table is retried after the\n * others, with backoff, within a retry budget for the whole step; one still\n * held after that is reported in `deferred` — its transaction rolled back, so\n * it is exactly as it was before this boot — or, if RLS was off on it, closed\n * by revoking the user role's grant, like every table RLS cannot be enabled on.\n */\nexport async function ensureCollectionPolicies(\n client: Queryable,\n collections: CollectionConfig[],\n log?: (message: string) => void,\n options: BootLockOptions & {\n /**\n * Whether this server's admin switch is live (`settleAdminSwitch`).\n * `false` writes the server-or-admin policies `TO public` and creates\n * no role: written `TO rebase_admin` while admin requests run as the\n * request role, they would refuse every admin caller. Left out, they\n * go `TO rebase_admin` wherever that role exists or can be made.\n */\n adminRoleAvailable?: boolean;\n } = {}\n): Promise<PolicyEnsureResult> {\n const result: PolicyEnsureResult = {\n policiesApplied: 0, tablesSecured: 0, unchanged: 0, skipped: [], failures: [], unsecured: [],\n orphansDropped: 0, deferred: [], rulesDropped: []\n };\n\n let plans = planCollectionPolicies(collections);\n if (plans.length === 0) return result;\n // The server-or-admin policies are written `TO rebase_admin`\n // (`rls.adminPolicies: \"adminRole\"`), and CREATE POLICY refuses a role that\n // does not exist; nothing guarantees this step runs after the one that\n // makes it. Where it cannot be made — a connection without CREATEROLE, a\n // role nobody pre-created — those policies are written `TO public`, as they\n // were before, rather than dropped and left uncreatable: admin requests then\n // keep running as the request role (`settleAdminRequestRoles`), which is\n // what `TO public` serves. A boot whose admin switch is not live says so\n // (`adminRoleAvailable: false`), and gets the same: an existing\n // `rebase_admin` — another project's, a privileged push's — is not enough.\n if (options.adminRoleAvailable === false) {\n plans = planCollectionPolicies(collections, { adminRoleAvailable: false });\n } else if (plans.some(plan => plan.policies.some(policy => policy.adminTarget))) {\n const run = async (text: string) => (await client.query<Record<string, unknown>>(text)).rows;\n const available = await ensureAdminPolicyRole(run).then(() => true, (err: unknown) => {\n log?.(`the \"${REBASE_ADMIN_ROLE}\" role does not exist and could not be created (${describeDriverError(err)}); ` +\n \"the server-or-admin policies stay TO public, and signed-in users' owner-scoped reads keep scanning\");\n return false;\n });\n if (!available) plans = planCollectionPolicies(collections, { adminRoleAvailable: false });\n }\n const lock = resolveBootLockOptions(options);\n\n const schemas = Array.from(new Set(plans.map(p => p.schema)));\n const tables = await readTableSecurity(client, schemas);\n const livePolicies = await readLivePolicies(client, schemas);\n\n const work: TableWork[] = [];\n for (const plan of plans) {\n const table = tables.get(plan.qualified);\n if (!table) {\n result.skipped.push({\n table: plan.qualified,\n reason: \"table is not present in the database; create it with `rebase db push` / `rebase db migrate`\"\n });\n continue;\n }\n const live = livePolicies.get(plan.qualified) ?? new Map<string, LivePolicy>();\n const present = [...live.keys()];\n const orphans = orphansOf(plan, present);\n // Already exactly what the plan would leave: nothing to run, no lock to take.\n if (table.rls && orphans.length === 0 && policiesAreCurrent(plan, live)) {\n result.tablesSecured++;\n result.unchanged++;\n continue;\n }\n const presentSet = new Set(present);\n const rulesChanged = orphans.length > 0 || [...plannedPolicyNames(plan)].some(name => !presentSet.has(name));\n const declaresNoRule = ![...plannedPolicyNames(plan)].some(name => isGeneratedPolicyName(name, plan.table));\n work.push({ plan, rlsOn: table.rls, orphans, rulesChanged, declaresNoRule });\n }\n if (result.unchanged > 0) {\n log?.(`${result.unchanged} table(s) already have exactly the declared policies; left as they are`);\n }\n\n // Until the handle refuses a multi-statement string (an extended-protocol\n // driver), after which every table goes one statement at a time.\n let atomic = true;\n let retryBudget = lock.retryBudgetMs;\n let queue = work;\n let lastError = new Map<TableWork, string>();\n\n for (let attempt = 1; queue.length > 0; attempt++) {\n if (attempt > 1) {\n if (attempt > lock.attempts || retryBudget <= 0) break;\n await sleep(lock.backoffMs(attempt - 1));\n }\n const contended: TableWork[] = [];\n const errors = new Map<TableWork, string>();\n for (const table of queue) {\n if (attempt > 1 && retryBudget <= 0) {\n contended.push(table);\n errors.set(table, lastError.get(table) ?? \"\");\n continue;\n }\n if (atomic) {\n const outcome = await applyAtomically(client, table, lock);\n if (outcome.kind === \"applied\") {\n record(result, table, log);\n continue;\n }\n if (outcome.kind === \"lock-timeout\") {\n if (attempt > 1) retryBudget -= lock.lockTimeoutMs;\n contended.push(table);\n errors.set(table, outcome.error);\n continue;\n }\n if (outcome.kind === \"unsupported\") {\n atomic = false;\n } else {\n log?.(`${table.plan.qualified}: applying its policies in one transaction failed ` +\n `(${outcome.error}); applying them one statement at a time`);\n }\n }\n await applyEachStatement(client, table, result, log, atomic ? lock : undefined);\n }\n queue = contended;\n lastError = errors;\n }\n\n // Still contended after every attempt the budget allowed.\n for (const table of queue) {\n await giveUp(client, table, lastError.get(table) ?? \"\", lock, result);\n }\n\n return result;\n}\n\n/**\n * The table's statements, in the order they must run — the stamp last, so it\n * reads back the policies this same transaction created.\n */\nconst statementsOf = (table: TableWork): string[] => {\n const stamp = policyStampSql(table.plan);\n return [\n ...(table.rlsOn ? [] : [table.plan.enableRls]),\n ...table.plan.policyStatements,\n ...table.orphans.map(name => dropPolicySql(table.plan, name)),\n ...(stamp ? [stamp] : [])\n ];\n};\n\nasync function applyAtomically(\n client: Queryable,\n table: TableWork,\n lock: ResolvedBootLockOptions\n): Promise<AtomicOutcome> {\n const statements = statementsOf(table);\n if (statements.length === 0) return { kind: \"applied\" };\n try {\n await client.query(atomicBatch(statements, lock.lockTimeoutMs));\n return { kind: \"applied\" };\n } catch (err) {\n if (isLockTimeout(err)) return { kind: \"lock-timeout\", error: describeDriverError(err) };\n if (isMultiStatementRefusal(err)) return { kind: \"unsupported\" };\n return { kind: \"failed\", error: describeDriverError(err) };\n }\n}\n\n/**\n * The warning a boot gives for one entry of {@link PolicyEnsureResult.rulesDropped}:\n * each policy, what it means for the table, and the likely cause.\n */\nexport function describeRulesDropped(dropped: { table: string; policies: string[] }): string {\n return `🔐 [rls] \"${dropped.table}\" declares no securityRules, so the policies its rules had made were dropped: ` +\n `${dropped.policies.join(\", \")}. Only administrators reach its rows now, on every server sharing this database. ` +\n \"If its collection came in an array handed to createRebaseBackend, that array lacked the defaultSecurityRules \" +\n \"its config/collections/index.ts declares: pass collectionsDir, or the array that index exports, which carries \" +\n \"them. If the rules were removed on purpose, this is that change.\";\n}\n\n/** The orphans just dropped, when they were every rule the table had. See {@link PolicyEnsureResult.rulesDropped}. */\nfunction recordRulesDropped(result: PolicyEnsureResult, table: TableWork): void {\n if (table.declaresNoRule && table.orphans.length > 0) {\n result.rulesDropped.push({ table: table.plan.qualified, policies: [...table.orphans].sort() });\n }\n}\n\nfunction record(result: PolicyEnsureResult, table: TableWork, log?: (message: string) => void): void {\n const created = table.plan.policyStatements.filter(isCreatePolicy).length;\n result.tablesSecured++;\n result.policiesApplied += created;\n result.orphansDropped += table.orphans.length;\n recordRulesDropped(result, table);\n log?.(`${table.plan.qualified}: RLS enabled, ${created} policy(ies) applied` +\n (table.orphans.length > 0 ? `, ${table.orphans.length} orphan(s) dropped` : \"\"));\n}\n\n/**\n * The table applied one statement at a time — the path every table took before\n * the per-table transaction, kept as its fallback so a failure ends exactly\n * where it always did.\n *\n * Each statement still carries the lock budget when the handle can take it.\n */\nasync function applyEachStatement(\n client: Queryable,\n table: TableWork,\n result: PolicyEnsureResult,\n log: ((message: string) => void) | undefined,\n lock: ResolvedBootLockOptions | undefined\n): Promise<void> {\n const { plan } = table;\n const run = (sql: string) => client.query(lock ? atomicBatch([sql], lock.lockTimeoutMs) : sql);\n\n // Enabling RLS is its own step, because its failure is the opposite of\n // every other failure here. Once RLS is on, anything that goes wrong\n // afterwards leaves the table denying; while it is off, the grant made\n // earlier in boot leaves the table wide open. Sharing one `try` meant\n // the dangerous case was reported in the safe case's words.\n const locked = await lockTable(client, plan, table.rlsOn, run);\n if (!locked.locked) {\n result.unsecured.push({ table: plan.qualified, error: locked.error, grantWithdrawn: locked.grantWithdrawn });\n return;\n }\n result.tablesSecured++;\n\n // The restrictive gates go in before any grant, and a gate that cannot be\n // created is replaced by one that passes nothing. A restrictive policy is\n // ANDed over the permissive ones, so a missing gate is not a denial: the\n // grants made beside it would answer alone, and a tenancy or admin-write\n // gate that failed to apply let every grant through it.\n let created = 0;\n let gateError: string | undefined;\n for (const policy of plan.policies.filter(p => p.restrictive)) {\n try {\n for (const statement of policy.statements) await run(statement);\n result.policiesApplied++;\n created++;\n } catch (err) {\n gateError ??= `${policy.name}: ${describeDriverError(err)}`;\n try {\n for (const statement of policy.denying ?? []) await run(statement);\n } catch (denyErr) {\n // Neither the gate nor its stand-in is in place, so the grants\n // already on the table answer alone: closed the way a table RLS\n // cannot be enabled on is.\n result.tablesSecured--;\n const closed = await withdrawGrant(client, plan,\n `restrictive policy ${gateError}; its denying stand-in failed too: ${describeDriverError(denyErr)}`);\n if (!closed.locked) {\n result.unsecured.push({ table: plan.qualified, error: closed.error, grantWithdrawn: closed.grantWithdrawn });\n }\n return;\n }\n }\n }\n\n try {\n for (const policy of plan.policies.filter(p => !p.restrictive)) {\n for (const statement of policy.statements) await run(statement);\n result.policiesApplied++;\n created++;\n }\n if (gateError) throw new Error(`restrictive policy ${gateError}; it denies every row until it can be created`);\n for (const name of table.orphans) {\n await run(dropPolicySql(plan, name));\n result.orphansDropped++;\n }\n recordRulesDropped(result, table);\n log?.(`${plan.qualified}: RLS enabled, ${created} policy(ies) applied` +\n (table.orphans.length > 0 ? `, ${table.orphans.length} orphan(s) dropped` : \"\"));\n } catch (err) {\n result.failures.push({\n table: plan.qualified,\n error: describeDriverError(err)\n });\n return;\n }\n\n // Only once every policy is in. A stamp that cannot be written costs the\n // next boot a re-apply of this table — what every boot did before stamps —\n // so it is reported, not failed.\n const stamp = policyStampSql(plan);\n if (!stamp) return;\n try {\n await run(stamp);\n } catch (err) {\n log?.(`${plan.qualified}: policies applied, but not stamped (${describeDriverError(err)}); ` +\n \"the next boot applies them again\");\n }\n}\n\n/**\n * A table whose lock was held for every attempt. Its transaction rolled back\n * each time, so it is exactly as it was before this boot.\n *\n * With RLS on, that is a safe state to leave it in — reported, not failed. With\n * RLS off it is an open table over the schema-wide grant, so it is closed the\n * way any table RLS cannot be enabled on is: the catalogue is asked once more,\n * and only a table that really is RLS-off has the user role's grant withdrawn.\n */\nasync function giveUp(\n client: Queryable,\n table: TableWork,\n lastError: string,\n lock: ResolvedBootLockOptions,\n result: PolicyEnsureResult\n): Promise<void> {\n const { plan } = table;\n const error =\n `another session held the table's lock for every attempt (lock_timeout ${lock.lockTimeoutMs} ms` +\n `${lastError ? `: ${lastError.split(\"\\n\")[0]}` : \"\"}) — a long transaction, a report or a dump`;\n if (table.rlsOn || await rlsIsOn(client, plan)) {\n result.tablesSecured++;\n result.deferred.push({ table: plan.qualified, error, rulesChanged: table.rulesChanged });\n return;\n }\n const closed = await withdrawGrant(client, plan, error);\n if (!closed.locked) {\n result.unsecured.push({ table: plan.qualified, error: closed.error, grantWithdrawn: closed.grantWithdrawn });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsJA,IAAM,kBAAkB,cAA+B,qBAAqB,KAAK,SAAS;;;;;;;;;;;;;AAc1F,IAAM,qBAAqB,cAA0C;CACjE,MAAM,QAAQ,iCAAiC,KAAK,SAAS;CAC7D,OAAO,QAAQ,qBAAqB,MAAM,EAAE,IAAI,KAAA;AACpD;;AAGA,IAAM,sBAAsB,SAA4C;CACpE,MAAM,2BAAW,IAAI,IAAY;CACjC,KAAK,MAAM,aAAa,KAAK,kBAAkB;EAC3C,MAAM,OAAO,kBAAkB,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ChC,MAAM,GAAG,KAAK,UAAU,iBAAiB,QAAQ,yBAC5C,MAAM,QAAQ,SAAS,IAAI,KAAK,MAAM,QAAQ,OAAO,sBAAsB,GAAG;CACvF,SAAS,KAAK;EACV,OAAO,SAAS,KAAK;GACjB,OAAO,KAAK;GACZ,OAAO,oBAAoB,GAAG;EAClC,CAAC;EACD;CACJ;CAKA,MAAM,QAAQ,eAAe,IAAI;CACjC,IAAI,CAAC,OAAO;CACZ,IAAI;EACA,MAAM,IAAI,KAAK;CACnB,SAAS,KAAK;EACV,MAAM,GAAG,KAAK,UAAU,uCAAuC,oBAAoB,GAAG,EAAE,oCAClD;CAC1C;AACJ;;;;;;;;;;AAWA,eAAe,OACX,QACA,OACA,WACA,MACA,QACa;CACb,MAAM,EAAE,SAAS;CACjB,MAAM,QACF,yEAAyE,KAAK,cAAc,KACzF,YAAY,KAAK,UAAU,MAAM,IAAI,CAAC,CAAC,OAAO,GAAG;CACxD,IAAI,MAAM,SAAS,MAAM,QAAQ,QAAQ,IAAI,GAAG;EAC5C,OAAO;EACP,OAAO,SAAS,KAAK;GAAE,OAAO,KAAK;GAAW;GAAO,cAAc,MAAM;EAAa,CAAC;EACvF;CACJ;CACA,MAAM,SAAS,MAAM,cAAc,QAAQ,MAAM,KAAK;CACtD,IAAI,CAAC,OAAO,QACR,OAAO,UAAU,KAAK;EAAE,OAAO,KAAK;EAAW,OAAO,OAAO;EAAO,gBAAgB,OAAO;CAAe,CAAC;AAEnH"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"generate-postgres-ddl-logic-G9PvjHrr.js","names":[],"sources":["../src/schema/generate-postgres-ddl-logic.ts"],"sourcesContent":["/**\n * The SQL half of `rebase db generate`, as a plan and a renderer.\n *\n * There is no interpretation left in this file. `schema/plan/plan-schema.ts`\n * reads the collections into a {@link SchemaPlan} and `schema/plan/render-ddl.ts`\n * writes the files; what remains here is the public entry points those two are\n * reached through, plus the smaller plans (`planRelationalColumns`,\n * `planJunctionTables`, `planCollectionPolicies`) that other modules ask for as\n * slices of the same plan.\n *\n * It used to hold `getSqlColumnType` and a `CREATE TABLE` walk with its own\n * reading of relations, junctions, enums and search — one of three such\n * readings. See `schema/plan/types.ts` for what that cost.\n */\nimport { CollectionConfig, SecurityRule, isPostgresCollectionConfig } from \"@rebasepro/types\";\nimport { getTableName } from \"@rebasepro/common\";\nimport { planSchema, compileSecurityRule, quoteSqlLiteral, defaultBelongsToOnDelete } from \"./plan/plan-schema\";\nimport {\n renderDenyingPolicyStatements,\n renderPgType,\n renderPoliciesDdl,\n renderPolicyStatements,\n renderPostgresDdl,\n renderSearchDdl,\n renderTriggersDdl,\n renderViewsDdl,\n renderVectorDdl,\n searchExcludePatternsOf,\n triggerExcludePatternsOf,\n vectorExcludePatternsOf,\n type DdlRenderOptions\n} from \"./plan/render-ddl\";\nimport type { ForeignKeyPlan, SchemaPlan } from \"./plan/types\";\nimport type { GeneratedColumnDependency } from \"./generated-column-conflicts\";\n\nexport { quoteSqlLiteral, defaultBelongsToOnDelete };\nexport type { ForeignKeyPlan };\n\ntype ResolveCollection = (slug: string) => CollectionConfig | undefined;\n\n/**\n * The individual SQL statements a single security rule compiles to: a\n * `DROP POLICY IF EXISTS` / `CREATE POLICY` pair per operation, each a complete\n * statement (terminated by `;`, no trailing newline).\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 generatePolicyStatements = (\n collection: CollectionConfig,\n rule: SecurityRule,\n resolveCollection: ResolveCollection\n): string[] => {\n const table = {\n schema: isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\",\n table: getTableName(collection)\n };\n return compileSecurityRule(collection, rule, resolveCollection, false)\n .flatMap(policy => renderPolicyStatements(table, policy));\n};\n\n/**\n * `.rebase/sql/schema.sql` — the desired state Atlas diffs the database against.\n *\n * Synchronous. It was `async` with nothing to await, which made every caller\n * (the writer script, the doctor, the live editor, two gates) carry a promise\n * for no reason and made the one place that forgot to await it silently compare\n * `[object Promise]`.\n */\nexport const generatePostgresDdl = (\n allCollections: CollectionConfig[],\n options: DdlRenderOptions = {}\n): string => renderPostgresDdl(planSchema(allCollections), options);\n\n/** `.rebase/sql/policies.sql` — the RLS policies. Atlas has no model for a policy. */\nexport const generatePostgresPoliciesDdl = (allCollections: CollectionConfig[]): string =>\n renderPoliciesDdl(planSchema(allCollections));\n\n/**\n * `.rebase/sql/search.sql` — everything a `search` block needs, as a file Rebase\n * applies itself.\n *\n * Search is one of the parts of the schema Atlas does not own, for two\n * independent reasons and either alone would be enough:\n *\n * 1. Its free tier refuses to *parse* a desired-state file that so much as\n * contains a function — \"functions and procedures are available to\n * logged-in users only\". A generated `tsvector` column cannot avoid one:\n * `unaccent` is STABLE and jsonb flattening needs a set-returning function,\n * so both have to be wrapped in an IMMUTABLE helper to be legal in a\n * generated column at all.\n * 2. Even with the file accepted, Atlas *wipes* the dev database it diffs\n * against, so a helper seeded there beforehand is gone by the time the plan\n * is analysed. There is no hook to reinstate it.\n *\n * Empty when nothing opted in — the caller writes no file then.\n */\nexport const generatePostgresSearchDdl = (allCollections: CollectionConfig[]): string =>\n renderSearchDdl(planSchema(allCollections));\n\n/**\n * Glob patterns telling Atlas to leave the search column and its index alone.\n *\n * Without these, a desired state that omits search reads to Atlas as an\n * instruction to drop the column — taking the index and the whole search\n * feature with it on the next push.\n */\nexport const searchExcludePatterns = (allCollections: CollectionConfig[]): string[] =>\n searchExcludePatternsOf(planSchema(allCollections));\n\n/**\n * `.rebase/sql/vector.sql` — the `vector` columns, their ANN indexes and, when a\n * database declared it, the extension.\n *\n * Vector is out of Atlas's hands for a narrower reason than search: not that\n * Atlas refuses to parse the file, but that it cannot *execute* it. To compute\n * a desired state Atlas materialises `schema.sql` in a dev database, that\n * database is created empty, and Atlas empties it again at the start of every\n * run — so `VECTOR(384)` resolves against a database that structurally cannot\n * have pgvector, and every push dies with `type \"vector\" does not exist`.\n */\nexport const generatePostgresVectorDdl = (\n allCollections: CollectionConfig[],\n options: { extensions?: readonly string[] } = {}\n): string => renderVectorDdl(planSchema(allCollections, { databaseExtensions: options.extensions }));\n\n/** @see searchExcludePatterns */\nexport const vectorExcludePatterns = (allCollections: CollectionConfig[]): string[] =>\n vectorExcludePatternsOf(planSchema(allCollections));\n\n/**\n * `.rebase/sql/triggers.sql` — the `BEFORE UPDATE` triggers behind\n * `autoValue: \"on_update\"`, and the one function they share.\n *\n * A trigger is a function plus a binding, so it is carved out of Atlas's view\n * for the first of the two reasons search is. Empty when no property declares\n * `on_update` — the caller writes no file then, and removes a stale one.\n */\nexport const generatePostgresTriggersDdl = (allCollections: CollectionConfig[]): string =>\n renderTriggersDdl(planSchema(allCollections));\n\n/**\n * `.rebase/sql/views.sql` — the views of the collections that declare `view`,\n * which Atlas's free tier does not manage. Empty when none does — the caller\n * writes no file then, and removes a stale one.\n */\nexport const generatePostgresViewsDdl = (allCollections: CollectionConfig[]): string =>\n renderViewsDdl(planSchema(allCollections));\n\n/** @see searchExcludePatterns */\nexport const triggerExcludePatterns = (allCollections: CollectionConfig[]): string[] =>\n triggerExcludePatternsOf(planSchema(allCollections));\n\n// ── Slices of the plan other modules ask for ─────────────────────────────────\n\n/** A column a `relation` or `reference` property owns on its own table. */\nexport interface RelationalColumnPlan {\n schema: string;\n /** Bare table name, no schema prefix. */\n table: string;\n column: string;\n /** Postgres type, exactly as the DDL renderer declares it. */\n type: string;\n /** `validation.required` on the property that owns the link. */\n required: boolean;\n /**\n * True when a declared property emits this column and the relation\n * contributes only the constraint — `postId` with `columnName: \"post_id\"`\n * beside a `belongsTo` on `post_id`.\n */\n columnOwnedByProperty?: boolean;\n /** Absent when the target collection is not part of this bundle. */\n foreignKey?: ForeignKeyPlan;\n /**\n * What this column would have been called before `generateForeignKeyName`\n * learned to singularize. Carried so the boot-time ensure can notice a\n * database provisioned under the old rule; never used to name anything.\n */\n legacyColumn?: string;\n}\n\n/** The table behind a many-to-many `through` relation. */\nexport interface JunctionTablePlan {\n schema: string;\n /** Bare table name, no schema prefix. */\n table: string;\n columns: { name: string; type: string; legacyName?: string }[];\n /** Both endpoint columns plus the composite primary key. */\n createTable: string;\n foreignKeys: ForeignKeyPlan[];\n}\n\nconst planOf = (collections: CollectionConfig[]): SchemaPlan => planSchema(collections);\n\n/**\n * The FK columns the declared collections own — one entry per `relation`\n * (`belongsTo` side) or `reference` property.\n *\n * A view over the schema plan. It was a second walk of the collections beside\n * the `CREATE TABLE` one, which is how boot-ensure came to add every relation\n * column bare while `db push` made the same column `NOT NULL`.\n */\nexport const planRelationalColumns = (allCollections: CollectionConfig[]): RelationalColumnPlan[] => {\n const plan = planOf(allCollections);\n const out: RelationalColumnPlan[] = [];\n for (const table of plan.tables) {\n if (table.kind !== \"collection\") continue;\n for (const column of table.columns) {\n if (column.source.kind !== \"relation\" && column.source.kind !== \"reference\") continue;\n out.push({\n schema: table.schema,\n table: table.table,\n column: column.column,\n type: renderPgType(column.type),\n required: !column.nullable,\n columnOwnedByProperty: column.columnOwnedByProperty,\n legacyColumn: column.legacyColumn,\n foreignKey: column.foreignKey\n });\n }\n }\n return out;\n};\n\n/**\n * The junction tables a bundle's many-to-many relations imply.\n *\n * Derived from the same plan the derived RLS comes from, so a table created\n * here always has policies planned for it — a junction with row-level security\n * left off is readable and writable by every signed-in user.\n */\nexport const planJunctionTables = (allCollections: CollectionConfig[]): JunctionTablePlan[] =>\n planOf(allCollections).tables\n .filter(table => table.kind === \"junction\")\n .map(table => ({\n schema: table.schema,\n table: table.table,\n columns: table.columns.map(c => ({\n name: c.column,\n type: renderPgType(c.type),\n legacyName: c.legacyColumn\n })),\n createTable:\n `CREATE TABLE IF NOT EXISTS \"${table.schema}\".\"${table.table}\" (` +\n table.columns.map(c => `\"${c.column}\" ${renderPgType(c.type)} NOT NULL`).join(\", \") +\n `, PRIMARY KEY (${table.primaryKey.map(c => `\"${c}\"`).join(\", \")}));`,\n foreignKeys: table.columns.map(c => c.foreignKey).filter((fk): fk is ForeignKeyPlan => fk !== undefined)\n }));\n\nexport interface CollectionPolicyPlan {\n /** The table's schema (e.g. `public`, `rebase`). */\n schema: string;\n /** The bare table name, no schema prefix. */\n table: string;\n /** `schema.table` — matches the keys `readExistingSchema` returns. */\n qualified: string;\n /** `ALTER TABLE … ENABLE ROW LEVEL SECURITY;` — locked by default. */\n enableRls: string;\n /** `DROP POLICY IF EXISTS` / `CREATE POLICY` statements, in order. */\n policyStatements: string[];\n /**\n * The same statements, grouped by policy, with each restrictive policy's\n * denying stand-in. What the boot applier's one-statement-at-a-time\n * fallback walks: it creates the restrictive gates before any grant, and\n * puts the stand-in where a gate could not be created.\n */\n policies: PolicyApplyPlan[];\n}\n\n/** One policy of a {@link CollectionPolicyPlan}, as the statements that make it. */\nexport interface PolicyApplyPlan {\n name: string;\n /** Written `TO rebase_admin` by the compiler's choice (`rls.adminPolicies`). */\n adminTarget: boolean;\n restrictive: boolean;\n /** Its `DROP POLICY IF EXISTS` / `CREATE POLICY` statements — a slice of `policyStatements`. */\n statements: string[];\n /** For a restrictive policy, the statements that make it deny every row instead. */\n denying?: string[];\n}\n\n/**\n * The per-table RLS plan for the declared collections and their junctions, as\n * executable statements — what the managed runtime applies at boot so a freshly\n * provisioned tenant database serves data instead of 401ing every read.\n *\n * The same policies `policies.sql` carries, from the same plan, so boot and\n * `db push` produce identical RLS from identical collections.\n */\nexport const planCollectionPolicies = (\n allCollections: CollectionConfig[],\n options: { adminRoleAvailable?: boolean } = {}\n): CollectionPolicyPlan[] => {\n const plan = planOf(allCollections);\n // Collections first, then the junctions no collection declares.\n const ordered = [\n ...plan.tables.filter(t => t.kind === \"collection\"),\n ...plan.tables.filter(t => t.kind === \"junction\")\n ];\n return ordered.map(table => {\n const policies: PolicyApplyPlan[] = table.policies.map(planned => {\n // Where `rebase_admin` cannot exist, a policy the compiler put there\n // is written as it was before it did: `TO public`.\n const policy = options.adminRoleAvailable === false && planned.adminTarget\n ? { ...planned, roles: [\"public\"] }\n : planned;\n const restrictive = policy.mode === \"restrictive\";\n return {\n name: policy.name,\n adminTarget: policy.adminTarget === true && policy.roles[0] !== \"public\",\n restrictive,\n statements: renderPolicyStatements(table, policy),\n ...(restrictive ? { denying: renderDenyingPolicyStatements(table, policy) } : {})\n };\n });\n return {\n schema: table.schema,\n table: table.table,\n qualified: table.qualified,\n enableRls: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ENABLE ROW LEVEL SECURITY;`,\n policyStatements: policies.flatMap(policy => policy.statements),\n policies\n };\n });\n};\n\n/**\n * The `generated column → column it reads` edges a project's `search` blocks\n * imply, derived from the collections alone.\n *\n * The same edges `queryGeneratedColumnDependencies` reads out of `pg_depend`,\n * but available where no database is: `rebase db generate` writes a migration\n * that will run somewhere else, later, against a database it cannot inspect.\n * A spec's `fields[].column` is the physical column each search field starts\n * at, which is exactly what the generated expression depends on.\n */\nexport const searchColumnDependencies = (\n allCollections: CollectionConfig[]\n): GeneratedColumnDependency[] => {\n const dependencies: GeneratedColumnDependency[] = [];\n for (const table of planOf(allCollections).tables) {\n const spec = table.search;\n if (!spec) continue;\n const generated = [spec.column, ...(spec.fuzzy ? [spec.fuzzy.column] : [])];\n const sources = new Set(spec.fields.map(field => field.column));\n for (const column of generated) {\n for (const dependsOn of sources) {\n dependencies.push({ schema: table.schema, table: table.table, column, dependsOn });\n }\n }\n }\n return dependencies;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,uBACT,gBACA,UAA4B,CAAC,MACpB,kBAAkB,WAAW,cAAc,GAAG,OAAO;;AAGlE,IAAa,+BAA+B,mBACxC,kBAAkB,WAAW,cAAc,CAAC;;;;;;;;;;;;;;;;;;;;AAqBhD,IAAa,6BAA6B,mBACtC,gBAAgB,WAAW,cAAc,CAAC;;;;;;;;AAS9C,IAAa,yBAAyB,mBAClC,wBAAwB,WAAW,cAAc,CAAC;;;;;;;;;;;;AAatD,IAAa,6BACT,gBACA,UAA8C,CAAC,MACtC,gB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S,KAAI,YAAW;GAG9D,MAAM,SAAS,QAAQ,uBAAuB,SAAS,QAAQ,cACzD;IAAE,GAAG;IAAS,OAAO,CAAC,QAAQ;GAAE,IAChC;GACN,MAAM,cAAc,OAAO,SAAS;GACpC,OAAO;IACH,MAAM,OAAO;IACb,aAAa,OAAO,gBAAgB,QAAQ,OAAO,MAAM,OAAO;IAChE;IACA,YAAY,uBAAuB,OAAO,MAAM;IAChD,GAAI,cAAc,EAAE,SAAS,8BAA8B,OAAO,MAAM,EAAE,IAAI,CAAC;GACnF;EACJ,CAAC;EACD,OAAO;GACH,QAAQ,MAAM;GACd,OAAO,MAAM;GACb,WAAW,MAAM;GACjB,WAAW,gBAAgB,MAAM,OAAO,KAAK,MAAM,MAAM;GACzD,kBAAkB,SAAS,SAAQ,WAAU,OAAO,UAAU;GAC9D;EACJ;CACJ,CAAC;AACL;;;;;;;;;;;AAYA,IAAa,4BACT,mBAC8B;CAC9B,MAAM,eAA4C,CAAC;CACnD,KAAK,MAAM,SAAS,OAAO,cAAc,CAAC,CAAC,QAAQ;EAC/C,MAAM,OAAO,MAAM;EACnB,IAAI,CAAC,MAAM;EACX,MAAM,YAAY,CAAC,KAAK,QAAQ,GAAI,KAAK,QAAQ,CAAC,KAAK,MAAM,MAAM,IAAI,CAAC,CAAE;EAC1E,MAAM,UAAU,IAAI,IAAI,KAAK,OAAO,KAAI,UAAS,MAAM,MAAM,CAAC;EAC9D,KAAK,MAAM,UAAU,WACjB,KAAK,MAAM,aAAa,SACpB,aAAa,KAAK;GAAE,QAAQ,MAAM;GAAQ,OAAO,MAAM;GAAO;GAAQ;EAAU,CAAC;CAG7F;CACA,OAAO;AACX"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"plan-schema-CMhNYEYF.js","names":[],"sources":["../src/schema/relation-names.ts","../src/schema/plan/tenant-keep-trigger.ts","../src/schema/plan/updated-at-trigger.ts","../src/schema/plan/plan-schema.ts"],"sourcesContent":["import { CollectionConfig, ResolvedRelation } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, getTableName } from \"@rebasepro/common\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\n/**\n * The `relationName` both sides of a link must agree on.\n *\n * Drizzle pairs an owning `one()` with its inverse `many()` by this string and\n * by nothing else, and the two sides are computed by different callers holding\n * different collections — so the rule has to be derivable from either end. It\n * is: name the link after the table that carries the foreign key and the field\n * key that column is served under.\n *\n * owning (belongsTo) → `{thisTable}_{fieldKey(localKey)}`\n * inverse (hasMany/hasOne) → `{targetTable}_{fieldKey(foreignKeyOnTarget)}`\n *\n * Both spellings of `jobs.company` produce `jobs_companyId`. A many-to-many is\n * named through its junction wiring and a `via` chain is not a Drizzle relation\n * at all, so both keep the local name.\n *\n * The field key rather than the column: the Drizzle object is keyed by the wire\n * name (`fieldKeyForColumn` is the one definition of it), and a name built from\n * the column would differ between a collection that declares `columnName` and\n * one that does not, for the same link.\n *\n * **This is the one definition.** `generate-drizzle-schema-logic.ts` holds a\n * private copy (`computeSharedRelationName`) that this was lifted from verbatim;\n * the generator should import this instead, so the file it writes and the\n * relations the runtime builds from the live catalogue cannot drift apart.\n */\nexport function sharedRelationName(\n relation: ResolvedRelation,\n sourceCollection: CollectionConfig\n): string {\n const fallback = (): string => {\n if (relation.relationName) return relation.relationName;\n try {\n return toSnakeCase(relation.target().slug);\n } catch {\n return relation.relationName;\n }\n };\n\n if (relation.kind === \"belongsTo\") {\n return `${getTableName(sourceCollection)}_${fieldKeyForColumn(sourceCollection, relation.localKey)}`;\n }\n\n if (relation.kind === \"hasMany\" || relation.kind === \"hasOne\") {\n try {\n const target = relation.target();\n return `${getTableName(target)}_${fieldKeyForColumn(target, relation.foreignKeyOnTarget)}`;\n } catch {\n return fallback();\n }\n }\n\n return fallback();\n}\n","/**\n * `tenant`'s immutability, as a database trigger.\n *\n * The driver refuses an update that moves a row to another tenant\n * (`TENANT_IMMUTABLE`, see `resolveTenantWrite` in `@rebasepro/common`), and\n * the restrictive tenant policy cannot: a policy sees the new row or the old\n * one, never both, so a caller who belongs to two tenants passes it while\n * moving a row from one to the other. Every writer that is not the driver —\n * SQL run as the caller (`DataDriver.sql`) above all — met only the policy.\n *\n * So a `BEFORE UPDATE` trigger compares the two. It applies to whoever the\n * table's policies bind (`row_security_active`), which is every request role\n * whatever `rls.requestRole` names it: the owner connection (migrations, the\n * auth flows, a person in `psql`) keeps moving rows when it means to, as it\n * always could, and so does a caller holding one of the collection's\n * `bypassRoles` — the same exemption the driver makes.\n *\n * One function for every table, the column and the bypass roles arriving as\n * trigger arguments, like `set_updated_at`. The arguments are compared with\n * the catalogue's on boot (see `diffPlanAgainstCatalogue`), so a changed\n * `bypassRoles` re-creates the binding rather than leaving the old list in\n * force.\n */\nimport { REBASE_SCHEMA } from \"@rebasepro/types\";\nimport type { TriggerPlan } from \"./types\";\n\n/** The one trigger function, qualified. A frozen derived name. */\nexport const KEEP_TENANT_FN = `${REBASE_SCHEMA}.keep_tenant`;\n\n/** The trigger's name on `table`. A frozen derived name. */\nexport const keepTenantTriggerName = (table: string): string => `${table}_keep_tenant`;\n\nexport const keepTenantFunction = (): string =>\n `CREATE OR REPLACE FUNCTION ${KEEP_TENANT_FN}() RETURNS trigger\\n` +\n \"LANGUAGE plpgsql AS $$\\n\" +\n \"BEGIN\\n\" +\n // Nested rather than one AND, which Postgres may evaluate in any order;\n // and the roles read from the setting itself, as `rebase.roles()` does,\n // so the owner's updates never depend on that function existing yet.\n \" IF row_security_active(TG_RELID) THEN\\n\" +\n \" IF to_jsonb(OLD) -> TG_ARGV[0] IS DISTINCT FROM to_jsonb(NEW) -> TG_ARGV[0] THEN\\n\" +\n \" IF NOT (string_to_array(COALESCE(current_setting('app.user_roles', true), ''), ',') && TG_ARGV[1:TG_NARGS - 1]) THEN\\n\" +\n \" RAISE EXCEPTION 'TENANT_IMMUTABLE: an update cannot move a row of \\\"%\\\" to another tenant (column \\\"%\\\")', TG_TABLE_NAME, TG_ARGV[0]\\n\" +\n \" USING ERRCODE = '42501',\\n\" +\n \" HINT = 'Move it as a role listed in the collection''s tenant.bypassRoles.';\\n\" +\n \" END IF;\\n\" +\n \" END IF;\\n\" +\n \" END IF;\\n\" +\n \" RETURN NEW;\\n\" +\n \"END;\\n\" +\n \"$$;\";\n\n/** The arguments the binding passes: the column, then each bypass role. */\nexport const keepTenantArguments = (plan: TriggerPlan): string[] => [plan.column, ...(plan.bypassRoles ?? [])];\n\nconst literal = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\n\nexport const createKeepTenantStatement = (plan: TriggerPlan): string =>\n `CREATE TRIGGER \"${plan.name}\" BEFORE UPDATE ON \"${plan.schema}\".\"${plan.table}\" ` +\n `FOR EACH ROW EXECUTE FUNCTION ${KEEP_TENANT_FN}(${keepTenantArguments(plan).map(literal).join(\", \")});`;\n","/**\n * `autoValue: \"on_update\"`, as a database trigger.\n *\n * ## Why a trigger and not only the driver\n *\n * The driver stamps `updated_at` on every write it makes, and it has to keep\n * doing so: a `beforeSave` hook reads the row it is about to persist, and a\n * value that only appears once Postgres has written it is a value the hook\n * cannot see.\n *\n * But the driver is not the only writer. A seed script, a migration backfill, a\n * `psql` session, an admin fixing one row by hand — every one of those leaves\n * `updated_at` at whatever it was, and the column then says the row has not\n * changed since a date that is simply wrong. Anything reading it to decide what\n * to re-index, re-sync or re-send skips the row. The declaration says \"this\n * column tracks the last write\"; only the database can make that true.\n *\n * So both: the app stamps so hooks see the value, and a `BEFORE UPDATE` trigger\n * stamps so every other writer does too. They agree because they both mean\n * \"now\" — the trigger's `now()` is the transaction's start time, which is the\n * same instant the driver's own timestamp is written under.\n *\n * ## Why it is carved out of Atlas\n *\n * Atlas's free tier refuses to *parse* a desired-state file containing a\n * function (\"functions and procedures are available to logged-in users only\"),\n * and a trigger is a function plus a binding. This is the same arrangement the\n * search helpers already have: excluded from Atlas's view by pattern, written\n * to a file Rebase applies itself, applied at boot by the schema ensure, and\n * appended to migrations by the CLI so a replay is complete.\n *\n * ## Why one function for every column\n *\n * The column name arrives as a trigger argument (`TG_ARGV[0]`), so a project\n * with forty `updated_at` columns installs one function and forty bindings\n * rather than forty near-identical functions. `jsonb_populate_record(NEW, …)`\n * is the documented way to set a field of a row whose type is not known until\n * run time; it takes `NEW` as the row template, so the value is cast back to\n * whatever the column actually is — a `timestamptz`, or a `date` if that is\n * what the property declared.\n */\nimport { REBASE_SCHEMA } from \"@rebasepro/types\";\nimport type { TriggerPlan } from \"./types\";\nimport { createKeepTenantStatement } from \"./tenant-keep-trigger\";\n\n/** The one trigger function, qualified. A frozen derived name. */\nexport const SET_UPDATED_AT_FN = `${REBASE_SCHEMA}.set_updated_at`;\n\n/**\n * `CREATE OR REPLACE FUNCTION`, so replaying it against a database that already\n * has it is a no-op — this is emitted into a file that runs on every push and\n * is appended to migrations that run against databases at any stage of life.\n */\nexport const setUpdatedAtFunction = (): string =>\n `CREATE OR REPLACE FUNCTION ${SET_UPDATED_AT_FN}() RETURNS trigger\\n` +\n \"LANGUAGE plpgsql AS $$\\n\" +\n \"BEGIN\\n\" +\n \" NEW := jsonb_populate_record(NEW, jsonb_build_object(TG_ARGV[0], now()));\\n\" +\n \" RETURN NEW;\\n\" +\n \"END;\\n\" +\n \"$$;\";\n\n/**\n * `DROP TRIGGER IF EXISTS` before the `CREATE`.\n *\n * `CREATE OR REPLACE TRIGGER` exists only on Postgres 14+, and this runs\n * against whatever a self-hosted project points at. Two statements rather than\n * one is also what the boot-time applier needs: it issues DDL one statement at\n * a time over the extended query protocol, which forbids multiple commands in\n * one execute.\n */\nexport const dropTriggerStatement = (plan: TriggerPlan): string =>\n `DROP TRIGGER IF EXISTS \"${plan.name}\" ON \"${plan.schema}\".\"${plan.table}\";`;\n\nexport const createTriggerStatement = (plan: TriggerPlan): string =>\n `CREATE TRIGGER \"${plan.name}\" BEFORE UPDATE ON \"${plan.schema}\".\"${plan.table}\" ` +\n `FOR EACH ROW EXECUTE FUNCTION ${SET_UPDATED_AT_FN}('${plan.column.replace(/'/g, \"''\")}');`;\n\n/** Both statements, in the order they must run — for either kind of trigger. */\nexport const triggerStatements = (plan: TriggerPlan): string[] =>\n [dropTriggerStatement(plan), plan.kind === \"keep-tenant\" ? createKeepTenantStatement(plan) : createTriggerStatement(plan)];\n","/**\n * The only place a `Property` is read for schema purposes.\n *\n * Everything that used to `switch (prop.type)` — the Drizzle generator, the DDL\n * generator, the boot-time ensure — now renders the {@link SchemaPlan} this\n * produces. See `./types.ts` for why.\n *\n * Pure and synchronous. It reads collections and nothing else: no database, no\n * filesystem, no process-wide registry. The one fact about the world it needs\n * (which extensions a project's databases gave Rebase leave to install) is\n * passed in, because a plan that depended on whatever module happened to be\n * imported would not be comparable with itself.\n *\n * It **throws** rather than guessing. A configuration no renderer can honour —\n * an empty enum, `isId: \"cuid\"`, a foreign key into a composite key, an unknown\n * `columnType`, a relation to a collection that is not in the bundle, a\n * `search` block on a collection Postgres does not store — used to fail\n * differently in each of the three emitters, or not at all, and the failure\n * landed at `CREATE TABLE` time on a managed tenant with nobody in the loop.\n * Here it lands once, with the collection and the property named.\n */\nimport {\n isPostgresCollectionConfig,\n isManyToMany,\n REBASE_SCHEMA,\n type ArrayProperty,\n type CollectionConfig,\n type DateProperty,\n type MapProperty,\n type NumberProperty,\n type Properties,\n type Property,\n type ReferenceProperty,\n type RelationProperty,\n type ResolvedForeignKeyOnTarget,\n type ResolvedRelation,\n type SecurityRule,\n type StringProperty,\n type VectorProperty,\n hasForeignKeyOnTarget\n} from \"@rebasepro/types\";\nimport {\n fieldKeyForColumn,\n findRelation,\n getEffectiveSecurityRules,\n getEnumVarName,\n getInjectedSecurityRules,\n getTenantConfig,\n tenantBypassRoles,\n TENANT_INDEX_REASON,\n getJunctionCollectionConfig,\n getJunctionSecurityRules,\n getTableName,\n type JunctionSpec,\n getTableVarName,\n compileRulePolicies,\n relationalCollections,\n resolveCollectionRelations,\n resolveJunctionSpecs,\n assertBeforeQueryIsPostgresOnly,\n resolveStringColumnLength\n} from \"@rebasepro/common\";\nimport {\n generateForeignKeyName,\n getPolicySupersededNames,\n legacyForeignKeyName,\n toPostgresIdentifier,\n toSnakeCase\n} from \"@rebasepro/utils\";\nimport {\n declaresEnumType,\n enumLabelsOf,\n getPrimaryKeyColumn,\n getPrimaryKeyName,\n getPrimaryKeyProp,\n idColumnDefault,\n isIdProperty,\n primaryKeyPropertyNames,\n resolveColumnName,\n sqlExpressionText\n} from \"../column-plan-helpers\";\nimport {\n AUTH_USERS_COLUMNS,\n authUsersColumnDefinition,\n authUsersColumnSql,\n isAuthCollection\n} from \"../auth-users-columns\";\nimport {\n assertSearchIsPostgresOnly,\n buildSearchColumnSpec,\n searchColumnTypeSql,\n searchExtensionStatements,\n searchHelperFunctions\n} from \"../search-column\";\nimport {\n buildVectorColumnSpecs,\n buildVectorIndexPlan,\n vectorExtensionDeclared,\n vectorExtensionStatement\n} from \"../vector-index\";\nimport {\n buildCollectionIndexSpecs,\n collectionIndexStatement,\n deriveIndexName,\n foreignKeyIndexSpec,\n leadsWithColumn,\n type CollectionIndexSpec\n} from \"../collection-index\";\nimport { createHash } from \"node:crypto\";\nimport { sharedRelationName } from \"../relation-names\";\nimport { SET_UPDATED_AT_FN, setUpdatedAtFunction } from \"./updated-at-trigger\";\nimport { keepTenantFunction, keepTenantTriggerName } from \"./tenant-keep-trigger\";\nimport { DEFAULT_VIEW_ROLES, viewRowsName } from \"./view-names\";\nimport type {\n ColumnDefault,\n ColumnPlan,\n EnumPlan,\n ForeignKeyPlan,\n PgType,\n PlanOptions,\n PolicyPlan,\n RelationPlan,\n SchemaPlan,\n TablePlan,\n TriggerPlan,\n ViewPlan\n} from \"./types\";\n\ntype ResolveCollection = (slug: string) => CollectionConfig | undefined;\n\n/**\n * Single-quote escaping for a SQL string literal (PostgreSQL doubles the\n * quote). Enum labels and `defaultValue`s come straight from user-authored\n * collection config, so a value like `it's` closes the literal early and the\n * whole generated file stops parsing at that statement.\n */\nexport const quoteSqlLiteral = (value: string): string => `'${value.replace(/'/g, \"''\")}'`;\n\nconst schemaOf = (collection: CollectionConfig): string =>\n isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n\nconst bareTableName = (name: string): string => (name.includes(\".\") ? name.split(\".\").pop()! : name);\n\nconst describe = (collection: CollectionConfig): string =>\n collection.slug ?? collection.name ?? \"(unnamed)\";\n\n/** A link, as a refusal names it: `relation \"posts.author\"`. */\nconst linkLabel = (kind: string, collection: CollectionConfig, key: string): string =>\n `${kind} \"${describe(collection)}.${key}\"`;\n\n/**\n * The `ON DELETE` a foreign key gets when the author did not say.\n *\n * One rule for every property that emits one — `belongsTo` relations and\n * `reference` properties alike. `reference` kept its own `CASCADE` default for\n * a release after this rule was written, which is exactly the split this\n * function exists to prevent: two spellings of the same link, two\n * data-retention behaviours, and only one of them documented.\n *\n * An optional link is `SET NULL`: the column can hold NULL, so dropping the\n * parent leaves the child row with an empty pointer, which is what \"optional\"\n * already means.\n *\n * A required link is **`RESTRICT`**, not `CASCADE`. `NOT NULL` says the child\n * cannot exist without a parent; it does not say deleting the parent should\n * take the child with it. That second claim is a data-retention decision, and\n * defaulting to it meant `onDelete` — a field nobody has to write — silently\n * turned every `DELETE FROM authors` into a cascade through posts, comments and\n * anything else that hung off them.\n */\nexport const defaultBelongsToOnDelete = (required: boolean | undefined): \"RESTRICT\" | \"SET NULL\" =>\n required ? \"RESTRICT\" : \"SET NULL\";\n\nconst foreignKeyPlan = (\n args: Omit<ForeignKeyPlan, \"constraintName\" | \"sql\">\n): ForeignKeyPlan => {\n const constraintName = toPostgresIdentifier(`${args.table}_${args.column}_fkey`);\n const onUpdate = args.onUpdate ? ` ON UPDATE ${args.onUpdate.toUpperCase()}` : \"\";\n return {\n ...args,\n constraintName,\n sql:\n `ALTER TABLE \"${args.schema}\".\"${args.table}\" ADD CONSTRAINT \"${constraintName}\" ` +\n `FOREIGN KEY (\"${args.column}\") REFERENCES \"${args.targetSchema}\".\"${args.targetTable}\" ` +\n `(\"${args.targetColumn}\") ON DELETE ${args.onDelete.toUpperCase()}${onUpdate}`\n };\n};\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\n/**\n * The type a column pointing at this collection's primary key must have — a\n * junction endpoint, a `belongsTo` foreign key, a `reference`.\n *\n * The key's own column type, from the same functions that typed the key: a\n * foreign key only holds between compatible types, so any second reading of\n * the key is a constraint waiting to fail. This used to look at the id\n * strategy alone, so `id: { isId: true, columnType: \"uuid\" }` was referenced by\n * TEXT columns (42804 — the constraint was never created) and a `bigint` key by\n * INTEGER ones, which overflow at 2^31.\n *\n * One exception: a `serial` key owns a sequence, and a column pointing at it is\n * the plain integer of the same width — `SERIAL` there would give every\n * referencing column a sequence of its own.\n *\n * @param via the link asking, named if the collection's key is composite and so\n * cannot be pointed at — see `getPrimaryKeyProp`.\n */\nexport const primaryKeyPgType = (collection: CollectionConfig, via: string): PgType => {\n const { name, prop } = getPrimaryKeyProp(collection, via);\n if (prop?.type === \"number\") {\n return withoutSequence(numberType(name, prop as NumberProperty, collection, true));\n }\n if (prop?.type === \"string\") return stringType(name, prop as StringProperty, collection);\n // The implicit `id TEXT PRIMARY KEY` of a collection that declares no key.\n return { kind: \"text\" };\n};\n\n/**\n * The DEFAULT of the implicit `id TEXT PRIMARY KEY` a collection that declares\n * no key gets: a uuid, as text. The same generator `isId: \"uuid\"` uses, cast to\n * the column the key has always been.\n */\nexport const IMPLICIT_ID_DEFAULT = \"gen_random_uuid()::text\";\n\nconst withoutSequence = (type: PgType): PgType => {\n switch (type.kind) {\n case \"smallserial\": return { kind: \"smallint\" };\n case \"serial\": return { kind: \"integer\" };\n case \"bigserial\": return { kind: \"bigint\" };\n default: return type;\n }\n};\n\n/** The `columnType`s a `number` property may name, and what each one is. */\nconst NUMBER_COLUMN_TYPES: Record<string, PgType> = {\n \"integer\": { kind: \"integer\" },\n // `smallint` and `smallserial` are not in `NumberProperty[\"columnType\"]`'s\n // union, and both have always reached the database: the DDL generator\n // upper-cased whatever it was given. Accepted here for that reason and\n // listed on purpose — the point of this table is that an unrecognised\n // `columnType` is refused with the property named rather than passed\n // through to fail at `CREATE TABLE`.\n \"smallint\": { kind: \"smallint\" },\n \"smallserial\": { kind: \"smallserial\" },\n \"bigint\": { kind: \"bigint\" },\n \"serial\": { kind: \"serial\" },\n \"bigserial\": { kind: \"bigserial\" },\n \"real\": { kind: \"real\" },\n \"double precision\": { kind: \"doublePrecision\" },\n \"numeric\": { kind: \"numeric\" }\n};\n\nconst numberType = (propName: string, prop: NumberProperty, collection: CollectionConfig, isId: boolean): PgType => {\n // An identity column is INTEGER, and `columnType` is not read beside it, on\n // purpose: it is the type every identity key in the field was created with,\n // and every column pointing at one takes it too (`primaryKeyPgType`). The\n // Drizzle generator used to honour `columnType` here while the DDL one\n // ignored it, so the same property was int8 in `schema.generated.ts` and\n // int4 in the database; with `columnType: \"bigserial\"` the emitted\n // `.generatedByDefaultAsIdentity()` is not a method that exists, so the file\n // did not compile at all.\n if (prop.isId === \"increment\") return { kind: \"integer\" };\n if (prop.columnType) {\n const mapped = NUMBER_COLUMN_TYPES[prop.columnType];\n if (!mapped) {\n throw new Error(\n `Property \"${propName}\" of collection \"${describe(collection)}\" declares ` +\n `\\`columnType: \"${prop.columnType}\"\\`, which is not a Postgres numeric type Rebase emits. ` +\n `Use one of: ${Object.keys(NUMBER_COLUMN_TYPES).join(\", \")}.`\n );\n }\n if (mapped.kind === \"numeric\") return numericType(prop);\n return mapped;\n }\n if (prop.validation?.integer || isId) return { kind: \"integer\" };\n return numericType(prop);\n};\n\n/** `NUMERIC`, with the precision and scale the property asks for. */\nconst numericType = (prop: NumberProperty): PgType => {\n const { precision, scale } = prop;\n if (precision === undefined) return { kind: \"numeric\" };\n return scale === undefined\n ? { kind: \"numeric\", precision }\n : { kind: \"numeric\", precision, scale };\n};\n\nconst stringType = (propName: string, prop: StringProperty, collection: CollectionConfig): PgType => {\n if (prop.enum) {\n // Throws on an empty list rather than naming a type nothing creates —\n // the column type and the `CREATE TYPE` come from one reading of `enum`.\n const labels = enumLabelsOf(propName, prop as Property, collection);\n const table = getTableName(collection);\n const column = resolveColumnName(propName, prop as Property);\n return {\n kind: \"enum\",\n schema: schemaOf(collection),\n name: `${table}_${column}`,\n varName: getEnumVarName(table, propName),\n labels\n };\n }\n if (prop.isId === \"uuid\" || prop.columnType === \"uuid\") return { kind: \"uuid\" };\n // The width comes from `validation.max` when the property states one. It\n // used to be a hardcoded 255 in the DDL generator and *absent* on the\n // Drizzle path, so the same property produced a bounded column down one\n // generator and an unbounded one down the other.\n if (prop.columnType === \"char\") return { kind: \"char\", length: resolveStringColumnLength(prop) };\n if (prop.columnType === \"varchar\") return { kind: \"varchar\", length: resolveStringColumnLength(prop) };\n if (prop.columnType !== undefined && prop.columnType !== \"text\") {\n throw new Error(\n `Property \"${propName}\" of collection \"${describe(collection)}\" declares ` +\n `\\`columnType: \"${String(prop.columnType)}\"\\`, which is not a Postgres string type Rebase emits. ` +\n \"Use one of: text, varchar, char, uuid.\"\n );\n }\n // `text` is the default, and the only length-unbounded choice.\n return { kind: \"text\" };\n};\n\nconst arrayElementType = (prop: ArrayProperty): PgType | undefined => {\n let colType = prop.columnType;\n if (!colType && prop.of && !Array.isArray(prop.of)) {\n const of = prop.of as Property;\n if (of.type === \"string\") colType = \"text[]\";\n else if (of.type === \"number\") colType = of.validation?.integer ? \"integer[]\" : \"numeric[]\";\n else if (of.type === \"boolean\") colType = \"boolean[]\";\n }\n switch (colType) {\n case \"text[]\": return { kind: \"text\" };\n case \"integer[]\": return { kind: \"integer\" };\n case \"boolean[]\": return { kind: \"boolean\" };\n case \"numeric[]\": return { kind: \"numeric\" };\n default: return undefined;\n }\n};\n\n/**\n * The Postgres type a property's column has.\n *\n * Every member of `DataType` has an arm. A type this does not know is a\n * generator that has not been taught it yet, and it says so — a silent `TEXT`\n * here is how `geopoint` ended up with a database column, no Drizzle key, and\n * every write to it discarded with a 201.\n */\nexport const columnPgType = (\n propName: string,\n prop: Property,\n collection: CollectionConfig,\n resolveCollection: ResolveCollection\n): PgType => {\n switch (prop.type) {\n case \"string\":\n return stringType(propName, prop as StringProperty, collection);\n case \"number\":\n return numberType(propName, prop as NumberProperty, collection, isIdProperty(propName, prop, collection));\n case \"boolean\":\n return { kind: \"boolean\" };\n case \"date\": {\n const dateProp = prop as DateProperty;\n if (dateProp.columnType === \"date\") return { kind: \"date\" };\n if (dateProp.columnType === \"time\") return { kind: \"time\" };\n return { kind: \"timestamptz\" };\n }\n case \"map\":\n return (prop as MapProperty).columnType === \"json\" ? { kind: \"json\" } : { kind: \"jsonb\" };\n // `{ latitude, longitude }` — a document, like `map`.\n case \"geopoint\":\n return { kind: \"jsonb\" };\n case \"array\": {\n const arrayProp = prop as ArrayProperty;\n if (arrayProp.columnType === \"json\") return { kind: \"json\" };\n const element = arrayElementType(arrayProp);\n return element ? { kind: \"array\", of: element } : { kind: \"jsonb\" };\n }\n case \"vector\":\n return { kind: \"vector\", dimensions: (prop as VectorProperty).dimensions };\n case \"binary\":\n return { kind: \"bytea\" };\n case \"relation\":\n case \"reference\": {\n const target = linkTarget(propName, prop, collection, resolveCollection);\n return target ? primaryKeyPgType(target, linkLabel(prop.type, collection, propName)) : { kind: \"text\" };\n }\n default:\n throw new Error(\n `No Postgres column type for property \"${propName}\" of type ` +\n `\"${(prop as Property).type}\" in collection \"${describe(collection)}\". ` +\n \"Add a case to `columnPgType` in schema/plan/plan-schema.ts.\"\n );\n }\n};\n\n/** The collection a `relation` or `reference` points at, when it resolves. */\nconst linkTarget = (\n propName: string,\n prop: Property,\n collection: CollectionConfig,\n resolveCollection: ResolveCollection\n): CollectionConfig | undefined => {\n if (prop.type === \"reference\") {\n const path = (prop as ReferenceProperty).path;\n return path ? resolveCollection(path) : undefined;\n }\n const relProp = prop as RelationProperty;\n const relation = findRelation(resolveCollectionRelations(collection), relProp.relation?.relationName ?? propName);\n if (relation?.kind !== \"belongsTo\") return undefined;\n try {\n return relation.target();\n } catch {\n return undefined;\n }\n};\n\n// ── Defaults ─────────────────────────────────────────────────────────────────\n\n/** A value already written as a day, or as a time of day. */\nconst BARE_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst BARE_TIME = /^\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?$/;\n\n/**\n * A date default in the shape its column's type accepts: a day for `date`, a\n * time of day for `time`, an instant for a timestamp.\n *\n * Rendered as a full ISO timestamp whatever the column, a `time` column's\n * DEFAULT was `'2024-03-01T15:30:00.000Z'`, which Postgres refuses — \"invalid\n * input syntax for type time\" — so the schema would not apply. A value already\n * written in the column's shape (`\"2024-12-25\"`, `\"09:00\"`) is kept as written;\n * anything else is read as an instant and its UTC day or time of day taken, the\n * same zone the timestamp rendering has always used. A string that is no date\n * at all is no DEFAULT, rather than a schema that cannot be applied.\n */\nconst dateDefaultLiteral = (value: unknown, type: PgType): string | undefined => {\n if (typeof value === \"string\") {\n if (type.kind === \"date\" && BARE_DATE.test(value)) return value;\n if (type.kind === \"time\" && BARE_TIME.test(value)) return value;\n }\n const instant = value instanceof Date ? value : typeof value === \"string\" ? new Date(value) : undefined;\n if (!instant || Number.isNaN(instant.getTime())) return undefined;\n const iso = instant.toISOString();\n if (type.kind === \"date\") return iso.slice(0, 10);\n if (type.kind === \"time\") return iso.slice(11, 23);\n // A timestamp keeps a string default as it was written — its own offset\n // included — and a Date as the instant it is.\n return typeof value === \"string\" ? value : iso;\n};\n\n/**\n * A `defaultValue` as a database DEFAULT.\n *\n * `defaultValue` reached neither the schema nor — until recently — the write\n * path, so a documented, type-checked field did nothing at all: the panel\n * pre-filled it, an insert from anywhere else (the REST API, a seed, psql) did\n * not, and the column came out NULL. A DEFAULT is the one place that binds\n * every writer.\n *\n * Only literals. A `reference`'s default is an `EntityReference` object and a\n * `vector`'s is an embedding — neither is a column literal, and inventing one\n * would be a value the write path and the database disagree about.\n * `undefined` for those, which is what \"no DEFAULT\" means everywhere here.\n */\nconst literalDefault = (prop: Property, type: PgType): ColumnDefault | undefined => {\n const value = (prop as { defaultValue?: unknown }).defaultValue;\n if (value === undefined || value === null) return undefined;\n\n switch (prop.type) {\n case \"string\":\n // An enum default is its id, which is exactly the label the type\n // carries — the same string the write path stores.\n return typeof value === \"string\" ? { kind: \"literal\", value, sql: quoteSqlLiteral(value) } : undefined;\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value)\n ? { kind: \"literal\", value, sql: String(value) }\n : undefined;\n case \"boolean\":\n return typeof value === \"boolean\"\n ? { kind: \"literal\", value, sql: value ? \"TRUE\" : \"FALSE\" }\n : undefined;\n case \"date\": {\n const literal = dateDefaultLiteral(value, type);\n return literal === undefined ? undefined : { kind: \"literal\", value: literal, sql: quoteSqlLiteral(literal) };\n }\n case \"map\":\n case \"array\":\n case \"geopoint\": {\n // A document default is a JSON literal cast to the column's own\n // type, so `jsonb` and `json` columns each get a value Postgres\n // accepts without an implicit cast.\n if (type.kind !== \"jsonb\" && type.kind !== \"json\") return undefined;\n let json: string;\n try {\n json = JSON.stringify(value);\n } catch {\n return undefined; // circular, or a BigInt: not a literal.\n }\n if (json === undefined) return undefined;\n return { kind: \"literal\", value, sql: `${quoteSqlLiteral(json)}::${type.kind}` };\n }\n default:\n return undefined;\n }\n};\n\n/**\n * The DEFAULT a column carries: id strategy, then `autoValue`, then a\n * `databaseDefault` given as SQL, then `defaultValue`.\n */\nconst columnDefault = (\n propName: string,\n prop: Property,\n collection: CollectionConfig,\n type: PgType\n): ColumnDefault | undefined => {\n const idDefault = idColumnDefault(propName, prop, collection);\n if (idDefault) {\n if (idDefault.kind === \"uuid\") return { kind: \"sql\", expression: \"gen_random_uuid()\" };\n if (idDefault.kind === \"identity\") return { kind: \"identity\" };\n return { kind: \"sql\", expression: idDefault.expression };\n }\n if (prop.type === \"date\") {\n const autoValue = (prop as DateProperty).autoValue;\n if (autoValue === \"on_create\" || autoValue === \"on_update\") {\n return { kind: \"sql\", expression: \"now()\" };\n }\n }\n if (typeof prop.databaseDefault === \"string\") {\n const expression = sqlExpressionText(prop.databaseDefault).trim();\n if (expression) return { kind: \"sql\", expression };\n }\n return literalDefault(prop, type);\n};\n\n// ── Policies ─────────────────────────────────────────────────────────────────\n\n/**\n * One security rule, compiled to the clauses a policy is made of.\n *\n * The compilation is `compileRulePolicies` in `@rebasepro/common`, which the\n * Studio's RLS editor also compares the live database against — so the UI, the\n * DDL and the database agree about who can read a row. What this adds is only\n * the planner's bookkeeping: which rule a policy came from, and whether Rebase\n * injected it.\n */\nexport const compileSecurityRule = (\n collection: CollectionConfig,\n rule: SecurityRule,\n resolveCollection: ResolveCollection,\n injected: boolean,\n ruleKey = rule.name ?? \"(unnamed)\"\n): PolicyPlan[] => {\n const supersedes = getPolicySupersededNames(rule, getTableName(collection));\n // This driver switches admin requests to `<role>_admin`, so it may have\n // server-or-admin grants written TO rebase_admin (`rls.adminPolicies`).\n return compileRulePolicies(collection, rule, { resolveCollection, adminRole: true })\n .map((policy, index) => ({\n ...policy,\n ruleKey,\n injected,\n ...(index === 0 && supersedes.length > 0 ? { supersedes } : {})\n }));\n};\n\n/**\n * Refuse two of a table's policies that Postgres would store under one name.\n *\n * Each policy is rendered as `DROP POLICY IF EXISTS \"<name>\"` and then its\n * `CREATE`, and Postgres keeps the first 63 bytes of the name, so the second\n * of two policies whose names share those bytes drops the first and takes its\n * place. On a table of 56 bytes or more every unnamed rule of one operation is\n * `<table>_<op>` once stored, so a restrictive gate followed by a grant left\n * the grant alone in force. One rule's own operations never collide here —\n * `getPolicyNamesForRule` names them apart — so a collision is always two\n * rules, and the author names one of them.\n */\nconst sameStoredPolicy = (a: PolicyPlan, b: PolicyPlan): boolean =>\n a.name === b.name && a.operation === b.operation && a.mode === b.mode\n && a.roles.join(\",\") === b.roles.join(\",\") && a.using === b.using && a.withCheck === b.withCheck;\n\nfunction assertDistinctStoredPolicyNames(policies: PolicyPlan[]): void {\n const owners = new Map<string, PolicyPlan>();\n for (const policy of policies) {\n const stored = toPostgresIdentifier(policy.name);\n const first = owners.get(stored);\n if (!first) {\n owners.set(stored, policy);\n continue;\n }\n // The same policy twice — a rule repeated verbatim — replaces itself.\n if (sameStoredPolicy(first, policy)) continue;\n throw new Error(\n `The security rules \"${first.ruleKey}\" and \"${policy.ruleKey}\" compile to the policies ` +\n `\"${first.name}\" and \"${policy.name}\", which Postgres stores under one name, \"${stored}\": it ` +\n \"keeps only the first 63 bytes of an identifier, so the second would replace the first. \" +\n \"Give one of the rules a shorter `name`, or the collection a shorter `table`.\"\n );\n }\n}\n\n/**\n * A table's policies, minus any superseded name Postgres would store one of\n * them under.\n *\n * A superseded name is a 63-byte cut, and another rule's over-long name can\n * cut to the very same bytes — `<table>_default_admin_read` and the old\n * `<table>_default_admin_write_<op>` both do on a 50-byte table. Dropping it\n * then would drop that policy right after its own `CREATE`. Its own `DROP\n * POLICY IF EXISTS` already removes the old policy, so nothing is lost.\n */\nconst withoutLiveSupersededNames = (policies: PolicyPlan[]): PolicyPlan[] => {\n assertDistinctStoredPolicyNames(policies);\n const stored = new Set(policies.map(policy => toPostgresIdentifier(policy.name)));\n return policies.map(policy => {\n if (!policy.supersedes) return policy;\n const supersedes = policy.supersedes.filter(name => !stored.has(name));\n if (supersedes.length === policy.supersedes.length) return policy;\n const kept: PolicyPlan = { ...policy };\n if (supersedes.length > 0) kept.supersedes = supersedes;\n else delete kept.supersedes;\n return kept;\n });\n};\n\n/**\n * Whether a collection serves a SQL view rather than a table.\n *\n * A link into one is read-side only. Postgres refuses a foreign key that\n * references a view (\"referenced relation is not a table\"), and the generated\n * drizzle file declares no variable for a view, so a link into one plans no\n * constraint and no generated relation. The runtime still reads it: its\n * relations are built from the catalogue, which holds views.\n */\nconst servesView = (collection: CollectionConfig): boolean =>\n isPostgresCollectionConfig(collection) && Boolean(collection.view);\n\n// ── The planner ──────────────────────────────────────────────────────────────\n\nexport function planSchema(allCollections: CollectionConfig[], options: PlanOptions = {}): SchemaPlan {\n // Before the filter, deliberately: a `search` block on a collection this\n // engine does not store would otherwise be dropped without a word.\n assertSearchIsPostgresOnly(allCollections);\n // Same reasoning, and a stronger reason to be loud: a `beforeQuery` that\n // does nothing is a row filter that does nothing.\n assertBeforeQueryIsPostgresOnly(allCollections);\n\n // A Firestore or MongoDB collection has no table here, and generating one\n // is not merely wasted output: `db push` would create it, and the doctor\n // would then report the store the collection actually reads from as drift.\n const relational = relationalCollections(allCollections);\n // A collection that serves a view has no table, policy or enum: it is\n // planned on its own (`views`), and resolvable as a relation target.\n const collections = relational.filter(c => !servesView(c));\n\n // The first collection, in declaration order, whose slug or table name is\n // the key — what `collections.find(...)` answered, from a map built once\n // rather than a scan per lookup.\n const firstBySlugOrTable = new Map<string, CollectionConfig>();\n for (const c of relational) {\n for (const key of [c.slug, getTableName(c)]) {\n if (!firstBySlugOrTable.has(key)) firstBySlugOrTable.set(key, c);\n }\n }\n const resolveCollection: ResolveCollection = (slug) => firstBySlugOrTable.get(slug);\n\n const declaredSchemas = Array.from(new Set(\n collections.map(c => (isPostgresCollectionConfig(c) ? c.schema : undefined)).filter(Boolean) as string[]\n ));\n const schemas = Array.from(new Set([REBASE_SCHEMA, ...declaredSchemas]));\n\n // ── Enum types ───────────────────────────────────────────────────────────\n // The name is derived from table + column, so two collections mapped onto\n // the same table — or two properties whose `columnName` resolves to the\n // same column — land on the same type. `CREATE TYPE` has no IF NOT EXISTS,\n // so emitting it twice aborts the whole file; deduplicated by name here,\n // once, for every renderer.\n //\n // Deduplicated by the name *Postgres* holds, which is the first 63 bytes,\n // and only for the same column. Two different columns deriving one name —\n // `orders.item_status` and `orders_item.status`, or two long names that\n // share their first 63 bytes — cannot share a type: the second column would\n // be typed with the first one's labels and reject its own. The name is\n // frozen once a database holds it, so this refuses rather than renaming.\n const enums: EnumPlan[] = [];\n const enumOwners = new Map<string, { table: string; column: string; owner: string }>();\n /**\n * Every enum type one table's properties declare, appended once.\n *\n * `declaredSchema` is passed rather than read off the config because a\n * junction's synthetic collection carries `schema: \"public\"` as a resolved\n * fact and not as a declaration — emitting it as one would make the\n * generated file reach for a `pgSchema(\"public\")` variable that exists for\n * nobody.\n */\n const collectEnumTypes = (\n collection: CollectionConfig,\n properties: Properties,\n declaredSchema: string | undefined\n ): void => {\n for (const [propName, rawProp] of Object.entries(properties)) {\n const prop = rawProp as Property;\n if (!(\"enum\" in prop) || !prop.enum) continue;\n if (prop.type !== \"string\" && prop.type !== \"number\") continue;\n // Refuses an empty list whatever the property's type, then declares\n // a type only for the string ones: a `number` enum's column is\n // NUMERIC or INTEGER on every path, so the type used to be created\n // and referenced by nothing.\n const labels = enumLabelsOf(propName, prop, collection);\n if (!declaresEnumType(prop)) continue;\n const schema = schemaOf(collection);\n const table = getTableName(collection);\n const column = resolveColumnName(propName, prop);\n const name = `${table}_${column}`;\n const qualified = `${schema}.${toPostgresIdentifier(name)}`;\n const owner = `property \"${propName}\" of collection \"${describe(collection)}\"`;\n const claimed = enumOwners.get(qualified);\n if (claimed) {\n if (claimed.table === table && claimed.column === column) continue;\n throw new Error(\n `The enum ${owner} and the enum ${claimed.owner} both derive the Postgres type ` +\n `\"${schema}\".\"${toPostgresIdentifier(name)}\" (an enum type is named <table>_<column>, ` +\n \"and Postgres keeps the first 63 bytes). One type cannot hold both columns' values, and a \" +\n \"type's name cannot change once a database holds it. Give one of the two columns another \" +\n \"name with `columnName`, or its collection another `table` or `schema`.\"\n );\n }\n enumOwners.set(qualified, { table, column, owner });\n enums.push({\n schema,\n name,\n qualified,\n declaredSchema,\n varName: getEnumVarName(getTableName(collection), propName),\n labels\n });\n }\n };\n for (const collection of collections) {\n collectEnumTypes(\n collection,\n (collection.properties ?? {}) as Properties,\n isPostgresCollectionConfig(collection) ? collection.schema : undefined\n );\n }\n\n // ── The table set ────────────────────────────────────────────────────────\n // Each collection's table, then any junction its relations imply, in the\n // order the collections arrive. `schema.sql` and `schema.generated.ts` are\n // compared against their committed copies, so this order is the file's.\n const tableEntries = new Map<string, {\n collection: CollectionConfig;\n junction?: { relation: ResolvedRelation; source: CollectionConfig };\n }>();\n const junctionShapes = new Map<string, { keys: string; claim: string }>();\n for (const collection of collections) {\n const tableName = getTableName(collection);\n if (tableName) tableEntries.set(tableName, { collection });\n for (const [relationKey, relation] of Object.entries(resolveCollectionRelations(collection))) {\n if (!isManyToMany(relation)) continue;\n const junctionTable = relation.through.table;\n assertOneJunctionShape(junctionShapes, junctionTable, collection, relation.relationName ?? relationKey, relation);\n if (tableEntries.has(junctionTable)) continue;\n tableEntries.set(junctionTable, {\n collection: { table: junctionTable, properties: {} } as CollectionConfig,\n junction: { relation, source: collection }\n });\n }\n }\n\n const junctionSpecs = resolveJunctionSpecs(collections);\n\n // A junction's payload may declare an enum too, and the type it names is\n // created by nobody else: no collection owns the table, so the loop above\n // never sees the property. Appended after the collections' — the enum block\n // is compared byte-for-byte against its committed copy, and a junction\n // whose type interleaved with the collections' would reorder that file\n // whenever a `through.properties` block moved.\n for (const spec of junctionSpecs.values()) {\n if (Object.keys(spec.properties).length === 0) continue;\n collectEnumTypes(getJunctionCollectionConfig(spec), spec.properties, undefined);\n }\n\n const triggerFunctionNeeded = { value: false };\n\n const tables: TablePlan[] = [];\n for (const [tableName, entry] of tableEntries) {\n tables.push(entry.junction\n ? planJunctionTable(\n tableName, entry.junction.relation, entry.junction.source,\n junctionSpecs, resolveCollection, triggerFunctionNeeded)\n : planCollectionTable(entry.collection, resolveCollection, triggerFunctionNeeded));\n }\n\n assertNoTruncationCollisions(tables, enums);\n\n // ── Extensions and functions ─────────────────────────────────────────────\n const extensions: string[] = [];\n const functions: string[] = [];\n const seenStatements = new Set<string>();\n const add = (into: string[], statement: string): void => {\n if (seenStatements.has(statement)) return;\n seenStatements.add(statement);\n into.push(statement);\n };\n for (const table of tables) {\n if (!table.search) continue;\n for (const statement of searchExtensionStatements(table.search)) add(extensions, statement);\n }\n // pgvector is a separate build behind an image, a grant and a provider\n // allow-list, so whether Rebase may install it is not Rebase's to decide.\n // See `DatabaseOptions.extensions`.\n if (vectorExtensionDeclared(options.databaseExtensions)\n && tables.some(t => t.vectorColumns.length > 0)) {\n add(extensions, vectorExtensionStatement());\n }\n for (const table of tables) {\n if (!table.search) continue;\n for (const statement of searchHelperFunctions(table.search)) add(functions, statement);\n }\n if (triggerFunctionNeeded.value) add(functions, setUpdatedAtFunction());\n if (tables.some(t => t.triggers.some(trigger => trigger.kind === \"keep-tenant\"))) add(functions, keepTenantFunction());\n\n return {\n schemas,\n declaredSchemas,\n enums,\n tables,\n views: planViews(relational),\n relations: planRelations(collections, tableEntries),\n extensions,\n functions,\n collections,\n options\n };\n}\n\n/**\n * The view collections' views, each after the views its query names.\n *\n * Which views a query reads is read off its text — a planned view's name as a\n * whole word — which is enough to order them: a name that appears in a string\n * literal only orders two views that did not need it, never the other way.\n */\nexport function planViews(collections: CollectionConfig[]): ViewPlan[] {\n const declared = collections.flatMap(collection => {\n if (!isPostgresCollectionConfig(collection) || !collection.view) return [];\n const schema = schemaOf(collection);\n const name = getTableName(collection);\n const idColumns = Object.entries(collection.properties ?? {})\n .filter(([, property]) => Boolean((property as { isId?: unknown }).isId))\n .map(([key, property]) => resolveColumnName(key, property as Property));\n const materialized = collection.view.materialized === true;\n return [{\n schema, name, qualified: `${schema}.${name}`,\n query: collection.view.query.trim().replace(/;\\s*$/, \"\"),\n materialized,\n roles: materialized ? [...(collection.view.roles ?? DEFAULT_VIEW_ROLES)] : [],\n idColumns,\n // A materialized view's own `indexes`, on its stored rows.\n indexes: materialized\n ? buildCollectionIndexSpecs(collection, resolveColumnName)\n .map(spec => collectionIndexStatement({ ...spec, table: viewRowsName(name) }).replace(/;$/, \"\"))\n : []\n }];\n });\n const named = (query: string, view: { schema: string; name: string }) =>\n new RegExp(`(^|[^A-Za-z0-9_$\"])\"?${escapeRegExp(view.name)}\"?([^A-Za-z0-9_$\"]|$)`).test(query);\n const withDependencies = declared.map(view => ({\n ...view,\n dependsOn: declared.filter(other => other !== view && named(view.query, other)).map(other => other.qualified)\n }));\n\n // Depth-first, so every view lands after what it reads; a cycle is two\n // queries naming each other, which Postgres refuses to create anyway.\n const ordered: typeof withDependencies = [];\n const placed = new Set<string>();\n const visiting = new Set<string>();\n const place = (view: typeof withDependencies[number]): void => {\n if (placed.has(view.qualified)) return;\n if (visiting.has(view.qualified)) {\n throw new Error(`The views ${[...visiting].join(\", \")} read each other; a view cannot be created before the view it reads.`);\n }\n visiting.add(view.qualified);\n for (const dependency of view.dependsOn) {\n const target = withDependencies.find(other => other.qualified === dependency);\n if (target) place(target);\n }\n visiting.delete(view.qualified);\n placed.add(view.qualified);\n ordered.push(view);\n };\n for (const view of withDependencies) place(view);\n\n return ordered.map(view => ({\n ...view,\n hash: createHash(\"sha256\")\n // `gated`: a materialized view is its stored rows behind a view\n // that serves them to its roles (0.29.0 created the bare matview).\n .update(JSON.stringify([view.qualified, view.query, view.materialized, view.idColumns,\n ...(view.materialized ? [\"gated\", view.roles, view.indexes] : [])]))\n .digest(\"hex\")\n .slice(0, 16)\n }));\n}\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Refuse two relations — tables, junctions and enum types share one namespace\n * per schema, because every table owns a row type of its own name — that are\n * distinct in full but one name after Postgres keeps the first 63 bytes.\n *\n * `a_table_with_a_really_long_name_that_goes_on_and_on_and_on_forever` with an\n * enum column and a many-to-many truncated its table, its enum type and its\n * junction to the same identifier: the push failed with `type \"…\" already\n * exists` and no validator mentioned the length. A name that already works is\n * never touched — only a collision that cannot be created refuses.\n */\nfunction assertNoTruncationCollisions(tables: TablePlan[], enums: EnumPlan[]): void {\n const owners = new Map<string, string>();\n const claim = (schema: string, name: string, what: string): void => {\n const key = `${schema}.${toPostgresIdentifier(name)}`;\n const first = owners.get(key);\n if (first === undefined) {\n owners.set(key, what);\n return;\n }\n throw new Error(\n `The ${what} and the ${first} both become \"${schema}\".\"${toPostgresIdentifier(name)}\" in Postgres, ` +\n \"which keeps only the first 63 bytes of an identifier — and a table, a junction table and an enum \" +\n \"type share one namespace (every table owns a row type of its name). The push would fail with \" +\n \"\\\"already exists\\\". Give the collection a shorter `table`, or the enum's property a shorter \" +\n \"`columnName` (an enum type is named <table>_<column>).\"\n );\n };\n for (const table of tables) {\n claim(table.schema, table.table, table.kind === \"junction\" ? `junction table \"${table.table}\"` : `table \"${table.table}\"`);\n }\n for (const e of enums) claim(e.schema, e.name, `enum type \"${e.name}\"`);\n}\n\n/**\n * Refuse two many-to-many relations that resolve to one junction table with\n * different key columns.\n *\n * A default `through` is named after the two tables, so `posts.tags` and\n * `posts.featuredTags` both resolve to `posts_tags` — one keyed by `tag_id`,\n * the other by `featured_tag_id`. One table is created, from whichever came\n * first, so the other relation read and wrote a column that was never there.\n * The two sides of one link (`posts.tags` and `tags.posts`) share a junction\n * legitimately, and they name the same two columns — so the comparison is of\n * the (column, endpoint) pairs, in either order.\n */\nfunction assertOneJunctionShape(\n seen: Map<string, { keys: string; claim: string }>,\n junctionTable: string,\n collection: CollectionConfig,\n relationName: string,\n relation: ResolvedRelation\n): void {\n if (!isManyToMany(relation)) return;\n // A target that does not resolve plans no junction here; `resolveJunctionSpecs` skips it the same way.\n const target: CollectionConfig | undefined = relation.target();\n if (!target) return;\n const sourceTable = getTableName(collection);\n const targetTable = getTableName(target);\n const { sourceColumn, targetColumn } = relation.through;\n const keys = JSON.stringify([[sourceColumn, sourceTable], [targetColumn, targetTable]].sort());\n const claim = `the relation \"${relationName}\" of collection \"${describe(collection)}\" ` +\n `(\"${sourceColumn}\" → ${sourceTable}, \"${targetColumn}\" → ${targetTable})`;\n const first = seen.get(junctionTable);\n if (!first) {\n seen.set(junctionTable, { keys, claim });\n return;\n }\n if (first.keys === keys) return;\n throw new Error(\n `Two many-to-many relations resolve to the junction table \"${junctionTable}\" with different key ` +\n `columns: ${first.claim} and ${claim}. Only one table is created, so one of them would read ` +\n \"and write columns that do not exist. Give the second its own junction — \" +\n `\\`through: { table: \"${sourceTable}_${toSnakeCase(relationName)}\" }\\` — or, if both are meant to ` +\n \"be one link, declare it once.\"\n );\n}\n\n// ── A collection's table ─────────────────────────────────────────────────────\n\nfunction planCollectionTable(\n collection: CollectionConfig,\n resolveCollection: ResolveCollection,\n triggerFunctionNeeded: { value: boolean }\n): TablePlan {\n const schema = schemaOf(collection);\n const table = bareTableName(getTableName(collection));\n const auth = isAuthCollection(collection);\n const columns: ColumnPlan[] = [];\n const triggers: TriggerPlan[] = [];\n const relations = resolveCollectionRelations(collection);\n\n for (const [propName, rawProp] of Object.entries(collection.properties ?? {})) {\n const prop = rawProp as Property;\n\n if (prop.type === \"relation\") {\n const column = planRelationColumn(propName, prop as RelationProperty, collection, relations, schema, table);\n if (column) columns.push(column);\n continue;\n }\n if (prop.type === \"reference\") {\n columns.push(planReferenceColumn(propName, prop as ReferenceProperty, collection, resolveCollection, schema, table));\n continue;\n }\n\n columns.push(planPropertyColumn(propName, prop, {\n collection,\n resolveCollection,\n schema,\n table,\n auth,\n triggers,\n triggerFunctionNeeded\n }));\n }\n\n // ── Auth columns the collection file never mentions ──────────────────────\n // `db push` is declarative: Atlas diffs the database against exactly what\n // is emitted and drops anything else. The scaffold's users collection\n // describes 12 columns while auth needs 14, so `is_anonymous` and\n // `tokens_valid_after` read as unmanaged drift and a push run after the\n // server had started once planned to DROP them.\n if (auth) {\n const declared = new Set(columns.map(c => c.column));\n for (const spec of AUTH_USERS_COLUMNS) {\n if (declared.has(spec.column)) continue;\n columns.push({\n key: spec.column,\n column: spec.column,\n type: authColumnType(spec.type),\n nullable: spec.notNull !== true,\n primaryKey: false,\n unique: false,\n sqlDefinition: authUsersColumnSql(spec),\n source: { kind: \"auth\", slug: collection.slug }\n });\n }\n }\n\n // ── The opt-in search column ─────────────────────────────────────────────\n // Last, so it reads as what it is: derived from the columns above it.\n // Postgres recomputes it on every write of a source column and rejects any\n // attempt to write it directly, which is what makes it impossible for the\n // index to drift from the row.\n const search = buildSearchColumnSpec(collection);\n if (search) {\n columns.push({\n key: search.column,\n column: search.column,\n type: { kind: \"tsvector\" },\n nullable: true,\n primaryKey: false,\n unique: false,\n generated: { expression: search.expression, stored: true },\n sqlDefinition: searchColumnTypeSql(search.expression, \"tsvector\"),\n source: { kind: \"search\", slug: collection.slug }\n });\n if (search.fuzzy) {\n columns.push({\n key: search.fuzzy.column,\n column: search.fuzzy.column,\n type: { kind: \"text\" },\n nullable: true,\n primaryKey: false,\n unique: false,\n generated: { expression: search.fuzzy.expression, stored: true },\n sqlDefinition: searchColumnTypeSql(search.fuzzy.expression, \"text\"),\n source: { kind: \"search\", slug: collection.slug }\n });\n }\n }\n\n const primaryKey = planPrimaryKey(collection, columns);\n\n const injected = new Set(getInjectedSecurityRules(collection).map(rule => rule.name));\n const policies = withoutLiveSupersededNames(getEffectiveSecurityRules(collection).flatMap((rule, index) =>\n compileSecurityRule(\n collection,\n rule,\n resolveCollection,\n Boolean(rule.name && injected.has(rule.name)),\n rule.name ?? `#${index}`\n )));\n\n // ── Tenancy ──────────────────────────────────────────────────────────────\n // The policy is already above — `getEffectiveSecurityRules` injects it, so\n // it compiles, names and renders like every other rule. What is left is the\n // half a rule cannot express: the column is NOT NULL, and it is indexed.\n const tenantIndexes = applyTenantColumnEffects(collection, columns, primaryKey, schema, table);\n const keepTenant = planKeepTenantTrigger(collection, columns, schema, table);\n if (keepTenant) triggers.push(keepTenant);\n\n // Last among the columns, because it reads a nullability the two passes\n // above can still change.\n settleDefaultOnDelete(collection, columns, relations);\n\n // After every other index, because the foreign-key ones defer to them: a\n // declared index or the tenant index that already leads with the column\n // serves the same lookups, and a second one would only cost writes.\n const indexes = [...buildCollectionIndexSpecs(collection, resolveColumnName), ...tenantIndexes];\n indexes.push(...planForeignKeyIndexes(schema, table, columns, primaryKey, indexes, column => {\n // A `belongsTo` whose author opted out keeps its constraint and loses\n // only the index. Asked of the relation, not the column: the column a\n // declared property owns carries no relation of its own.\n if (column.source.kind !== \"relation\" || !column.source.propName) return false;\n const prop = collection.properties?.[column.source.propName] as RelationProperty | undefined;\n const relation = findRelation(relations, prop?.relation?.relationName ?? column.source.propName);\n return relation?.kind === \"belongsTo\" && relation.index;\n }));\n\n return {\n schema,\n table,\n qualified: `${schema}.${table}`,\n declaredSchema: isPostgresCollectionConfig(collection) ? collection.schema : undefined,\n varName: getTableVarName(getTableName(collection)),\n kind: \"collection\",\n slug: collection.slug,\n columns,\n primaryKey,\n indexes,\n search,\n vector: buildVectorIndexPlan(collection, resolveColumnName),\n vectorColumns: buildVectorColumnSpecs(collection, resolveColumnName),\n policies,\n triggers,\n auth\n };\n}\n\n/**\n * The table's primary key, as the column names {@link TablePlan.primaryKey}\n * lists — and the columns adjusted to state it one way only.\n *\n * One `isId` property is a key column of its own, declared inline\n * (`\"id\" INTEGER PRIMARY KEY`, `.primaryKey()`), which is how\n * {@link planPropertyColumn} planned it. Several are one composite key, and a\n * composite key cannot be said column by column: two inline `PRIMARY KEY`\n * clauses are two primary keys, which Postgres refuses. So each member stops\n * being a key of its own, keeps NOT NULL (the constraint implies it, and every\n * emitter spells it on the column so the three read the same), and the table\n * gets one `PRIMARY KEY (a, b)` over the list returned here — the shape a\n * junction's key has always had.\n *\n * A collection that declares no key gets an implicit `id TEXT PRIMARY KEY`,\n * which is what `getPrimaryKeys` reads back.\n */\nfunction planPrimaryKey(collection: CollectionConfig, columns: ColumnPlan[]): string[] {\n const keyNames = primaryKeyPropertyNames(collection);\n\n if (keyNames.length > 1) {\n return keyNames.map(name => {\n const column = columns.find(c => c.source.propName === name && !c.columnOwnedByProperty);\n if (!column) {\n throw new Error(\n `Property \"${name}\" of collection \"${describe(collection)}\" is marked \\`isId\\`, and it puts ` +\n \"no column on this table, so it cannot be part of the table's primary key. Mark the \" +\n \"property that holds the column instead.\"\n );\n }\n column.primaryKey = false;\n column.nullable = false;\n return column.column;\n });\n }\n\n // With a default the database fills. Nothing else can: the key is not a\n // property, so the admin form has no field for it, and REST, the SDK and\n // the socket send none. Without one, every insert into a collection that\n // declares no key — the quickstart's first one among them — was refused\n // as a missing `id`. The column stays TEXT so a table created before this\n // keeps its type, and boot's ensure adds the default to it: a DEFAULT binds\n // only future writes, so it is the one change it makes to an existing\n // column. A key the caller does supply still wins over the default.\n if (!columns.some(c => c.primaryKey)) {\n columns.unshift({\n key: \"id\",\n column: \"id\",\n type: { kind: \"text\" },\n nullable: false,\n primaryKey: true,\n unique: false,\n default: { kind: \"sql\", expression: IMPLICIT_ID_DEFAULT },\n source: { kind: \"implicit-id\", slug: collection.slug }\n });\n }\n return columns.filter(c => c.primaryKey).map(c => c.column);\n}\n\n/** What {@link planPropertyColumn} needs about the table the column lands on. */\ninterface PropertyColumnContext {\n /** The collection, or the synthetic one standing in for a junction. */\n collection: CollectionConfig;\n resolveCollection: ResolveCollection;\n schema: string;\n /** Bare table name — the trigger name is derived from it. */\n table: string;\n /** Whether `auth-users-columns` owns this table's columns. */\n auth: boolean;\n /** Collected `BEFORE UPDATE` triggers, appended to. */\n triggers: TriggerPlan[];\n triggerFunctionNeeded: { value: boolean };\n}\n\n/**\n * One declared, non-linking property, as a column.\n *\n * Extracted from {@link planCollectionTable} the moment a second table needed\n * it: a `manyToMany`'s `through.properties` are columns on the junction, and\n * \"declared exactly like a collection's properties\" has to mean the same code\n * reads them, or it is a promise the next `columnType` or `defaultValue` change\n * quietly breaks. A junction payload column therefore gets the type, the\n * nullability, the default, the UNIQUE and the `on_update` trigger a collection\n * column with the same declaration gets — because it is the same function\n * answering.\n *\n * `relation` and `reference` do not come through here; they own a foreign key\n * and are planned by {@link planRelationColumn} / {@link planReferenceColumn}.\n * A junction payload may not declare either (config validation refuses it), so\n * this is the whole of a payload column.\n */\nfunction planPropertyColumn(\n propName: string,\n prop: Property,\n ctx: PropertyColumnContext\n): ColumnPlan {\n const { collection, resolveCollection, schema, table, auth } = ctx;\n\n const isId = isIdProperty(propName, prop, collection);\n const column = resolveColumnName(propName, prop);\n const type = columnPgType(propName, prop, collection, resolveCollection);\n const required = prop.validation?.required === true;\n const defaultValue = columnDefault(propName, prop, collection, type);\n // On an auth collection, the columns auth itself reads and writes have\n // exactly one definition wherever the table is created from — see\n // `auth-users-columns`. Anything else there is an ordinary field.\n const authDefinition = auth && !isId ? authUsersColumnDefinition(column) : undefined;\n\n const plan: ColumnPlan = {\n key: propName,\n column,\n type,\n // A primary key is NOT NULL whether or not anyone writes it.\n nullable: !(isId || required),\n primaryKey: isId,\n // `validation.unique` holds for every type. The Drizzle generator\n // honoured it on `string` and `number` only, so a unique `date` or\n // `map` was UNIQUE in the database and not in the file drizzle-kit\n // plans from. A primary key gets neither UNIQUE nor NOT NULL —\n // both are implied, and emitting them made drizzle-kit plan an\n // extra constraint against a database `db push` built without one.\n unique: !isId && prop.validation?.unique === true,\n default: defaultValue,\n sqlDefinition: authDefinition,\n source: { kind: \"property\", propName, slug: collection.slug }\n };\n if (prop.type === \"date\" && (prop as DateProperty).autoValue === \"on_update\") {\n plan.touchOnUpdate = true;\n ctx.triggerFunctionNeeded.value = true;\n ctx.triggers.push({\n schema,\n table,\n column,\n name: toPostgresIdentifier(`${table}_${column}_touch`)\n });\n }\n return plan;\n}\n\n/**\n * The two schema effects a `tenant` declaration has that a policy cannot state.\n *\n * The policy itself is injected as an ordinary `SecurityRule`\n * (`buildTenantSecurityRule`) and compiled above with every other rule, so\n * nothing here touches `policies`. What is left is the column:\n *\n * - **`NOT NULL`.** A row whose tenant is NULL belongs to nobody, and the\n * restrictive policy compares the column to the caller's tenant — a\n * comparison against NULL is never true. Such a row is therefore invisible to\n * every caller, forever, including the one who wrote it. The write path\n * refuses to create one (`TENANT_REQUIRED`); this is the same statement made\n * where a raw `INSERT`, a seed and a migration can also hear it.\n * - **An index.** The tenancy predicate is ANDed into *every* statement against\n * the table, so an unindexed tenant column turns every read into a sequential\n * scan filtered by tenant. It is the one index a tenant-scoped table cannot\n * be without, and the one people most reliably forget — which is the whole\n * argument for deriving it rather than documenting it.\n *\n * The index goes through `deriveIndexName` like every other index, so it is a\n * Rebase-managed name (`_ix_<fingerprint>`), it is in the Atlas diff, and the\n * doctor recognises it. Because that name is a fingerprint of the index's\n * semantics, an author who has *already* declared a plain btree index on the\n * tenant column derives byte-for-byte the same name — so the two are the same\n * object and this adds nothing rather than colliding.\n *\n * Throws when the field names no column. `planSchema` throws rather than\n * guessing, and the alternative here is a table with a tenancy policy over a\n * column that does not exist: `CREATE POLICY` fails, RLS stays enabled, and the\n * collection denies every row.\n */\nfunction applyTenantColumnEffects(\n collection: CollectionConfig,\n columns: ColumnPlan[],\n primaryKey: string[],\n schema: string,\n table: string\n): CollectionIndexSpec[] {\n const tenant = getTenantConfig(collection);\n if (!tenant) return [];\n\n const column = findTenantColumn(collection, columns, tenant.field);\n if (!column) {\n throw new Error(\n `Collection \"${describe(collection)}\" declares \\`tenant: { field: \"${tenant.field}\" }\\`, and ` +\n \"no property of that name reaches a column. `tenant` says what a column means; it does not \" +\n \"create one. Declare the property, or name the one that holds the tenant id.\"\n );\n }\n\n // The leading column of the primary key is already NOT NULL and already\n // indexed by `<table>_pkey`. Saying either again would make `db push` plan\n // a constraint and an index the database has no reason to hold. A later\n // column of a composite key is NOT NULL too, but `<table>_pkey` cannot\n // serve a lookup on it alone, so it still gets its index.\n if (primaryKey[0] === column.column) return [];\n\n column.nullable = false;\n\n const withoutName = {\n schema,\n table,\n method: \"btree\" as const,\n unique: false,\n keys: [{ column: column.column, direction: \"asc\" as const, nulls: \"last\" as const }],\n include: [],\n predicate: null,\n reason: TENANT_INDEX_REASON\n };\n return [{ ...withoutName, indexName: deriveIndexName(withoutName) }];\n}\n\n/**\n * The trigger that keeps a row in its tenant, or nothing when the collection\n * declares no `tenant`. See `tenant-keep-trigger.ts` for why a policy cannot.\n */\nfunction planKeepTenantTrigger(\n collection: CollectionConfig,\n columns: ColumnPlan[],\n schema: string,\n table: string\n): TriggerPlan | undefined {\n const tenant = getTenantConfig(collection);\n if (!tenant) return undefined;\n const column = findTenantColumn(collection, columns, tenant.field);\n if (!column) return undefined;\n return {\n schema,\n table,\n column: column.column,\n name: toPostgresIdentifier(keepTenantTriggerName(table)),\n kind: \"keep-tenant\",\n bypassRoles: [...tenantBypassRoles(tenant)]\n };\n}\n\n/**\n * A btree on each foreign-key column of one table, where nothing already\n * serves the lookup — see `foreignKeyIndexSpec` for why the column needs one.\n *\n * Skipped, so that no table ever carries two indexes doing one job, when the\n * column already leads:\n *\n * - the primary key — `<table>_pkey` is a btree over the key in key order, so\n * its first column is indexed and the rest are not (a junction's\n * `(post_id, tag_id)` key serves `post_id`, and `tag_id` gets an index);\n * - a UNIQUE on the column (`validation.unique`, on the relation or on the\n * property that owns the column) — Postgres backs it with a btree;\n * - another planned index that leads with it ({@link leadsWithColumn}) — one\n * the collection declares in `indexes:`, or the tenant index.\n *\n * Only the plan is consulted, never the catalogue: `db push` renders this from\n * the collections alone, and boot has to reach the same set with the same\n * names, or Atlas would plan to drop what boot built.\n */\nfunction planForeignKeyIndexes(\n schema: string,\n table: string,\n columns: ColumnPlan[],\n primaryKey: string[],\n planned: readonly CollectionIndexSpec[],\n wantsIndex: (column: ColumnPlan) => boolean\n): CollectionIndexSpec[] {\n const created = columns.filter(c => !c.columnOwnedByProperty);\n const derived: CollectionIndexSpec[] = [];\n for (const column of columns) {\n const fk = column.foreignKey;\n if (!fk || !wantsIndex(column)) continue;\n const name = fk.column;\n if (primaryKey[0] === name) continue;\n if (created.some(c => c.column === name && c.unique)) continue;\n if ([...planned, ...derived].some(spec => leadsWithColumn(spec, name))) continue;\n derived.push(foreignKeyIndexSpec(schema, table, name));\n }\n return derived;\n}\n\n/**\n * The planned column a `tenant.field` names.\n *\n * Not simply `columns.find(c => c.key === field)`: a `belongsTo` relation\n * property emits its column under the *foreign key's* field name, so\n * `tenant: { field: \"org\" }` beside `org: { type: \"relation\", … }` has to\n * resolve through the relation to `org_id`. Matching only on `key` found\n * nothing there and the declaration would have been refused as naming no\n * column — for the shape the documentation recommends.\n */\nfunction findTenantColumn(\n collection: CollectionConfig,\n columns: ColumnPlan[],\n field: string\n): ColumnPlan | undefined {\n // Only columns that are created. A relation whose column a declared\n // property owns keeps an entry for its constraint alone, under the same key\n // and column; when the relation was declared first, NOT NULL landed on that\n // entry, nothing rendered it, and the tenant column stayed nullable.\n const created = columns.filter(c => !c.columnOwnedByProperty);\n const direct = created.find(c => c.key === field);\n if (direct) return direct;\n\n const prop = collection.properties?.[field] as Property | undefined;\n if (prop?.type === \"relation\") {\n const relations = resolveCollectionRelations(collection);\n const relation = findRelation(relations, (prop as RelationProperty).relation?.relationName ?? field);\n if (relation?.kind === \"belongsTo\" && relation.localKey) {\n return created.find(c => c.column === relation.localKey);\n }\n return undefined;\n }\n if (!prop) return undefined;\n const columnName = resolveColumnName(field, prop);\n return created.find(c => c.column === columnName);\n}\n\n/**\n * The `ON DELETE` a link gets when the author did not say, decided from the\n * column as it will be created.\n *\n * {@link planRelationColumn} and {@link planReferenceColumn} see only their own\n * property's `required`, and two later facts change the premise: `tenant` makes\n * its column NOT NULL, and a declared property that owns a relation's column\n * decides that column's nullability itself. Defaulting before either produced\n * `NOT NULL … ON DELETE SET NULL` — a parent's delete that can only fail, and\n * fails with 23502 naming the child's column rather than as the foreign-key\n * refusal it is. An `onDelete` the author wrote is theirs and is kept.\n */\nfunction settleDefaultOnDelete(\n collection: CollectionConfig,\n columns: ColumnPlan[],\n relations: Record<string, ResolvedRelation>\n): void {\n for (const column of columns) {\n const fk = column.foreignKey;\n if (!fk || declaresOnDelete(collection, relations, column)) continue;\n const created = columns.find(c => c.column === column.column && !c.columnOwnedByProperty) ?? column;\n const onDelete = defaultBelongsToOnDelete(!created.nullable);\n if (onDelete === fk.onDelete) continue;\n column.foreignKey = foreignKeyPlan({\n schema: fk.schema,\n table: fk.table,\n column: fk.column,\n targetSchema: fk.targetSchema,\n targetTable: fk.targetTable,\n targetColumn: fk.targetColumn,\n onDelete,\n onUpdate: fk.onUpdate\n });\n }\n}\n\n/** Whether the author wrote this link's `onDelete`. A `reference` has none to write. */\nconst declaresOnDelete = (\n collection: CollectionConfig,\n relations: Record<string, ResolvedRelation>,\n column: ColumnPlan\n): boolean => {\n const propName = column.source.propName;\n if (column.source.kind !== \"relation\" || !propName) return false;\n const prop = collection.properties?.[propName] as RelationProperty | undefined;\n const relation = findRelation(relations, prop?.relation?.relationName ?? propName);\n return relation?.kind === \"belongsTo\" && relation.onDelete !== undefined;\n};\n\n/**\n * The column a `belongsTo` relation owns, or `undefined` when the relation puts\n * no column on this table.\n *\n * Every other kind is a column on the target, a junction row, or a join chain.\n */\nfunction planRelationColumn(\n propName: string,\n prop: RelationProperty,\n collection: CollectionConfig,\n relations: Record<string, ResolvedRelation>,\n schema: string,\n table: string\n): ColumnPlan | undefined {\n const relation = findRelation(relations, prop.relation?.relationName ?? propName);\n if (relation?.kind !== \"belongsTo\") return undefined;\n\n let target: CollectionConfig;\n try {\n target = relation.target();\n } catch {\n // A relation whose target is not in this bundle yields no column and no\n // constraint. Every emitter returned early here, and they must keep\n // agreeing: a column with no constraint down one path is a schema fork.\n return undefined;\n }\n if (!target) return undefined;\n\n const required = prop.validation?.required === true;\n // The relation and an explicit FK property can both be declared; the\n // explicit one owns the column, and the relation still owns the constraint.\n // Asked of the *field key* rather than the column — `properties[\"post_id\"]`\n // is not where a property declared `postId: { columnName: \"post_id\" }`\n // lives, so this used to emit the column twice and `CREATE TABLE` failed\n // with \"column specified more than once\".\n const fkFieldKey = fieldKeyForColumn(collection, relation.localKey);\n const columnOwnedByProperty = Boolean(collection.properties?.[fkFieldKey]) && propName !== fkFieldKey;\n\n // Only a *derived* column name can be affected by the change to\n // `generateForeignKeyName`; one the author wrote is theirs.\n const relationName = prop.relation?.relationName ?? propName;\n const legacyKey = legacyForeignKeyName(relationName);\n const derived = relation.localKey === generateForeignKeyName(relationName);\n const via = linkLabel(\"relation\", collection, propName);\n\n return {\n key: fkFieldKey,\n column: relation.localKey,\n type: primaryKeyPgType(target, via),\n nullable: !required,\n primaryKey: false,\n // `validation.unique` on a link is a one-to-one, and all three emitters\n // dropped it: the property said unique, the column was not, and a\n // second row could point at the same parent.\n unique: prop.validation?.unique === true,\n columnOwnedByProperty: columnOwnedByProperty || undefined,\n legacyColumn: derived && legacyKey !== relation.localKey ? legacyKey : undefined,\n foreignKey: servesView(target) ? undefined : foreignKeyPlan({\n schema,\n table,\n column: relation.localKey,\n targetSchema: schemaOf(target),\n targetTable: bareTableName(getTableName(target)),\n targetColumn: getPrimaryKeyColumn(target, via),\n onDelete: relation.onDelete ?? defaultBelongsToOnDelete(required),\n onUpdate: relation.onUpdate\n }),\n source: { kind: \"relation\", propName, slug: collection.slug }\n };\n}\n\n/** The column a `reference` property owns — a foreign key like any other. */\nfunction planReferenceColumn(\n propName: string,\n prop: ReferenceProperty,\n collection: CollectionConfig,\n resolveCollection: ResolveCollection,\n schema: string,\n table: string\n): ColumnPlan {\n // A `reference` with no `path` names no collection, so it keeps its column\n // (the id is still a string) and gets no constraint — the same shape as one\n // whose target is not in this bundle.\n const target = prop.path ? resolveCollection(prop.path) : undefined;\n const column = resolveColumnName(propName, prop as Property);\n const required = prop.validation?.required === true;\n const via = linkLabel(\"reference\", collection, propName);\n\n return {\n key: propName,\n column,\n // A `reference` whose target is not in the bundle keeps its column (the\n // id is still a string) and gets no constraint.\n type: target ? primaryKeyPgType(target, via) : { kind: \"text\" },\n nullable: !required,\n primaryKey: false,\n unique: prop.validation?.unique === true,\n foreignKey: target && !servesView(target)\n ? foreignKeyPlan({\n schema,\n table,\n column,\n targetSchema: schemaOf(target),\n targetTable: bareTableName(getTableName(target)),\n targetColumn: getPrimaryKeyColumn(target, via),\n // The same rule as `belongsTo`, from the same function. A\n // `reference` carries no `onDelete` of its own to override it.\n onDelete: defaultBelongsToOnDelete(required)\n })\n : undefined,\n source: { kind: \"reference\", propName, slug: collection.slug }\n };\n}\n\n/**\n * An auth-owned column's declared SQL type, as a tag.\n *\n * `auth-users-columns` states these as SQL because that is the grammar its three\n * creators write in; the plan needs the tag so nothing downstream has to parse a\n * type back apart. Deliberately exhaustive rather than a fallback: a column auth\n * adds with a type nobody mapped should say so here, not turn into `TEXT` in a\n * table the login flow reads.\n */\nconst AUTH_COLUMN_TYPES: Record<string, PgType> = {\n \"TEXT\": { kind: \"text\" },\n \"TEXT[]\": { kind: \"array\", of: { kind: \"text\" } },\n \"BOOLEAN\": { kind: \"boolean\" },\n \"JSONB\": { kind: \"jsonb\" },\n \"TIMESTAMP WITH TIME ZONE\": { kind: \"timestamptz\" }\n};\n\nconst authColumnType = (sqlType: string): PgType => {\n const mapped = AUTH_COLUMN_TYPES[sqlType];\n if (!mapped) {\n throw new Error(\n `\\`auth-users-columns\\` declares a column of type \"${sqlType}\", which the schema plan ` +\n \"has no tag for. Add it to `AUTH_COLUMN_TYPES` in schema/plan/plan-schema.ts.\"\n );\n }\n return mapped;\n};\n\n// ── A junction table ─────────────────────────────────────────────────────────\n\n/**\n * Which declaring side a junction is planned from.\n *\n * With one side, that side — as it always was, so a junction only one end\n * declares keeps the key every database already has. With both ends declaring\n * it, the planner used to take whichever it reached first, and the two doors\n * reach them in different orders: `db push` loads files by name, boot walks the\n * bundle's array. The same junction was keyed `(a_id, b_id)` by one and\n * `(b_id, a_id)` by the other, and a push against a boot-built database rebuilt\n * the key. Now the side whose table sorts first, which is the order `db push`\n * already used wherever a file is named after its table.\n */\nfunction canonicalJunctionSide(\n table: string,\n relation: ResolvedRelation,\n source: CollectionConfig,\n spec: JunctionSpec | undefined\n): { relation: ResolvedRelation; source: CollectionConfig } {\n if (!spec || spec.declaringSides.length < 2) return { relation, source };\n const ordered = [...spec.declaringSides].sort((a, b) => {\n const left = bareTableName(getTableName(a.collection));\n const right = bareTableName(getTableName(b.collection));\n if (left !== right) return left < right ? -1 : 1;\n return a.junctionColumn < b.junctionColumn ? -1 : a.junctionColumn > b.junctionColumn ? 1 : 0;\n });\n const chosen = ordered[0].collection;\n if (chosen === source) return { relation, source };\n const resolved = Object.values(resolveCollectionRelations(chosen))\n .find(r => isManyToMany(r) && bareTableName(r.through.table) === table);\n return resolved ? { relation: resolved, source: chosen } : { relation, source };\n}\n\nfunction planJunctionTable(\n tableName: string,\n reachedRelation: ResolvedRelation,\n reachedSource: CollectionConfig,\n junctionSpecs: ReturnType<typeof resolveJunctionSpecs>,\n resolveCollection: ResolveCollection,\n triggerFunctionNeeded: { value: boolean }\n): TablePlan {\n const { relation, source } = canonicalJunctionSide(\n bareTableName(tableName), reachedRelation, reachedSource, junctionSpecs.get(bareTableName(tableName)));\n if (!isManyToMany(relation)) {\n throw new Error(`Internal: junction table \"${tableName}\" was reached from a ${relation.kind} relation.`);\n }\n const table = bareTableName(tableName);\n // Junctions live in `public`, full stop — `resolveJunctionSpecs` hardcodes\n // that, so it is where the tables are created and where the derived RLS\n // policies are applied. Inheriting the endpoint's schema put the junction\n // of any m2m onto `users` in `rebase` while its policies were still created\n // against `public.<junction>`: RLS enabled on one table, rows in another.\n const schema = \"public\";\n const target = relation.target();\n const { sourceColumn, targetColumn } = relation.through;\n // Every declaring side agrees on the edge's lifetime; the first one wins.\n const onDelete = relation.onDelete ?? \"CASCADE\";\n\n const spec = junctionSpecs.get(table);\n const legacyFor = (collection: CollectionConfig, column: string): string | undefined => {\n // A junction column's default name is derived from the endpoint\n // collection's slug — normally plural, so this is where the\n // singularization change lands: a `categories` endpoint used to give\n // `categorie_id` and now gives `category_id`. Recorded, not used.\n const slug = toSnakeCase(collection.slug ?? collection.name ?? \"\");\n const legacy = legacyForeignKeyName(slug);\n return column === generateForeignKeyName(slug) && legacy !== column ? legacy : undefined;\n };\n\n const via = linkLabel(\"relation\", source, relation.relationName);\n const endpoint = (collection: CollectionConfig, column: string): ColumnPlan => ({\n key: column,\n column,\n type: primaryKeyPgType(collection, via),\n nullable: false,\n // Part of the composite key on {@link TablePlan.primaryKey}, not a\n // key of its own — an inline `PRIMARY KEY` here would be a second one.\n primaryKey: false,\n unique: false,\n legacyColumn: legacyFor(collection, column),\n foreignKey: servesView(collection) ? undefined : foreignKeyPlan({\n schema,\n table,\n column,\n targetSchema: schemaOf(collection),\n targetTable: bareTableName(getTableName(collection)),\n targetColumn: getPrimaryKeyColumn(collection, via),\n onDelete\n }),\n source: { kind: \"junction-key\" }\n });\n\n const columns = [endpoint(source, sourceColumn), endpoint(target, targetColumn)];\n\n // ── The junction's own columns ───────────────────────────────────────────\n // `through.properties`: the `role` on a membership, the `position` on a\n // tag. Planned by the same {@link planPropertyColumn} the collection tables\n // use, against the synthetic collection {@link getJunctionCollectionConfig}\n // builds — so a payload property gets exactly the type, nullability,\n // default, UNIQUE and enum type it would get on a table, and there is no\n // second `switch (prop.type)` anywhere to disagree with the first.\n //\n // Not supported here, and deliberately: `indexes` (declared per collection,\n // and no collection declares a junction), `search`, `vector`, and any\n // linking property — a payload cannot be a `relation`, a `reference` or a\n // `vector`. Config validation refuses those with the relation named; this\n // would otherwise reach `columnPgType` and produce a column no writer knows\n // how to fill.\n const triggers: TriggerPlan[] = [];\n if (spec && Object.keys(spec.properties).length > 0) {\n const junctionCollection = getJunctionCollectionConfig(spec);\n const keyColumns = new Set([sourceColumn, targetColumn]);\n for (const [propName, rawProp] of Object.entries(spec.properties)) {\n const prop = rawProp as Property;\n const plan = planPropertyColumn(propName, prop, {\n collection: junctionCollection,\n resolveCollection,\n schema,\n table,\n auth: false,\n triggers,\n triggerFunctionNeeded\n });\n // A payload column that resolves onto a key column would be a\n // second definition of it — refused by `checkJunctionPayload` at\n // boot, and skipped here so a config that got past it still\n // produces a table rather than a duplicate-column CREATE.\n if (keyColumns.has(plan.column)) continue;\n columns.push(plan);\n }\n }\n\n // Junction tables are generated tables like any other: locked by default,\n // with derived policies — reads follow the endpoints' visibility, writes\n // follow the declaring side's update rules. Without them they were the one\n // kind of generated table with no RLS at all.\n const policies = spec\n ? withoutLiveSupersededNames(getJunctionSecurityRules(spec).flatMap((rule, index) =>\n compileSecurityRule(\n getJunctionCollectionConfig(spec), rule, resolveCollection, false, rule.name ?? `#${index}`)))\n : [];\n\n return {\n schema,\n table,\n qualified: `${schema}.${table}`,\n varName: getTableVarName(tableName),\n kind: \"junction\",\n declaringSlugs: spec?.declaringSides.map(side => side.collection.slug) ?? [],\n columns,\n primaryKey: [sourceColumn, targetColumn],\n // Always, and with no opt-out: the junction is the platform's table,\n // not the author's. The key covers lookups by `sourceColumn`; the\n // reverse side of the link — `tags → posts` — filters on\n // `targetColumn`, which only this index serves.\n indexes: planForeignKeyIndexes(schema, table, columns, [sourceColumn, targetColumn], [],\n column => column.source.kind === \"junction-key\"),\n vectorColumns: [],\n policies,\n triggers,\n auth: false\n };\n}\n\n// ── Drizzle relations ────────────────────────────────────────────────────────\n\n/**\n * The `relations(...)` entries the generated file carries.\n *\n * Both sides of a link must share a `relationName` or Drizzle cannot pair them;\n * `sharedRelationName` is the rule, and each side derives it independently.\n */\nfunction planRelations(\n collections: CollectionConfig[],\n tableEntries: Map<string, { collection: CollectionConfig; junction?: { relation: ResolvedRelation; source: CollectionConfig } }>\n): RelationPlan[] {\n const plans: RelationPlan[] = [];\n\n // Every relation whose foreign key lives on its target's table, grouped by\n // that target's slug, in the order the scan below used to meet them —\n // collections in declaration order, each one's relations in order. Built\n // once: the scan ran once per collection over every other collection's\n // relations, N² in the collection count (24 ms at 200, 204 ms at 1,000).\n const fkOnTargetBySlug = new Map<string, Array<{ other: CollectionConfig; otherRel: ResolvedForeignKeyOnTarget }>>();\n for (const other of collections) {\n for (const otherRel of Object.values(resolveCollectionRelations(other))) {\n if (!hasForeignKeyOnTarget(otherRel)) continue;\n let otherTarget: CollectionConfig;\n try {\n otherTarget = otherRel.target();\n } catch {\n continue;\n }\n const list = fkOnTargetBySlug.get(otherTarget.slug) ?? [];\n list.push({ other, otherRel });\n fkOnTargetBySlug.set(otherTarget.slug, list);\n }\n }\n\n for (const [tableName, entry] of tableEntries) {\n const tableVar = getTableVarName(tableName);\n\n if (entry.junction) {\n const { relation, source } = entry.junction;\n if (!isManyToMany(relation)) continue;\n const target = relation.target();\n const via = linkLabel(\"relation\", source, relation.relationName);\n // Each `one()` here pairs with a `many(junction, { relationName })`\n // on its endpoint, so each takes the name that endpoint's own\n // relation derives — the rule `addJunctionSides` in\n // `config-relations.ts` builds the runtime's relations by.\n //\n // The far side is looked up as the target's many-to-many through\n // this same junction. It used to be matched on the *owning* side's\n // name, which `tags.posts` never carries, so the synthesized name\n // won and `tags`' `many(…, { relationName: \"posts\" })` had nothing\n // to pair with: `with: { posts: true }` threw. Only a junction\n // nothing points back through needs the synthesized name.\n const owningRelationName = sharedRelationName(relation, source);\n let inverse: ResolvedRelation | undefined;\n try {\n inverse = Object.values(resolveCollectionRelations(target)).find(r =>\n r.kind === \"manyToMany\" && bareTableName(r.through.table) === bareTableName(tableName));\n } catch {\n // A target whose relations cannot be resolved declares no inverse.\n }\n const inverseRelationName = inverse\n ? sharedRelationName(inverse, target)\n : `${tableName}_${relation.through.targetColumn}`;\n plans.push({\n tableVar,\n key: relation.through.sourceColumn,\n kind: \"one\",\n targetVar: getTableVarName(getTableName(source)),\n relationName: owningRelationName,\n fields: [relation.through.sourceColumn],\n references: [getPrimaryKeyName(source, via)]\n });\n // A self-referencing link is its own inverse: one name, one\n // endpoint table, and drizzle refuses two relations named alike.\n if (inverseRelationName === owningRelationName) continue;\n // The file declares no variable for a view to pair with.\n if (servesView(target)) continue;\n plans.push({\n tableVar,\n key: relation.through.targetColumn,\n kind: \"one\",\n targetVar: getTableVarName(getTableName(target)),\n relationName: inverseRelationName,\n fields: [relation.through.targetColumn],\n references: [getPrimaryKeyName(target, via)]\n });\n continue;\n }\n\n const collection = entry.collection;\n // `resolveCollectionRelations` already deduplicates, but an alias entry\n // for the same foreign key would otherwise emit twice.\n const emitted = new Set<string>();\n for (const [key, relation] of Object.entries(resolveCollectionRelations(collection))) {\n let target: CollectionConfig;\n try {\n target = relation.target();\n } catch {\n // A link to a collection outside this bundle is not a relation\n // this file can describe.\n continue;\n }\n // Nor is a link into a view, which the file declares no table for.\n if (servesView(target)) continue;\n const targetVar = getTableVarName(getTableName(target));\n const relationName = sharedRelationName(relation, collection);\n const dedupe = `${relationName}::${relation.kind}`;\n if (emitted.has(dedupe)) continue;\n emitted.add(dedupe);\n\n switch (relation.kind) {\n case \"belongsTo\":\n plans.push({\n tableVar,\n key,\n kind: \"one\",\n targetVar,\n relationName,\n // `localKey` is a COLUMN and the generated object is\n // keyed by PROPERTY: `user_id` is exposed as `userId`,\n // and emitting the column produces a file that does not\n // compile.\n fields: [fieldKeyForColumn(collection, relation.localKey)],\n references: [getPrimaryKeyName(target, linkLabel(\"relation\", collection, key))]\n });\n break;\n case \"hasOne\":\n // The foreign key lives on the TARGET table, so this side\n // states the join from its own end: its source key against\n // the target's foreign key, under the owning side's name.\n // Drizzle has no `one()` paired by `relationName` alone:\n // `one(target, { relationName })` is not a `RelationConfig`\n // (TS2345) and `createOne` reads `config.fields.reduce(...)`.\n // A bare `one(target)` is paired by table, which throws once\n // the target has two links back here or the link is to its\n // own table.\n plans.push({\n tableVar,\n key,\n kind: \"one\",\n targetVar,\n relationName,\n fields: [relation.sourceKey\n ? fieldKeyForColumn(collection, relation.sourceKey)\n : getPrimaryKeyName(collection, linkLabel(\"relation\", collection, key))],\n references: [fieldKeyForColumn(target, relation.foreignKeyOnTarget)],\n nullable: true\n });\n break;\n case \"hasMany\":\n plans.push({ tableVar, key, kind: \"many\", targetVar, relationName });\n break;\n case \"manyToMany\":\n plans.push({\n tableVar,\n key,\n kind: \"many\",\n targetVar: getTableVarName(relation.through.table),\n relationName\n });\n break;\n case \"via\":\n // A join chain is resolved at query time, not modelled as a\n // Drizzle relation.\n break;\n }\n }\n\n // Reciprocals the far side declares and this one does not. Drizzle\n // needs both halves of a pair to exist for a relational query to work.\n for (const { other, otherRel } of fkOnTargetBySlug.get(collection.slug) ?? []) {\n if (other.slug === collection.slug) continue;\n const relationName = sharedRelationName(otherRel, other);\n const dedupe = `${relationName}::belongsTo`;\n if (emitted.has(dedupe)) continue;\n emitted.add(dedupe);\n const otherVar = getTableVarName(getTableName(other));\n const fieldKey = fieldKeyForColumn(collection, otherRel.foreignKeyOnTarget);\n plans.push({\n tableVar,\n key: `_synth_${otherVar}_${fieldKey}`,\n kind: \"one\",\n targetVar: otherVar,\n relationName,\n fields: [fieldKey],\n // The column the far side points at: its primary key,\n // unless the link names another one with `sourceKey`.\n references: [otherRel.sourceKey\n ? fieldKeyForColumn(other, otherRel.sourceKey)\n : getPrimaryKeyName(other, linkLabel(\"relation\", other, otherRel.relationName))]\n });\n }\n }\n\n return plans;\n}\n\nexport { SET_UPDATED_AT_FN };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,mBACZ,UACA,kBACM;CACN,MAAM,iBAAyB;EAC3B,IAAI,SAAS,cAAc,OAAO,SAAS;EAC3C,IAAI;GACA,OAAO,YAAY,SAAS,OAAO,CAAC,CAAC,IAAI;EAC7C,QAAQ;GACJ,OAAO,SAAS;EACpB;CACJ;CAEA,IAAI,SAAS,SAAS,aAClB,OAAO,GAAG,aAAa,gBAAgB,EAAE,GAAG,kBAAkB,kBAAkB,SAAS,QAAQ;CAGrG,IAAI,SAAS,SAAS,aAAa,SAAS,SAAS,UACjD,IAAI;EACA,MAAM,SAAS,SAAS,OAAO;EAC/B,OAAO,GAAG,aAAa,MAAM,EAAE,GAAG,kBAAkB,QAAQ,SAAS,kBAAkB;CAC3F,QAAQ;EACJ,OAAO,SAAS;CACpB;CAGJ,OAAO,SAAS;AACpB;;;;;;;;;;;;;;;;;;;;;;;;;;;AC9BA,IAAa,iBAAiB,GAAG,cAAc;;AAG/C,IAAa,yBAAyB,UAA0B,GAAG,MAAM;AAEzE,IAAa,2BACT,8BAA8B,eAAe;;;;;;;;;;;;;;;AAoBjD,IAAa,uBAAuB,SAAgC,CAAC,KAAK,QAAQ,GAAI,KAAK,eAAe,CAAC,CAAE;AAE7G,IAAM,WAAW,UAA0B,IAAI,MAAM,QAAQ,MAAM,IAAI,EAAE;AAEzE,IAAa,6BAA6B,SACtC,mBAAmB,KAAK,KAAK,sBAAsB,KAAK,OAAO,KAAK,KAAK,MAAM,kCAC9C,eAAe,GAAG,oBAAoB,IAAI,CAAC,CAAC,IAAI,OAAO,CAAC,CAAC,KAAK,IAAI,EAAE;;;;;;;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