@rebasepro/server-postgres 0.29.0 → 0.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/{BranchService-JiYJ_n9E.js → BranchService-BIIBF5ZL.js} +3 -3
  2. package/dist/{BranchService-JiYJ_n9E.js.map → BranchService-BIIBF5ZL.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +27 -9
  4. package/dist/PostgresBootstrapper.d.ts +14 -0
  5. package/dist/{backup-cli-D_aKXPyX.js → backup-cli-QcOpmRpQ.js} +3 -3
  6. package/dist/{backup-cli-D_aKXPyX.js.map → backup-cli-QcOpmRpQ.js.map} +1 -1
  7. package/dist/{boot-ddl-D4W9o9xE.js → boot-ddl-BSNpEUOS.js} +2 -2
  8. package/dist/{boot-ddl-D4W9o9xE.js.map → boot-ddl-BSNpEUOS.js.map} +1 -1
  9. package/dist/{cli-console-DPdZCWTi.js → cli-console-DTsm96lW.js} +5 -5
  10. package/dist/{cli-console-DPdZCWTi.js.map → cli-console-DTsm96lW.js.map} +1 -1
  11. package/dist/{cli-errors-D8s4z_3g.js → cli-errors-DwqFRIWz.js} +49 -6
  12. package/dist/{cli-errors-D8s4z_3g.js.map → cli-errors-DwqFRIWz.js.map} +1 -1
  13. package/dist/cli.js +81 -41
  14. package/dist/cli.js.map +1 -1
  15. package/dist/database-preflight-D5JtPt8i.js +151 -0
  16. package/dist/database-preflight-D5JtPt8i.js.map +1 -0
  17. package/dist/db-subcommands.d.ts +1 -1
  18. package/dist/{deferred-index-build-F2GWu009.js → deferred-index-build-B8feKnUj.js} +12 -8
  19. package/dist/deferred-index-build-B8feKnUj.js.map +1 -0
  20. package/dist/{doctor-_g2tHRtG.js → doctor-BaR11xUe.js} +6 -6
  21. package/dist/{doctor-_g2tHRtG.js.map → doctor-BaR11xUe.js.map} +1 -1
  22. package/dist/{ensure-collection-policies-DUpWJb5D.js → ensure-collection-policies-85HiG-k1.js} +8 -8
  23. package/dist/{ensure-collection-policies-DUpWJb5D.js.map → ensure-collection-policies-85HiG-k1.js.map} +1 -1
  24. package/dist/{ensure-collection-tables-BK--gDo6.js → ensure-collection-tables-DR_WcxLA.js} +15 -10
  25. package/dist/ensure-collection-tables-DR_WcxLA.js.map +1 -0
  26. package/dist/{ensure-tables-Bx1DYarz.js → ensure-tables-Dh5UP_Zs.js} +4 -4
  27. package/dist/{ensure-tables-Bx1DYarz.js.map → ensure-tables-Dh5UP_Zs.js.map} +1 -1
  28. package/dist/{enum-labels-kept-DyFE4Gaq.js → enum-labels-kept-DSU8lAnd.js} +3 -3
  29. package/dist/{enum-labels-kept-DyFE4Gaq.js.map → enum-labels-kept-DSU8lAnd.js.map} +1 -1
  30. package/dist/{generate-drizzle-schema-taNTu3xv.js → generate-drizzle-schema-5spbTyQ6.js} +2 -2
  31. package/dist/{generate-drizzle-schema-taNTu3xv.js.map → generate-drizzle-schema-5spbTyQ6.js.map} +1 -1
  32. package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js → generate-drizzle-schema-logic-C5FB7Fpo.js} +2 -2
  33. package/dist/{generate-drizzle-schema-logic-DpFA1UVd.js.map → generate-drizzle-schema-logic-C5FB7Fpo.js.map} +1 -1
  34. package/dist/{generate-files-DbwU8Btx.js → generate-files-Bl3_D_oP.js} +3 -3
  35. package/dist/{generate-files-DbwU8Btx.js.map → generate-files-Bl3_D_oP.js.map} +1 -1
  36. package/dist/{generate-postgres-ddl-logic-ISVgsP34.js → generate-postgres-ddl-logic-BC3JA93M.js} +3 -3
  37. package/dist/{generate-postgres-ddl-logic-ISVgsP34.js.map → generate-postgres-ddl-logic-BC3JA93M.js.map} +1 -1
  38. package/dist/{generated-schema-diff-4lOC0g1_.js → generated-schema-diff-Jm93vyJB.js} +12 -4
  39. package/dist/generated-schema-diff-Jm93vyJB.js.map +1 -0
  40. package/dist/index.d.ts +2 -1
  41. package/dist/index.es.js +20 -12
  42. package/dist/index.es.js.map +1 -1
  43. package/dist/{migrate-baseline-BeepEphh.js → migrate-baseline-BfHmq3vN.js} +49 -4
  44. package/dist/{migrate-baseline-BeepEphh.js.map → migrate-baseline-BfHmq3vN.js.map} +1 -1
  45. package/dist/{migrate-policy-stamps-cYMJ_9Ha.js → migrate-policy-stamps-B4k1ggma.js} +6 -6
  46. package/dist/{migrate-policy-stamps-cYMJ_9Ha.js.map → migrate-policy-stamps-B4k1ggma.js.map} +1 -1
  47. package/dist/{open-rebase-CTNBmmH8.js → open-rebase-CiO_sjMT.js} +465 -80
  48. package/dist/open-rebase-CiO_sjMT.js.map +1 -0
  49. package/dist/open-rebase.d.ts +6 -1
  50. package/dist/{pg-error-utils-BLOVXK67.js → pg-error-utils-D1Nc0UML.js} +2 -2
  51. package/dist/{pg-error-utils-BLOVXK67.js.map → pg-error-utils-D1Nc0UML.js.map} +1 -1
  52. package/dist/{plan-schema-CMNWvqIa.js → plan-schema-BYxOzflz.js} +89 -9
  53. package/dist/plan-schema-BYxOzflz.js.map +1 -0
  54. package/dist/{policy-drift-IjD2AUD-.js → policy-drift-DKuTJHfc.js} +2 -2
  55. package/dist/{policy-drift-IjD2AUD-.js.map → policy-drift-DKuTJHfc.js.map} +1 -1
  56. package/dist/{push-index-prebuild-CIvajIrL.js → push-index-prebuild-bqXimSZz.js} +4 -4
  57. package/dist/{push-index-prebuild-CIvajIrL.js.map → push-index-prebuild-bqXimSZz.js.map} +1 -1
  58. package/dist/{push-kept-defaults-CLbsuSmo.js → push-kept-defaults-CN9R8cHf.js} +2 -2
  59. package/dist/{push-kept-defaults-CLbsuSmo.js.map → push-kept-defaults-CN9R8cHf.js.map} +1 -1
  60. package/dist/{push-legacy-renames-DeW_HTLJ.js → push-legacy-renames-CU_UYPbz.js} +4 -4
  61. package/dist/{push-legacy-renames-DeW_HTLJ.js.map → push-legacy-renames-CU_UYPbz.js.map} +1 -1
  62. package/dist/{push-policy-plan--oRXOj4X.js → push-policy-plan-JcyK94bc.js} +4 -4
  63. package/dist/{push-policy-plan--oRXOj4X.js.map → push-policy-plan-JcyK94bc.js.map} +1 -1
  64. package/dist/{render-ddl-CzVcbbR1.js → render-ddl-DCdVP-pQ.js} +27 -10
  65. package/dist/render-ddl-DCdVP-pQ.js.map +1 -0
  66. package/dist/request-role-cli-DSdRtvgH.js +260 -0
  67. package/dist/request-role-cli-DSdRtvgH.js.map +1 -0
  68. package/dist/request-role-cli.d.ts +86 -0
  69. package/dist/request-role-migration-D9BZ5Uba.js +150 -0
  70. package/dist/request-role-migration-D9BZ5Uba.js.map +1 -0
  71. package/dist/rls-enforcement-BO618rnr.js +992 -0
  72. package/dist/rls-enforcement-BO618rnr.js.map +1 -0
  73. package/dist/rls-settings-De5NoHHy.js +211 -0
  74. package/dist/rls-settings-De5NoHHy.js.map +1 -0
  75. package/dist/schema/doctor-cli.js +144 -6
  76. package/dist/schema/doctor-cli.js.map +1 -1
  77. package/dist/schema/doctor-database.d.ts +27 -0
  78. package/dist/schema/generate-drizzle-schema.js +1 -1
  79. package/dist/schema/generate-postgres-ddl.js +1 -1
  80. package/dist/schema/introspect-db.js +1 -1
  81. package/dist/schema/plan/diff-plan.d.ts +6 -1
  82. package/dist/schema/plan/render-ddl.d.ts +10 -3
  83. package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
  84. package/dist/schema/plan/types.d.ts +15 -0
  85. package/dist/schema/plan/updated-at-trigger.d.ts +1 -1
  86. package/dist/schema/plan/view-names.d.ts +6 -0
  87. package/dist/schema/rls-bootstrap-sql.d.ts +23 -0
  88. package/dist/security/caller-sql-columns.d.ts +60 -0
  89. package/dist/security/caller-sql.d.ts +8 -0
  90. package/dist/security/database-preflight.d.ts +24 -0
  91. package/dist/security/request-role-migration.d.ts +36 -0
  92. package/dist/security/rls-enforcement.d.ts +191 -21
  93. package/dist/security/rls-settings.d.ts +177 -0
  94. package/dist/services/dataService.d.ts +2 -0
  95. package/dist/services/realtimeService.d.ts +3 -0
  96. package/dist/services/view-access.d.ts +2 -2
  97. package/dist/view-names-Dscp6--B.js +24 -0
  98. package/dist/view-names-Dscp6--B.js.map +1 -0
  99. package/dist/{websocket-D2y88dOa.js → websocket-B33YjKhs.js} +3 -3
  100. package/dist/{websocket-D2y88dOa.js.map → websocket-B33YjKhs.js.map} +1 -1
  101. package/package.json +7 -7
  102. package/dist/deferred-index-build-F2GWu009.js.map +0 -1
  103. package/dist/ensure-collection-tables-BK--gDo6.js.map +0 -1
  104. package/dist/generated-schema-diff-4lOC0g1_.js.map +0 -1
  105. package/dist/open-rebase-CTNBmmH8.js.map +0 -1
  106. package/dist/plan-schema-CMNWvqIa.js.map +0 -1
  107. package/dist/render-ddl-CzVcbbR1.js.map +0 -1
  108. package/dist/rls-enforcement-jZTv1yci.js +0 -534
  109. package/dist/rls-enforcement-jZTv1yci.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rebasepro/server-postgres",
3
- "version": "0.29.0",
3
+ "version": "0.29.1",
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/common": "0.29.0",
54
- "@rebasepro/codegen": "0.29.0",
55
- "@rebasepro/server": "0.29.0",
56
- "@rebasepro/utils": "0.29.0",
57
- "@rebasepro/types": "0.29.0"
53
+ "@rebasepro/common": "0.29.1",
54
+ "@rebasepro/server": "0.29.1",
55
+ "@rebasepro/codegen": "0.29.1",
56
+ "@rebasepro/types": "0.29.1",
57
+ "@rebasepro/utils": "0.29.1"
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.0"
73
+ "@rebasepro/client": "0.29.1"
74
74
  },
75
75
  "gitHead": "d935eefa5aa8d1009a2398cfac2c1e4ee9aeb6b6",
76
76
  "publishConfig": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"deferred-index-build-F2GWu009.js","names":[],"sources":["../src/schema/column-type-drift.ts","../src/schema/plan/diff-plan.ts","../src/schema/deferred-index-build.ts"],"sourcesContent":["/**\n * A column whose type in the database is not the type the collection declares.\n *\n * The boot ensure is additive: it creates tables, columns, enum values and\n * indexes, and it never changes an existing column's type. That is the right\n * default — an automatic `ALTER COLUMN … TYPE` against customer data, decided\n * by a process nobody is watching, is not a thing to do quietly.\n *\n * What was wrong is that it happened *silently*. A property's `columnType`\n * changed after the first deploy, the deploy reported success, the column stayed\n * as it was, and the divergence surfaced later as writes failing:\n *\n * Invalid data format in \"listing_observations\":\n * malformed array literal: \"[0,0,0.0755,…]\"\n *\n * ...after a 10,690-row import, from a deployment that had said \"success\". The\n * two ends disagreed about the schema, so no value satisfied both: the declared\n * shape was rejected by Postgres and the Postgres shape was rejected by the\n * API's own validator, first. There is no encoding out of that, only a report.\n *\n * ## Why the comparison is deliberately blunt\n *\n * A drift report that cries wolf is worse than none, because the boot that says\n * it every time is the boot nobody reads. So types are compared by *family*, and\n * a family is only split from another when the difference changes what the\n * column can hold:\n *\n * - every numeric type is one family. `int4`, `numeric` and `float8` all arrive\n * as JavaScript numbers and accept each other's values; a database adopted\n * from an existing schema legitimately has `int4` where `type: \"number\"`\n * generates `NUMERIC`, and that is not news.\n * - every character type is one family, for the same reason: `text`,\n * `varchar(255)` and `char(3)` differ in what they *reject*, not in shape.\n * - `jsonb` and an array are different families, and that is the case this\n * exists for.\n *\n * Anything this module does not recognise — an enum type, a domain, a PostGIS\n * geometry, an extension type it has never met — returns `null` and is compared\n * with nothing. Silence on an unknown type is the deliberate choice: the cost of\n * a missed report is a question somebody asks once, and the cost of a false one\n * is a warning everybody learns to skip.\n */\n\n/** A column whose live type and declared type are in different families. */\nexport interface ColumnTypeDrift {\n /** `schema.table`. */\n table: string;\n /** The column name as it exists in the database. */\n column: string;\n /** What the collection says the column should be, e.g. `JSONB`. */\n declared: string;\n /** What the database actually has, as `udt_name` reports it, e.g. `_numeric`. */\n actual: string;\n}\n\n/**\n * Types that mean the same thing to everything above the driver.\n *\n * Keyed by every spelling either side can produce: `information_schema` reports\n * `udt_name` (`int4`, `_numeric`, `bpchar`), while the generators emit SQL\n * (`INTEGER`, `NUMERIC[]`, `CHAR(3)`). Both are normalised through here.\n */\nconst FAMILIES: Record<string, string> = {\n // Numbers. One family on purpose — see the note above.\n int2: \"number\", smallint: \"number\",\n int4: \"number\", int: \"number\", integer: \"number\",\n int8: \"number\", bigint: \"number\",\n numeric: \"number\", decimal: \"number\",\n float4: \"number\", real: \"number\",\n float8: \"number\", \"double precision\": \"number\",\n money: \"number\",\n\n // Characters. Also one family: the differences are limits, not shapes.\n text: \"text\", varchar: \"text\", \"character varying\": \"text\",\n bpchar: \"text\", char: \"text\", character: \"text\", citext: \"text\",\n\n bool: \"boolean\", boolean: \"boolean\",\n\n json: \"json\",\n jsonb: \"jsonb\",\n\n uuid: \"uuid\",\n bytea: \"bytea\",\n\n date: \"date\",\n time: \"time\", \"time without time zone\": \"time\",\n timetz: \"time\", \"time with time zone\": \"time\",\n timestamp: \"timestamp\", \"timestamp without time zone\": \"timestamp\",\n timestamptz: \"timestamptz\", \"timestamp with time zone\": \"timestamptz\",\n interval: \"interval\",\n\n tsvector: \"tsvector\",\n vector: \"vector\",\n halfvec: \"halfvec\",\n sparsevec: \"sparsevec\"\n};\n\n/**\n * One SQL or `udt_name` spelling reduced to its family, or `null` when this\n * module has no opinion about it.\n *\n * `null` is not a failure. It is the answer for an enum type, a domain, a\n * PostGIS column, a quoted qualified name — everything whose identity is a\n * *name* rather than a shape, where two spellings being different says nothing\n * about whether the values are compatible.\n */\nexport function typeFamily(raw: string | undefined | null): string | null {\n if (!raw) return null;\n let type = raw.trim().toLowerCase();\n if (!type) return null;\n\n // `\"public\".\"posts_status\"` — an enum, identified by name. Not comparable.\n if (type.startsWith(\"\\\"\")) return null;\n\n // `INTEGER GENERATED BY DEFAULT AS IDENTITY` is an `int4` with a default\n // attached; the identity clause is not part of the type.\n const generated = type.indexOf(\" generated \");\n if (generated > 0) type = type.slice(0, generated).trim();\n\n // Arrays, in both spellings: `NUMERIC[]` from the generators, `_numeric`\n // from `udt_name`. Compared element-wise, so `text[]` and `numeric[]` are\n // different and `int4[]` and `numeric[]` are not.\n if (type.endsWith(\"[]\")) {\n const element = typeFamily(type.slice(0, -2));\n return element && `array:${element}`;\n }\n if (type.startsWith(\"_\")) {\n const element = typeFamily(type.slice(1));\n return element && `array:${element}`;\n }\n\n // `VARCHAR(255)`, `VECTOR(384)`, `NUMERIC(10, 2)` — the width is a limit on\n // a family, not a family. A vector whose *dimensions* changed is a separate\n // concern with its own handling in the ensure.\n const paren = type.indexOf(\"(\");\n if (paren > 0) type = type.slice(0, paren).trim();\n\n return FAMILIES[type] ?? null;\n}\n\n/**\n * Do these two spellings describe columns that hold the same kind of value?\n *\n * `true` whenever the answer is not confidently \"no\" — an unrecognised type on\n * either side agrees with everything, because a report needs evidence and an\n * unknown type is the absence of it.\n */\nexport function typesAgree(declared: string, actual: string): boolean {\n const a = typeFamily(declared);\n const b = typeFamily(actual);\n if (a === null || b === null) return true;\n if (a !== b) return false;\n // Same family, and for `numeric` that is not the end of it: the modifier is\n // what makes `NUMERIC(10, 2)` a price and a bare `NUMERIC` a number that\n // keeps whatever the caller sent. A property that declares\n // `precision`/`scale` is asking the database to round, and a column without\n // them silently does not — so the two disagree, and the drift report says\n // so. A declaration with no modifier accepts whatever is there, which is\n // what it always did.\n //\n // Tested on the spelling, not the family: the family is `number` for every\n // numeric type, and an `int4` under a `NUMERIC(10, 2)` stays the adopted\n // schema it was.\n if (!isNumeric(declared) || !isNumeric(actual)) return true;\n const declaredModifier = numericModifier(declared);\n if (declaredModifier === null) return true;\n return declaredModifier === numericModifier(actual);\n}\n\n/** `NUMERIC`, `numeric(10,2)`, `DECIMAL(10, 2)` — the arbitrary-precision type itself. */\nfunction isNumeric(raw: string): boolean {\n return /^\\s*(?:numeric|decimal)\\s*(?:\\(|$)/i.test(raw);\n}\n\n/**\n * `numeric(10,2)` / `NUMERIC(10, 2)` → `10,2`; a bare `numeric` → `null`. A\n * precision alone means a scale of 0, which is how the catalogue reports it:\n * `NUMERIC(10)` → `10,0`.\n */\nfunction numericModifier(raw: string): string | null {\n const match = raw.match(/\\(([^)]*)\\)/);\n if (!match) return null;\n const [precision, scale = \"0\"] = match[1].split(\",\").map(part => part.trim());\n return `${precision},${scale}`;\n}\n\n/**\n * The sentence a boot log says about one drifted column.\n *\n * Written to be actionable in the place it is read, which is a runtime log with\n * no way to run a migration from it: it names both types, says which surface\n * will break first, and gives the statement that resolves it.\n */\nexport function columnTypeDriftMessage(drift: ColumnTypeDrift): string {\n const [schema, table] = drift.table.split(\".\");\n return (\n `Column \"${drift.table}\".\"${drift.column}\" is ${drift.actual} in the database, but this ` +\n `collection declares ${drift.declared}. Boot does not change an existing column's type, so ` +\n \"the database keeps what it has and writes that match the declaration will be rejected by \" +\n \"Postgres. Change it deliberately, when you can watch it:\\n\" +\n ` ALTER TABLE \"${schema}\".\"${table}\" ALTER COLUMN \"${drift.column}\" ` +\n `TYPE ${drift.declared} USING \"${drift.column}\"::${drift.declared};`\n );\n}\n","/**\n * The additive statements that bring a database up to a {@link SchemaPlan}.\n *\n * ## Why additive-only, forever\n *\n * This runs unattended, at boot, against a database with customers' data in it,\n * with no human reading a diff. So it may only ever do things that cannot lose\n * data: create a missing table, add a missing column, create a missing enum\n * type, add an enum value, create an index.\n *\n * It will **never** drop a table or a column, narrow a type, or alter a\n * constraint at boot. A removed field leaves its column behind; a renamed field\n * looks like an addition and the old column stays. That is the correct trade\n * for an automated path — the alternative is an unattended process that can\n * silently destroy a column. Destructive changes stay a deliberate,\n * human-reviewed migration. Because of that, this is safe to run on every boot,\n * and re-running it is a no-op.\n *\n * ## What changed when the planner arrived\n *\n * This used to read `Property` itself — its own reading of the type, of\n * `validation`, of relations, of enums — and disagreed with `db push` about all\n * of them. The audit found a required `author_id` that was NOT NULL after a\n * push and nullable after a boot, on the one path with no developer in the\n * loop. Now it reads the same {@link ColumnPlan} the DDL renderer does, so a\n * column's type, default, uniqueness and foreign key are decided once. What is\n * left here is the half that is genuinely this path's own: *what the database\n * already has*, and which of the planned constraints are safe to apply to it.\n */\nimport type { ColumnPlan, SchemaPlan, TablePlan } from \"./types\";\nimport { renderColumnDefinition, renderEnableRls, renderPgType, renderPrimaryKeyConstraint } from \"./render-ddl\";\nimport { quoteSqlLiteral } from \"./plan-schema\";\nimport { SET_UPDATED_AT_FN, triggerStatements } from \"./updated-at-trigger\";\nimport {\n SEARCH_STAMP_PREFIX,\n SEARCH_TEXT_FN,\n SEARCH_UNACCENT_FN,\n searchColumnStamps,\n searchIndexStatements\n} from \"../search-column\";\nimport { collectionIndexStatement, sortIndexSpecs } from \"../collection-index\";\nimport { vectorIndexStatement, type SkippedVectorIndex } from \"../vector-index\";\nimport { typesAgree, type ColumnTypeDrift } from \"../column-type-drift\";\n\n/** Postgres identifiers this module is willing to interpolate. */\nconst SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;\n\n/**\n * Validation used to run only on the names read back OUT of the catalogue,\n * which is the direction that cannot hurt anyone: those came from Postgres. The\n * names going IN — the schema and table a collection declares — were quoted and\n * concatenated on trust, and quoting is not escaping. A table named\n * `x\" (id int); DROP TABLE users; --` closes the quote and the statement, and\n * the whole thing runs on the owner connection, which is the one connection in\n * the system that is exempt from every RLS policy.\n *\n * That is only a config file on a self-hosted project, where the person writing\n * it could run the SQL directly anyway. It is not only a config file where a\n * collection can be defined over the wire — the live-schema and source editors\n * both do that — and there the caller is an admin on the app, not an operator\n * of the database.\n */\nexport function assertSafeIdentifier(value: string, what: string): string {\n if (!SAFE_IDENTIFIER.test(value)) {\n throw new Error(`Refusing to build SQL with an unsafe ${what}: ${JSON.stringify(value)}`);\n }\n return value;\n}\n\n/** What the database currently has, as the planner needs it. */\nexport interface ExistingSchema {\n /** `schema.table` → set of column names. */\n tables: Map<string, Set<string>>;\n /** `schema.typename` of every enum type that already exists. */\n enums: Set<string>;\n /**\n * `schema.table.constraint` of every constraint that already exists.\n *\n * Optional so a caller that only cares about tables can still build one by\n * hand; absent is read as \"none known\", which at worst re-attempts a\n * constraint that then fails harmlessly as a duplicate.\n */\n constraints?: Set<string>;\n /**\n * `schema.table.column` → that column's comment, for the columns that have\n * one. This is where a generated search column's fingerprint lives.\n */\n columnComments?: Map<string, string>;\n /** `schema.typename` → its labels, in `enumsortorder`. */\n enumValues?: Map<string, string[]>;\n /** `schema.table.column` of every NOT NULL column. */\n notNullColumns?: Set<string>;\n /** `schema.table.column` of every column that has a DEFAULT. */\n columnDefaults?: Set<string>;\n /** `schema.table` of every table that holds at least one row. */\n populatedTables?: Set<string>;\n /**\n * `schema.table.column` → the type Postgres reports, as `udt_name` (plus a\n * modifier where one distinguishes two columns of the same family, e.g.\n * `numeric(10,2)`).\n */\n columnTypes?: Map<string, string>;\n /** `schema.table.trigger` of every trigger that already exists. */\n triggers?: Set<string>;\n /**\n * `schema.name` of every index (any relation of kind `i`/`I`) that already\n * exists. Absent means unknown, and every index is planned as before —\n * `IF NOT EXISTS` makes that correct, just not free.\n */\n indexes?: Set<string>;\n /**\n * `schema.name` of every index whose `pg_index.indisvalid` is false — the\n * husk a `CREATE INDEX CONCURRENTLY` leaves behind when it is cancelled,\n * times out, or loses a race with a peer. Such an index is in\n * {@link indexes} too, maintained on every write and used by no query, and\n * `IF NOT EXISTS` skips it by name forever. Absent means unknown.\n */\n invalidIndexes?: Set<string>;\n /**\n * Names of the extensions installed in the database. `CREATE EXTENSION IF\n * NOT EXISTS` skips by name whatever schema the extension is in, so the name\n * is the whole test. Absent means unknown.\n */\n extensions?: Set<string>;\n /**\n * {@link HELPER_FUNCTIONS} as they are in the catalogue: `schema.name(args)`\n * → {@link describeHelperFunction} of what `CREATE OR REPLACE` would set.\n * Absent means unknown, and every helper is re-created as before.\n */\n functions?: Map<string, string>;\n}\n\n/**\n * The functions the plan creates with `CREATE OR REPLACE`, which the catalogue\n * reader looks up so a boot that finds them unchanged plans nothing.\n *\n * A helper missing from this list is not wrong, only re-created on every boot,\n * which is what all of them were before.\n */\nexport const HELPER_FUNCTIONS: readonly string[] = [SEARCH_TEXT_FN, SEARCH_UNACCENT_FN, SET_UPDATED_AT_FN];\n\n/**\n * Everything `CREATE OR REPLACE FUNCTION` sets on a function, as one string.\n *\n * Built from the catalogue by the reader and from the statement by\n * {@link parseHelperFunction}, so the two meet in one shape. It covers every\n * attribute a `CREATE OR REPLACE` resets — body, language, volatility,\n * strictness, parallel safety, security, leakproofness, cost and `SET` options —\n * so a function someone altered by hand (`ALTER FUNCTION … VOLATILE`) still\n * compares unequal and is re-created, exactly as the unconditional statement\n * used to re-create it.\n */\nexport interface HelperFunctionFacts {\n returns: string;\n language: string;\n /** `provolatile`: `i`mmutable, `s`table, `v`olatile. */\n volatility: string;\n strict: boolean;\n /** `proparallel`: `s`afe, `r`estricted, `u`nsafe. */\n parallel: string;\n securityDefiner: boolean;\n leakproof: boolean;\n cost: number;\n /** Whether the function carries any `SET` options (`proconfig`). */\n hasConfig: boolean;\n /** `prosrc`: the text between the dollar quotes, exactly. */\n body: string;\n}\n\nexport const helperFunctionKey = (schema: string, name: string, args: string): string =>\n `${schema}.${name}(${args.replace(/\\s+/g, \" \").trim().toLowerCase()})`;\n\nexport const describeHelperFunction = (facts: HelperFunctionFacts): string =>\n JSON.stringify([\n facts.returns.toLowerCase(), facts.language.toLowerCase(), facts.volatility, facts.strict, facts.parallel,\n facts.securityDefiner, facts.leakproof, Number(facts.cost), facts.hasConfig, facts.body\n ]);\n\nconst HELPER_FUNCTION_RE = new RegExp(\n \"^\\\\s*CREATE OR REPLACE FUNCTION\\\\s+([A-Za-z_]\\\\w*)\\\\.([A-Za-z_]\\\\w*)\\\\(([^)]*)\\\\)\" +\n \"\\\\s+RETURNS\\\\s+([\\\\w\\\\[\\\\]]+)\\\\s+LANGUAGE\\\\s+(\\\\w+)\" +\n \"((?:\\\\s+(?:IMMUTABLE|STABLE|VOLATILE|STRICT|PARALLEL\\\\s+(?:SAFE|RESTRICTED|UNSAFE)))*)\" +\n \"\\\\s+AS\\\\s+\\\\$\\\\$([\\\\s\\\\S]*)\\\\$\\\\$;?\\\\s*$\",\n \"i\"\n);\n\n/**\n * What a helper's `CREATE OR REPLACE FUNCTION` statement would leave in the\n * catalogue, or `undefined` for a statement this does not recognise — which is\n * then planned unconditionally, as every statement was before.\n *\n * Only ever given statements this package renders (`searchHelperFunctions`,\n * `setUpdatedAtFunction`), so a strict pattern is the right tool: anything it\n * does not match exactly falls back to the safe behaviour.\n */\nexport function parseHelperFunction(statement: string): { key: string; definition: string } | undefined {\n const match = HELPER_FUNCTION_RE.exec(statement);\n if (!match) return undefined;\n const [, schema, name, args, returns, language, attributes, body] = match;\n const words = attributes.toUpperCase();\n const parallel = /PARALLEL\\s+SAFE/.test(words) ? \"s\" : /PARALLEL\\s+RESTRICTED/.test(words) ? \"r\" : \"u\";\n const volatility = /\\bIMMUTABLE\\b/.test(words) ? \"i\" : /\\bSTABLE\\b/.test(words) ? \"s\" : \"v\";\n return {\n key: helperFunctionKey(schema, name, args),\n definition: describeHelperFunction({\n returns,\n language,\n volatility,\n strict: /\\bSTRICT\\b/.test(words),\n parallel,\n securityDefiner: false,\n leakproof: false,\n // Postgres's default for every language but C and internal.\n cost: 100,\n hasConfig: false,\n body\n })\n };\n}\n\n/** The name a rendered `CREATE [UNIQUE] INDEX [CONCURRENTLY] IF NOT EXISTS \"<name>\"` creates. */\nconst indexNameOf = (statement: string): string | undefined =>\n /^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX\\s+(?:CONCURRENTLY\\s+)?IF\\s+NOT\\s+EXISTS\\s+\"([^\"]+)\"/i.exec(statement)?.[1];\n\n/** The extension a rendered `CREATE EXTENSION IF NOT EXISTS <name> …` installs. */\nconst extensionNameOf = (statement: string): string | undefined =>\n /^\\s*CREATE\\s+EXTENSION\\s+IF\\s+NOT\\s+EXISTS\\s+\"?([\\w-]+)\"?/i.exec(statement)?.[1];\n\n/**\n * How far the planner may go in making the database's constraints match the\n * configuration.\n *\n * - `additive` — the boot default. Columns, tables, indexes and enum values are\n * created; no existing column's constraints are touched. Unattended boots run\n * against customer data with nobody reading a diff, and a database adopted by\n * introspection legitimately carries NOT NULL on columns the generated\n * collection leaves optional (`introspect-db-logic` withholds `required` from\n * a column with a default or a trigger behind it). Converging there would\n * strip real constraints on first boot.\n * - `converge` — the live schema editor. Every statement is planned, shown to\n * the person making the change, and applied only once they confirm it.\n */\nexport type ConstraintPolicy = \"additive\" | \"converge\";\n\nexport interface DiffOptions {\n /** Defaults to `additive`. See {@link ConstraintPolicy}. */\n constraints?: ConstraintPolicy;\n /**\n * Plan every index a table that already exists needs — declared, search\n * and vector, missing or left INVALID under its name — as a\n * {@link DeferredIndexBuild} rather than an action, as the derived\n * foreign-key indexes always are. `ensureCollectionTables` sets it: it\n * hands them to `buildDeferredIndexes`, which builds them on a connection\n * of its own with no `statement_timeout`, and drops and rebuilds a husk.\n *\n * Absent — the live schema editor, which applies `statements` as text —\n * they stay `CREATE INDEX CONCURRENTLY IF NOT EXISTS` actions, as before.\n */\n deferLiveIndexes?: boolean;\n}\n\nexport interface EnsureAction {\n kind: \"create-enum\" | \"create-table\" | \"enable-rls\" | \"add-column\" | \"add-constraint\" | \"rename-column\"\n | \"create-extension\" | \"create-function\" | \"create-index\" | \"comment-column\"\n | \"add-enum-value\" | \"set-not-null\" | \"drop-not-null\" | \"set-default\" | \"create-trigger\";\n /** Qualified target, for logging: `public.posts` or `public.posts.title`. */\n target: string;\n sql: string;\n}\n\n/** A NOT NULL column with no default that no property declares. */\nexport interface OrphanedRequiredColumn {\n /** `schema.table`. */\n table: string;\n /** The column left behind. */\n column: string;\n /** The collection that no longer declares it. */\n slug: string;\n}\n\n/** A constraint the configuration asks for that the planner is not applying. */\nexport interface WithheldConstraint {\n /** `schema.table.column`. */\n target: string;\n kind: \"not-null\" | \"unique\";\n /**\n * Why, in a sentence that names the obstacle rather than the rule. The\n * reader is looking at a column that is nullable when they asked for\n * required, or accepts duplicates when they asked for unique, and needs to\n * know what to do about it.\n */\n reason: string;\n /** What would make it applicable. */\n remedy: string;\n}\n\n/**\n * A generated search column built from a `search` block that has since changed.\n *\n * Reported instead of applied because the two ways to apply it are both worse\n * than stopping. `ALTER COLUMN … SET EXPRESSION` exists only on PG17+ and\n * rewrites the table either way; `DROP COLUMN` + `ADD COLUMN` rewrites it under\n * an ACCESS EXCLUSIVE lock and rebuilds the GIN index. This module runs\n * unattended against live customer data with nobody reading a diff, so a\n * multi-minute outage is not a decision it may take on its own.\n *\n * Not applying it silently is not an option either: a collection that added a\n * field, flipped `unaccent` or raised a weight kept indexing the *old* set\n * forever, and the only symptom was searches returning nothing for content\n * plainly in the row.\n */\nexport interface SearchColumnDrift {\n /** `schema.table`. */\n table: string;\n column: string;\n /** The fingerprint recorded on the column. */\n found: string;\n /** The fingerprint the current `search` block computes. */\n expected: string;\n /** The statements that would rebuild the column, for the operator to run. */\n rebuild: string[];\n}\n\n/** A relation column whose old and new spellings both plausibly apply. */\nexport interface LegacyForeignKey {\n /** `schema.table`. */\n table: string;\n /** The name the current rule derives, and what this plan would create. */\n expected: string;\n /** The name the old rule derived, which the table already has. */\n legacy: string;\n}\n\n/**\n * An index a table that already exists is missing, or holds INVALID — a\n * derived foreign-key index always, and under\n * {@link DiffOptions.deferLiveIndexes} a declared, search or vector one too.\n *\n * Not an {@link EnsureAction}, because it must not hold the boot: on a table\n * with millions of rows `CREATE INDEX CONCURRENTLY` takes minutes, and every\n * minute of it would be a minute the deployment is not serving. The caller\n * builds these after the fact — boot in the background once it serves, every\n * other caller inline after the actions — through `buildDeferredIndexes`. A\n * {@link unique} one is the exception: it is built before the ensure returns.\n *\n * Kept out of {@link EnsurePlan.statements} for the same reason: a caller that\n * applies statements as text (the live schema editor) may run them inside a\n * transaction, which `CONCURRENTLY` refuses.\n */\nexport interface DeferredIndexBuild {\n schema: string;\n /** Bare table name. */\n table: string;\n indexName: string;\n /** `CREATE [UNIQUE] INDEX CONCURRENTLY IF NOT EXISTS …;` */\n sql: string;\n /**\n * The catalogue already holds an INVALID index under this name, which has\n * to be dropped before the build — `IF NOT EXISTS` would skip it.\n */\n invalid: boolean;\n /**\n * A declared `unique: true` index. Not an optimization but the collection\n * promising two rows cannot share a value, so `ensureCollectionTables`\n * builds it before it returns — never after the server is serving — and\n * fails when it cannot, as it did when this was an action. Absent is false.\n */\n unique?: boolean;\n}\n\nexport interface EnsurePlan {\n actions: EnsureAction[];\n /** Every statement, in dependency order. Empty when the schema is current. */\n statements: string[];\n /**\n * Relation columns this plan is about to create where the table already\n * carries the same column under its pre-singularization name.\n *\n * Reported rather than silently handled: the ensure is additive, so it\n * would add `category_id` beside a populated `categorie_id` and the\n * relation would then read the new, empty one. No statement fails, no table\n * is missing, and the only symptom is relations resolving to nothing.\n */\n legacyForeignKeys: LegacyForeignKey[];\n /** @see SearchColumnDrift */\n searchDrift: SearchColumnDrift[];\n /**\n * Generated search columns that exist but carry no fingerprint — created\n * before this check existed, or by `search.sql` on an older CLI. The plan\n * stamps them so the *next* change is detectable.\n */\n searchAdopted: { table: string; column: string }[];\n /**\n * Vector columns this plan is deliberately leaving unindexed, because\n * pgvector cannot build an ANN index that wide. Reported rather than\n * thrown: the column is valid, storable and searchable.\n */\n vectorIndexSkipped: SkippedVectorIndex[];\n /**\n * Constraints the configuration asks for that this plan is not applying,\n * and why. Every one of these was previously withheld in silence.\n */\n withheldConstraints: WithheldConstraint[];\n /**\n * Columns whose type in the database is in a different family from the one\n * the collection declares. Reported and never acted on — this is the one\n * divergence that presents as a *working* deploy.\n */\n columnTypeDrift: ColumnTypeDrift[];\n /**\n * Columns that are NOT NULL, have no default, and that no property declares\n * any more — so every insert through the API is rejected for a field the\n * author cannot name, because they already deleted it. This is what a\n * **rename** looks like to an additive provisioner. Reported, never acted\n * on: dropping the column is the right fix roughly always and destructive\n * exactly once, which is not a decision to take unattended.\n */\n orphanedRequiredColumns: OrphanedRequiredColumn[];\n /** @see DeferredIndexBuild */\n deferredIndexes: DeferredIndexBuild[];\n}\n\n/**\n * Whether a column is part of the table's primary key.\n *\n * Those are created with the table, in step 2, and never added afterwards: a\n * key column missing from a table that already exists cannot be made part of\n * its key by an additive change, so there is nothing safe to plan for one.\n *\n * A relation's entry for a column a declared property owns is not the column —\n * it carries only the constraint — so it is not a key column either, or the\n * key would be created twice.\n */\nconst isKeyColumn = (table: TablePlan, column: ColumnPlan): boolean =>\n !column.columnOwnedByProperty && table.primaryKey.includes(column.column);\n\n/**\n * A declared key whose default is the built-in uuid generator: the default\n * `isId: \"uuid\"` plans. It is the one declared-key default boot sets on an\n * existing table, because it is the one that cannot fail there.\n */\nconst isUuidKeyDefault = (column: ColumnPlan): boolean =>\n column.source.kind === \"property\" &&\n column.default?.kind === \"sql\" &&\n column.default.expression === \"gen_random_uuid()\";\n\n/** Which pass a column belongs to. The order below is the order they run in. */\nconst isScalarProperty = (table: TablePlan, column: ColumnPlan): boolean =>\n (column.source.kind === \"property\" || column.source.kind === \"implicit-id\") && !isKeyColumn(table, column);\n\n/**\n * `ENABLE ROW LEVEL SECURITY` on a table this plan has just created — the\n * statement immediately after its `CREATE TABLE`, never later.\n *\n * The user role every authenticated request runs as holds DML on a new table\n * the moment it exists: the schema's default privileges grant it, and boot's\n * `ensureAppRole` grants it on every table before the policies run. The\n * policies — which also switch RLS on — come after the driver and auth have\n * initialised, so any failure in between left a table with full DML and no row\n * filtering, served by every process in the deployment that does not\n * provision. Born locked, a table denies until its policies arrive, which is\n * the state a failure is allowed to leave behind. Idempotent, so a table a\n * concurrent boot created gets the same statement and nothing changes.\n */\nconst lockAction = (table: TablePlan): EnsureAction => ({\n kind: \"enable-rls\",\n target: table.qualified,\n sql: renderEnableRls(table)\n});\n\nexport function diffPlanAgainstCatalogue(\n plan: SchemaPlan,\n existing: ExistingSchema,\n options: DiffOptions = {}\n): EnsurePlan {\n const constraintPolicy: ConstraintPolicy = options.constraints ?? \"additive\";\n const actions: EnsureAction[] = [];\n const withheldConstraints: WithheldConstraint[] = [];\n const columnTypeDrift: ColumnTypeDrift[] = [];\n const legacyForeignKeys: LegacyForeignKey[] = [];\n const searchDrift: SearchColumnDrift[] = [];\n const searchAdopted: { table: string; column: string }[] = [];\n\n const collectionTables = plan.tables.filter(t => t.kind === \"collection\");\n const junctionTables = plan.tables.filter(t => t.kind === \"junction\");\n\n // 1. Enum types. `CREATE TYPE` has no IF NOT EXISTS, so an existing type is\n // skipped by name rather than guarded in SQL.\n for (const enumPlan of plan.enums) {\n assertSafeIdentifier(enumPlan.schema, \"schema name\");\n if (existing.enums.has(enumPlan.qualified)) {\n // The type is there, but that says nothing about its *values*.\n // Skipping the whole type by name is what made an added enum value\n // vanish: nothing was planned, the boot reported success, and the\n // first row using the value was rejected by a type that had never\n // heard of it. `ADD VALUE` is the one alteration Postgres offers\n // here, it is purely additive, and it is idempotent.\n //\n // `enumValues` absent means the caller built the schema by hand and\n // does not know the values; skip by name as before.\n const current = existing.enumValues?.get(enumPlan.qualified);\n if (!current) continue;\n for (const value of enumPlan.labels) {\n if (current.includes(value)) continue;\n actions.push({\n kind: \"add-enum-value\",\n target: `${enumPlan.qualified}.${value}`,\n // Not inside a transaction with any use of the value:\n // Postgres refuses to read a value added by the transaction\n // still adding it. The applier runs these one statement at a\n // time, which is what makes it legal.\n sql: `ALTER TYPE \"${enumPlan.schema}\".\"${enumPlan.name}\" ADD VALUE IF NOT EXISTS ${quoteSqlLiteral(value)};`\n });\n }\n continue;\n }\n actions.push({\n kind: \"create-enum\",\n target: enumPlan.qualified,\n sql: `CREATE TYPE \"${enumPlan.schema}\".\"${enumPlan.name}\" AS ENUM (${enumPlan.labels.map(quoteSqlLiteral).join(\", \")});`\n });\n }\n\n // 1b. Extensions and helper functions, before the tables and columns that\n // reference them: a generated column's expression is resolved when the\n // column is created, so a table whose search column calls\n // `rebase_search_text` cannot be added before that function exists.\n // Both forms are idempotent, and a boot against a database that already\n // has them plans nothing: each is looked up in the catalogue first. An\n // unconditional `CREATE OR REPLACE` rewrote the function's `pg_proc` row\n // and invalidated every cached plan that calls it, on every replica, on\n // every boot — and was reported as a change applied.\n for (const statement of plan.extensions) {\n const extension = extensionNameOf(statement);\n if (extension && existing.extensions?.has(extension)) continue;\n actions.push({\n kind: \"create-extension\",\n target: statement.replace(/^CREATE EXTENSION IF NOT EXISTS |;$/g, \"\"),\n sql: statement\n });\n }\n for (const statement of plan.functions) {\n const helper = parseHelperFunction(statement);\n if (helper && existing.functions?.get(helper.key) === helper.definition) continue;\n actions.push({ kind: \"create-function\", target: functionTarget(statement), sql: statement });\n }\n\n // 2. Missing tables. Only the key columns are created here; every other\n // column is added by step 3, so a new table and an existing table that\n // gained a field travel the exact same code path. One way to build a\n // column means one way for it to be wrong.\n //\n // A composite key's columns all arrive here, with the one `PRIMARY KEY`\n // constraint naming them: a primary key can only be declared when the\n // table is created, and a table created with the first key column alone\n // would never gain the rest as part of its key.\n const created = new Set<string>();\n for (const table of collectionTables) {\n if (existing.tables.has(table.qualified) || created.has(table.qualified)) continue;\n created.add(table.qualified);\n const schema = assertSafeIdentifier(table.schema, \"schema name\");\n const name = assertSafeIdentifier(table.table, \"table name\");\n const keyColumns = table.columns.filter(c => isKeyColumn(table, c));\n const definitions = keyColumns.length > 0\n ? keyColumns.map(c => `\"${assertSafeIdentifier(c.column, \"column name\")}\" ${renderColumnDefinition(c)}`)\n : ['\"id\" TEXT PRIMARY KEY'];\n if (keyColumns.length > 1) definitions.push(renderPrimaryKeyConstraint(table));\n actions.push({\n kind: \"create-table\",\n target: table.qualified,\n sql: `CREATE TABLE IF NOT EXISTS \"${schema}\".\"${name}\" (${definitions.join(\", \")});`\n });\n actions.push(lockAction(table));\n }\n\n // 2b. Junction tables behind many-to-many relations. No collection declares\n // them, so until they existed an m2m write had nowhere to land and the\n // junction's derived RLS had nothing to attach to. Both columns are\n // created here — unlike a collection table, whose CREATE declares only\n // the identity column — because there is nothing else to them.\n for (const table of junctionTables) {\n if (existing.tables.has(table.qualified) || created.has(table.qualified)) continue;\n created.add(table.qualified);\n const columns = table.columns\n .map(c => `\"${c.column}\" ${renderColumnDefinition(c)}`)\n .join(\", \");\n actions.push({\n kind: \"create-table\",\n target: table.qualified,\n sql: `CREATE TABLE IF NOT EXISTS \"${table.schema}\".\"${table.table}\" (${columns}` +\n `, ${renderPrimaryKeyConstraint(table)});`\n });\n actions.push(lockAction(table));\n }\n\n const addColumn = (table: TablePlan, column: string, definition: string): void => {\n if (existing.tables.get(table.qualified)?.has(column)) return;\n // Same reason as `assertSafeIdentifier` above: a column name reaching\n // here came from a property declaration, which on the editor paths came\n // over the wire. `definition` is built by the renderer from a closed set\n // of type mappings and is not caller text.\n assertSafeIdentifier(column, \"column name\");\n actions.push({\n kind: \"add-column\",\n target: `${table.qualified}.${column}`,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ADD COLUMN IF NOT EXISTS \"${column}\" ${definition};`\n });\n };\n\n /**\n * Move a column that is only missing because it was renamed.\n *\n * Returns true when it handled the column, so the caller skips the ordinary\n * ADD. Adding would be the wrong move and a quiet one: the data is in the\n * old column, `ADD COLUMN` creates the new one empty beside it, every\n * statement succeeds, and the relation reads the empty one. A rename is\n * metadata-only in Postgres, keeps the values, and carries the column's\n * indexes and constraints with it.\n */\n const renameLegacyColumn = (table: TablePlan, column: ColumnPlan): boolean => {\n const present = existing.tables.get(table.qualified);\n if (!column.legacyColumn || !present) return false;\n if (present.has(column.column) || !present.has(column.legacyColumn)) return false;\n legacyForeignKeys.push({ table: table.qualified, expected: column.column, legacy: column.legacyColumn });\n actions.push({\n kind: \"rename-column\",\n target: `${table.qualified}.${column.column}`,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" RENAME COLUMN \"${column.legacyColumn}\" TO \"${column.column}\";`\n });\n return true;\n };\n\n /**\n * A `NOT NULL` is safe exactly when it cannot fail against rows that are\n * already there, and there are three ways to know that:\n *\n * - the table is being created by this plan (no rows yet);\n * - the table exists and is empty;\n * - the column arrives with a DEFAULT, which Postgres backfills into every\n * existing row as part of ADD COLUMN.\n *\n * `populatedTables` absent means the caller does not know, and not knowing\n * has to read as \"assume rows\" — the other direction emits a NOT NULL that\n * is checked against live data and aborts the boot. Written as an explicit\n * `!== undefined` because the optional-chain form quietly says *empty* when\n * the fact is missing, which is the wrong way to be wrong.\n */\n const tableIsEmpty = (table: TablePlan): boolean =>\n existing.populatedTables !== undefined\n && existing.tables.has(table.qualified)\n && !existing.populatedTables.has(table.qualified);\n\n /**\n * The column is there and holds a different kind of value than the\n * collection says it does. Reported, never altered: an unattended `ALTER\n * COLUMN … TYPE` over customer data is not a thing to do quietly, and the\n * *quiet* is what this fixes. A deploy that changed a `columnType` used to\n * report success while the column stayed as it was, and the divergence\n * surfaced later as every write failing. A column whose definition is owned\n * elsewhere (auth, or a generated search column) is not compared: the\n * declaration there is a rendered string rather than a type, and auth's own\n * reconcile owns it.\n */\n const reportTypeDrift = (table: TablePlan, column: ColumnPlan): void => {\n const key = `${table.qualified}.${column.column}`;\n if (existing.tables.get(table.qualified)?.has(column.column) !== true || column.sqlDefinition) return;\n const declaredType = renderPgType(column.type);\n const actualType = existing.columnTypes?.get(key);\n if (actualType && !typesAgree(declaredType, actualType)) {\n columnTypeDrift.push({ table: table.qualified, column: column.column, declared: declaredType, actual: actualType });\n }\n };\n\n /**\n * `SET DEFAULT` on a column that is already there and has none.\n *\n * A DEFAULT binds future writes only, so `SET DEFAULT` cannot fail on data\n * and cannot touch a row that already exists. That makes it the one\n * convergence this path may do unattended — and it has to, because\n * `ADD COLUMN IF NOT EXISTS` is a no-op against an existing column, so a\n * `defaultValue` added to a live collection would otherwise never reach the\n * database at all.\n */\n const planMissingDefault = (table: TablePlan, column: ColumnPlan): void => {\n if (!column.default || column.default.kind === \"identity\" || column.generated) return;\n const key = `${table.qualified}.${column.column}`;\n if (existing.columnDefaults?.has(key)) return;\n const expression = column.default.kind === \"sql\" ? column.default.expression : column.default.sql;\n actions.push({\n kind: \"set-default\",\n target: key,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ALTER COLUMN \"${column.column}\" SET DEFAULT ${expression};`\n });\n };\n\n /**\n * Plan one column, with the constraints this database can safely take.\n *\n * The definition comes from the same renderer `schema.sql` uses, minus the\n * constraints that are checked against live rows. That subtraction is the\n * whole of what this path is allowed to decide for itself.\n */\n const planColumn = (table: TablePlan, column: ColumnPlan): void => {\n const key = `${table.qualified}.${column.column}`;\n const columnExists = existing.tables.get(table.qualified)?.has(column.column) === true;\n const fresh = created.has(table.qualified);\n const empty = tableIsEmpty(table);\n const required = !column.nullable;\n const hasDefault = column.default !== undefined;\n\n reportTypeDrift(table, column);\n\n // A table this run is creating has no rows yet, so the constraints\n // `db push` writes are free to apply. On a table that already exists\n // they are checked against live rows, so each is applied only where it\n // cannot fail.\n //\n // NOT NULL needs every existing row to get a value: an empty table, or\n // a default that backfills them.\n //\n // UNIQUE needs every existing row to get a *different* value, and a\n // column being added gets either its default in every row — the same\n // value, so a second row fails — or NULL in every row, and NULLs are\n // distinct. So it holds on an empty table, and on any table when the\n // column arrives with no default. A column that is already there is\n // not touched: whether it carries a unique constraint or index under\n // some other name is not something the catalogue read here says.\n const notNullIsSafe = fresh || empty || hasDefault;\n const uniqueIsSafe = fresh || empty || !hasDefault;\n const applicable: ColumnPlan = {\n ...column,\n unique: column.unique && !columnExists && uniqueIsSafe,\n nullable: column.nullable || !(notNullIsSafe || columnExists)\n };\n if (column.unique && !columnExists && !uniqueIsSafe) {\n withheldConstraints.push({\n target: key,\n kind: \"unique\",\n reason:\n `\"${column.column}\" is unique, but \"${table.qualified}\" ` +\n (existing.populatedTables === undefined ? \"may already hold rows\" : \"already holds rows\") +\n \" and the column's default would give every one of them the same value, so UNIQUE \" +\n \"would fail as it was added.\",\n remedy:\n \"Give each existing row its own value, then add the constraint — \" +\n `\\`ALTER TABLE \"${table.schema}\".\"${table.table}\" ADD UNIQUE (\"${column.column}\")\\` — ` +\n \"or drop the property's default.\"\n });\n }\n if (required && !columnExists && !notNullIsSafe) {\n withheldConstraints.push({\n target: key,\n kind: \"not-null\",\n reason: column.source.kind === \"relation\" || column.source.kind === \"reference\"\n ? `\"${column.column}\" is a required link, but \"${table.qualified}\" already holds rows and ` +\n \"the column has no default to backfill them with, so NOT NULL would be checked \" +\n \"against data that does not have a value yet.\"\n : `\"${column.column}\" is required, but \"${table.qualified}\" already holds rows and the column ` +\n \"has no default to backfill them with, so NOT NULL would be checked \" +\n \"against data that does not have a value yet.\",\n remedy: column.source.kind === \"relation\" || column.source.kind === \"reference\"\n ? \"Backfill the column, then add the constraint — or make the relation optional.\"\n : \"Backfill the column, then add the constraint — or give the property a \" +\n \"default so every existing row gets one.\"\n });\n }\n addColumn(table, column.column, renderColumnDefinition(applicable));\n\n if (!columnExists) return;\n\n planMissingDefault(table, column);\n\n // Two directions on NOT NULL, and they are not equally safe — see\n // `ConstraintPolicy` for why neither runs at an unattended boot.\n if (constraintPolicy !== \"converge\") return;\n const isNotNull = existing.notNullColumns?.has(key) === true;\n if (required && !isNotNull) {\n if (empty) {\n actions.push({\n kind: \"set-not-null\",\n target: key,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ALTER COLUMN \"${column.column}\" SET NOT NULL;`\n });\n } else {\n withheldConstraints.push({\n target: key,\n kind: \"not-null\",\n reason:\n `\"${column.column}\" became required, but \"${table.qualified}\" holds rows and any of them ` +\n \"with no value would make SET NOT NULL fail.\",\n remedy:\n \"Backfill the column first — `UPDATE … SET \\\"\" + column.column +\n \"\\\" = … WHERE \\\"\" + column.column + \"\\\" IS NULL` — then apply this again.\"\n });\n }\n }\n if (!required && isNotNull) {\n // Loosening never fails and never loses data. It is here rather\n // than at boot because a database adopted by introspection carries\n // NOT NULL on columns the generated collection deliberately leaves\n // optional, and converging those unasked would drop constraints\n // nobody edited.\n actions.push({\n kind: \"drop-not-null\",\n target: key,\n sql: `ALTER TABLE \"${table.schema}\".\"${table.table}\" ALTER COLUMN \"${column.column}\" DROP NOT NULL;`\n });\n }\n };\n\n // 3. Scalar columns, then the auth columns the collection never mentions.\n // The scaffold's users collection describes 12 of the 14 columns auth\n // reads and writes, so planning only from properties left `is_anonymous`\n // and `tokens_valid_after` to `ensureAuthTablesExist` — which does create\n // them, but only because that function happens to run later in the same\n // boot. Planning them here makes this path self-contained.\n for (const table of collectionTables) {\n assertSafeIdentifier(table.schema, \"schema name\");\n assertSafeIdentifier(table.table, \"table name\");\n for (const column of table.columns) {\n if (!isScalarProperty(table, column)) continue;\n planColumn(table, column);\n }\n // The implicit key of a collection that declares none. It is created\n // with the table, so the only thing to plan is the default a table\n // made before the key had one is missing — without it, nothing can\n // insert a row there: no door sends a key that is not a property.\n //\n // A declared uuid key (`isId: \"uuid\"`) is the same case: no door sends\n // it, and a table adopted by introspection or made by hand may lack\n // its default. Only the built-in generator is converged. A SQL\n // strategy's function may not exist yet, and setting it here would\n // turn an insert-time failure into a boot failure.\n for (const column of table.columns) {\n if (!column.primaryKey) continue;\n if (column.source.kind !== \"implicit-id\" && !isUuidKeyDefault(column)) continue;\n if (existing.tables.get(table.qualified)?.has(column.column) !== true) continue;\n planMissingDefault(table, column);\n }\n for (const column of table.columns) {\n if (column.source.kind !== \"auth\") continue;\n addColumn(table, column.column, renderColumnDefinition(column));\n }\n }\n\n // 3a. The generated search columns.\n //\n // Adding a STORED generated column rewrites the table, which on a large\n // one is not free — but it is the same additive shape as every other\n // column here, and the alternative (leaving it out until someone runs a\n // migration) is a declared `search` block that silently does nothing.\n //\n // Changing one is not additive, and `ADD COLUMN IF NOT EXISTS` is a\n // no-op against a column that is already there — which is why a `search`\n // block that gained a field, flipped `unaccent` or moved a weight used\n // to be inert forever, on every path, with nothing logged. Each column\n // carries a fingerprint of the expression it was built from, and a\n // mismatch is reported rather than applied.\n for (const table of collectionTables) {\n if (!table.search) continue;\n const definitions = new Map(\n table.columns\n .filter(c => c.source.kind === \"search\")\n .map(c => [c.column, renderColumnDefinition(c)] as const)\n );\n for (const stamp of searchColumnStamps(table.search)) {\n const definition = definitions.get(stamp.column)!;\n const exists = existing.tables.get(table.qualified)?.has(stamp.column) === true;\n const recorded = existing.columnComments?.get(`${table.qualified}.${stamp.column}`);\n\n if (exists && recorded?.startsWith(SEARCH_STAMP_PREFIX) && recorded !== stamp.fingerprint) {\n searchDrift.push({\n table: table.qualified,\n column: stamp.column,\n found: recorded,\n expected: stamp.fingerprint,\n rebuild: [\n `ALTER TABLE \"${table.schema}\".\"${table.table}\" DROP COLUMN \"${stamp.column}\";`,\n `ALTER TABLE \"${table.schema}\".\"${table.table}\" ADD COLUMN \"${stamp.column}\" ${definition};`,\n stamp.sql\n ]\n });\n // The old stamp is the only evidence of what the column holds;\n // overwriting it here would erase the drift instead of fixing it.\n continue;\n }\n\n addColumn(table, stamp.column, definition);\n if (exists && recorded === undefined) {\n searchAdopted.push({ table: table.qualified, column: stamp.column });\n }\n if (recorded !== stamp.fingerprint) {\n actions.push({ kind: \"comment-column\", target: `${table.qualified}.${stamp.column}`, sql: stamp.sql });\n }\n }\n }\n\n // 3b. A junction that already existed, but is short a column. One created\n // above already carries both, so re-listing them would log two no-op\n // statements and inflate the count of changes applied.\n for (const table of junctionTables) {\n if (created.has(table.qualified)) continue;\n for (const column of table.columns) {\n if (renameLegacyColumn(table, column)) continue;\n // A payload column (`through.properties`) goes through `planColumn`,\n // the same pass a collection's scalar columns take. The bare\n // `ADD COLUMN <type>` below is right for the two key columns — they\n // are NOT NULL by the composite primary key and have no default —\n // and wrong for everything else: it would drop a `defaultValue`, and\n // it would either omit a NOT NULL the collection declared or apply\n // one to a junction that already holds rows without a value to\n // backfill them. `planColumn` is the one place that decides which of\n // those is safe, and it reports the constraint it withheld.\n if (column.source.kind === \"property\") {\n planColumn(table, column);\n continue;\n }\n // A key column whose type is not its endpoint's key type is a\n // foreign key that can never be added (42804) — said, like any\n // other column's drift, rather than failed on every boot.\n reportTypeDrift(table, column);\n addColumn(table, column.column, renderPgType(column.type));\n }\n }\n\n // 3c. The columns relation and reference properties own.\n for (const table of collectionTables) {\n for (const column of table.columns) {\n if (column.source.kind !== \"relation\" && column.source.kind !== \"reference\") continue;\n // A declared property already emits this column (an explicit\n // `postId` beside the `belongsTo` that uses it); the relation\n // contributes only the constraint, below.\n if (column.columnOwnedByProperty) continue;\n // A reference that is part of a composite key was created with\n // the table, in step 2.\n if (isKeyColumn(table, column)) continue;\n if (renameLegacyColumn(table, column)) continue;\n planColumn(table, column);\n }\n }\n\n // 4. Foreign keys, last: the tables and columns on both ends have to exist\n // first, and a constraint is the one thing here that can fail on data\n // rather than on schema, so nothing else depends on it.\n const knownConstraints = existing.constraints ?? new Set<string>();\n const plannedConstraints = new Set<string>();\n for (const table of [...collectionTables, ...junctionTables]) {\n for (const column of table.columns) {\n const fk = column.foreignKey;\n if (!fk) continue;\n const name = `${fk.schema}.${fk.table}.${fk.constraintName}`;\n if (knownConstraints.has(name) || plannedConstraints.has(name)) continue;\n plannedConstraints.add(name);\n actions.push({ kind: \"add-constraint\", target: name, sql: `${fk.sql};` });\n }\n }\n\n // 5. Indexes, after everything — the column has to exist, and this is the\n // one step that runs against a populated table for real work.\n //\n // CONCURRENTLY: a plain CREATE INDEX takes a lock that blocks writes for\n // the duration of the build, which on a live table is an outage. Each\n // statement here is issued on its own, outside any transaction, which is\n // the condition CONCURRENTLY requires.\n //\n // ...and only on a live table. It is withheld for a table this same plan\n // is creating: there are no rows to build from and no writer to block, so\n // the lock CONCURRENTLY avoids is a lock nobody would have taken. Worth\n // withholding rather than merely harmless, because CONCURRENTLY is the\n // one index form Postgres refuses inside a transaction block.\n const concurrent = (schema: string, table: string): boolean => !created.has(`${schema}.${table}`);\n // An index already in the catalogue under its name is not planned:\n // `IF NOT EXISTS` would skip it by that same name, so the outcome is the\n // same — minus a lock on the table to find that out, and minus a change\n // reported on a database that has none.\n const indexExists = (schema: string, name: string | undefined): boolean =>\n name !== undefined && existing.indexes?.has(`${schema}.${name}`) === true;\n // ...except on a table that already exists, where an index goes to the\n // builder instead (`deferredIndexes`, see `DeferredIndexBuild`): a\n // derived foreign-key index always, and under `deferLiveIndexes` every\n // other kind too. The builder also repairs the one case `IF NOT EXISTS`\n // cannot see — an index that is there by name and INVALID, because a\n // concurrent build of it was cancelled — so it is planned again.\n const deferredIndexes: DeferredIndexBuild[] = [];\n const toBuilder = (schema: string, table: string, derived: boolean): boolean =>\n concurrent(schema, table) && (derived || options.deferLiveIndexes === true);\n const deferIndex = (build: Omit<DeferredIndexBuild, \"invalid\">): void => {\n const invalid = existing.invalidIndexes?.has(`${build.schema}.${build.indexName}`) === true;\n if (indexExists(build.schema, build.indexName) && !invalid) return;\n deferredIndexes.push({ ...build, invalid });\n };\n /** A search or vector statement in its concurrent form, or undefined if it has no plain `CREATE INDEX IF NOT EXISTS`. */\n const concurrentForm = (statement: string): string | undefined => {\n const rewritten = statement.replace(\"CREATE INDEX IF NOT EXISTS\", \"CREATE INDEX CONCURRENTLY IF NOT EXISTS\");\n return rewritten === statement ? undefined : rewritten;\n };\n for (const table of collectionTables) {\n if (!table.search) continue;\n const { schema, table: tableName } = table.search;\n for (const statement of searchIndexStatements(table.search)) {\n const name = indexNameOf(statement);\n const sql = concurrentForm(statement);\n if (name !== undefined && sql !== undefined && toBuilder(schema, tableName, false)) {\n deferIndex({ schema, table: tableName, indexName: name, sql });\n continue;\n }\n if (indexExists(table.schema, name)) continue;\n actions.push({\n kind: \"create-index\",\n target: table.qualified,\n sql: concurrent(table.schema, table.table)\n ? statement.replace(\"CREATE INDEX IF NOT EXISTS\", \"CREATE INDEX CONCURRENTLY IF NOT EXISTS\")\n : statement\n });\n }\n }\n\n // ANN indexes for vector columns, on the same terms. A column too wide\n // for pgvector to index is reported, not planned — silence there would\n // read as \"indexed\" to anyone watching the boot.\n const vectorIndexSkipped: SkippedVectorIndex[] = [];\n for (const table of collectionTables) {\n if (!table.vector) continue;\n for (const spec of table.vector.specs) {\n const sql = concurrentForm(vectorIndexStatement(spec));\n if (sql !== undefined && toBuilder(spec.schema, spec.table, false)) {\n deferIndex({ schema: spec.schema, table: spec.table, indexName: spec.indexName, sql });\n continue;\n }\n if (indexExists(spec.schema, spec.indexName)) continue;\n actions.push({\n kind: \"create-index\",\n target: `${spec.schema}.${spec.table}`,\n sql: concurrent(spec.schema, spec.table)\n ? vectorIndexStatement(spec).replace(\"CREATE INDEX IF NOT EXISTS\", \"CREATE INDEX CONCURRENTLY IF NOT EXISTS\")\n : vectorIndexStatement(spec)\n });\n }\n vectorIndexSkipped.push(...table.vector.skipped);\n }\n\n // Declared indexes, on exactly the same terms. Boot has to emit these,\n // not just `db push`: the managed runtime provisions at boot and never\n // runs a push, so a push-only index would simply not exist there — and\n // nothing would say so. `contracts/derived-names.txt` states the rule\n // (\"Both, or it is a bug\") and the gate enforces it.\n //\n // `concurrently` is a parameter rather than a string replacement on the\n // rendered SQL: the `.replace(…)` above silently does nothing for a\n // UNIQUE index, whose text is `CREATE UNIQUE INDEX …`.\n //\n // The foreign-key indexes the plan derives go through here too, and on a\n // table that already exists they go to the builder whoever plans them\n // (see `toBuilder`). A junction table carries one — its target column —\n // which is why this walks both kinds of table.\n for (const spec of sortIndexSpecs([...collectionTables, ...junctionTables].flatMap(t => t.indexes))) {\n if (toBuilder(spec.schema, spec.table, spec.derived === \"foreign-key\")) {\n deferIndex({\n schema: spec.schema,\n table: spec.table,\n indexName: spec.indexName,\n sql: collectionIndexStatement(spec, { concurrently: true, ifNotExists: true }),\n ...(spec.unique ? { unique: true } : {})\n });\n continue;\n }\n if (indexExists(spec.schema, spec.indexName)) continue;\n actions.push({\n kind: \"create-index\",\n target: `${spec.schema}.${spec.table}`,\n sql: collectionIndexStatement(spec, {\n concurrently: concurrent(spec.schema, spec.table),\n ifNotExists: true\n })\n });\n }\n\n // 6. `autoValue: \"on_update\"` triggers. After the column, and idempotent by\n // DROP-then-CREATE rather than `CREATE OR REPLACE TRIGGER`, which exists\n // only on Postgres 14+.\n for (const table of collectionTables) {\n for (const trigger of table.triggers) {\n // Named after its table and column, so a trigger already in the\n // catalogue is this one — re-issuing it every boot would work and\n // would report a change on a database that has none.\n if (existing.triggers?.has(`${table.qualified}.${trigger.name}`)) continue;\n for (const statement of triggerStatements(trigger)) {\n actions.push({\n kind: \"create-trigger\",\n target: `${table.qualified}.${trigger.name}`,\n sql: statement\n });\n }\n }\n }\n\n // A column the database still requires that no property declares any more.\n //\n // Computed last, over the same live snapshot the rest of the plan read, and\n // only for tables this run did not create — a table created here has exactly\n // the columns the collection asked for, so there is nothing to orphan.\n //\n // Every element of the test matters. NOT NULL, because a nullable leftover\n // accepts a write and is merely untidy. No DEFAULT, because a leftover with\n // one is filled in for you. Not declared, because that is what makes it\n // unreachable — the author has no field to send.\n const orphanedRequiredColumns: OrphanedRequiredColumn[] = [];\n if (existing.notNullColumns && existing.columnDefaults) {\n for (const table of collectionTables) {\n const live = existing.tables.get(table.qualified);\n if (!live || created.has(table.qualified)) continue;\n const declared = new Set<string>();\n for (const column of table.columns) {\n declared.add(column.column);\n if (column.legacyColumn) declared.add(column.legacyColumn);\n }\n for (const column of live) {\n const key = `${table.qualified}.${column}`;\n if (declared.has(column)) continue;\n if (!existing.notNullColumns.has(key)) continue;\n if (existing.columnDefaults.has(key)) continue;\n orphanedRequiredColumns.push({ table: table.qualified, column, slug: table.slug! });\n }\n }\n }\n\n return {\n actions,\n statements: actions.map(a => a.sql),\n legacyForeignKeys,\n searchDrift,\n searchAdopted,\n vectorIndexSkipped,\n withheldConstraints,\n columnTypeDrift,\n orphanedRequiredColumns,\n deferredIndexes\n };\n}\n\n/** What a `CREATE FUNCTION` statement is called, for the action log. */\nconst functionTarget = (statement: string): string => {\n if (statement.includes(\"set_updated_at\")) return SET_UPDATED_AT_FN;\n return statement.includes(\"unaccent\") ? SEARCH_UNACCENT_FN : SEARCH_TEXT_FN;\n};\n","/**\n * Building the indexes a live table is missing — or holds INVALID — without\n * holding anything up: the derived foreign-key indexes, and the declared,\n * search and vector ones the boot-time ensure finds missing on a table that\n * already exists.\n *\n * ## Why not a boot action like an index on a new table\n *\n * A table that already exists may hold millions of rows, and an index over\n * them takes minutes to build. Boot-ensure's actions run before the server\n * listens, so an index planned there is minutes of a deployment not serving —\n * on the first boot after an upgrade that adds one to every `belongsTo` in the\n * project, that is every large table at once. So these are planned apart\n * (`DeferredIndexBuild`) and built here, after the boot, one at a time. A\n * UNIQUE one is the exception: `ensureCollectionTables` builds it here too, but\n * before it returns.\n *\n * ## The build\n *\n * `CREATE INDEX CONCURRENTLY`, outside any transaction (Postgres refuses it\n * inside one), on a connection of its own with `statement_timeout` lifted: the\n * pool's 30 s would cancel any build worth deferring. `CONCURRENTLY` takes\n * `SHARE UPDATE EXCLUSIVE`, which conflicts with no read and no write — only\n * with other DDL, `VACUUM` and `ANALYZE` — so live traffic never queues behind\n * it, however long it runs.\n *\n * The boot's lock budget still applies, to the one wait that matters: getting\n * the table at all. A table something else holds — another instance's build,\n * an `ALTER TABLE`, a `VACUUM FULL` — is probed for `BOOT_LOCK_TIMEOUT_MS` at a\n * time within the boot's retry budget, and left for the next boot when it\n * stays held. Once the build has the table, it waits for the transactions\n * already running against it with no deadline: a timeout there would only turn\n * a slow build into a failed one.\n *\n * ## The husk a failed build leaves\n *\n * A cancelled `CONCURRENTLY` — a timeout, a killed process, a deploy that\n * replaced the pod mid-build, two instances racing on one name — leaves the\n * index behind marked `indisvalid = false`: maintained on every write, used by\n * no query. And `IF NOT EXISTS` is a *name* check, so every later attempt\n * skips it and reports success. This reads `pg_index` instead: an invalid index\n * under our name is dropped (`DROP INDEX CONCURRENTLY`) and built again, once.\n * One that another backend is still building (`pg_stat_progress_create_index`)\n * is left to it.\n *\n * Nothing here is fatal. A failure is logged with the index named and the\n * reason, and the next boot plans the index again.\n */\nimport type { Pool, QueryConfig, QueryResultRow } from \"pg\";\nimport { logger } from \"@rebasepro/server\";\nimport { assertSafeIdentifier, type DeferredIndexBuild } from \"./plan/diff-plan\";\nimport { quoteSqlLiteral } from \"./plan/plan-schema\";\nimport { extractPgError } from \"../utils/pg-error-utils\";\nimport {\n atomicBatch,\n BOOT_LOCK_RETRY_BUDGET_MS,\n isLockTimeout,\n isMultiStatementRefusal,\n resolveBootLockOptions,\n sleep,\n type BootLockOptions\n} from \"./boot-ddl\";\n\n/**\n * A connection the builder may hold for as long as an index takes.\n *\n * `dedicated` says whether consecutive queries reach the same backend. Only\n * then can a session setting be relied on — and be reset afterwards: on a\n * pool, `SET statement_timeout = 0` would land on whichever connection served\n * it and stay there for the next request to inherit.\n */\nexport interface IndexBuildSession {\n query<T = unknown>(sql: string): Promise<{ rows: T[] }>;\n readonly dedicated: boolean;\n /** Hand the connection back. Called once, after the last index. */\n release(): void | Promise<void>;\n}\n\nexport type OpenIndexBuildSession = () => Promise<IndexBuildSession>;\n\n/** A client-side read timeout no index build reaches. A pool's is 60 s. */\nconst INDEX_BUILD_READ_TIMEOUT_MS = 24 * 60 * 60 * 1000;\n\n/** A `pg.Pool` — what `connect()` checks a client out of — and not a `pg.Client`, whose `connect()` opens a socket. */\nexport const isPgPool = (value: unknown): value is Pick<Pool, \"connect\" | \"totalCount\"> =>\n typeof value === \"object\" && value !== null && \"connect\" in value && typeof value.connect === \"function\"\n && \"totalCount\" in value;\n\n/**\n * Sessions checked out of a `pg.Pool`, one connection each.\n *\n * Its own connection rather than the pool's next free one, because a build\n * has to outlive both of a pool's timeouts: the server-side\n * `statement_timeout` (30 s on this framework's pools), which the builder\n * lifts for the session — something it may only do on a connection nobody\n * else is handed until it is reset — and the client-side read timeout, which\n * is lifted here per query.\n */\nexport const poolIndexBuildSession = (pool: Pick<Pool, \"connect\">): OpenIndexBuildSession => async () => {\n const client = await pool.connect();\n return {\n dedicated: true,\n async query<T>(text: string): Promise<{ rows: T[] }> {\n const config: QueryConfig & { query_timeout: number } = { text, query_timeout: INDEX_BUILD_READ_TIMEOUT_MS };\n const result = await client.query<T & QueryResultRow>(config);\n return { rows: result.rows };\n },\n release: () => client.release()\n };\n};\n\n/**\n * A session on a connection opened for it, from a URL — for a pool behind a\n * transaction-mode pooler, where \"the pool's next connection\" is not one\n * backend: the pooler hands each statement whatever server connection is\n * free, so a session advisory lock and `SET statement_timeout = 0` would land\n * on one and the `CREATE INDEX` run on another. The URL must name the\n * database itself (`DATABASE_DIRECT_URL`). Ended, not released, when done.\n */\nexport const clientIndexBuildSession = (connectionString: string): OpenIndexBuildSession => async () => {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString, connectionTimeoutMillis: 10_000 });\n // A connection dropped mid-build fails the query in progress; a stray\n // error event after that must not take the process down.\n client.on(\"error\", () => undefined);\n await client.connect();\n return {\n dedicated: true,\n async query<T>(text: string): Promise<{ rows: T[] }> {\n const config: QueryConfig & { query_timeout: number } = { text, query_timeout: INDEX_BUILD_READ_TIMEOUT_MS };\n const result = await client.query<T & QueryResultRow>(config);\n return { rows: result.rows };\n },\n release: () => client.end().catch(() => undefined)\n };\n};\n\nexport interface DeferredIndexOptions extends BootLockOptions {\n /** Progress, one line per index. Failures are also `logger.warn`ed. */\n log?: (message: string) => void;\n /** Checked between indexes; once true, nothing further is started. */\n cancelled?: () => boolean;\n}\n\nexport interface DeferredIndexOutcome {\n /** `schema.index` this run built. */\n built: string[];\n /** Left alone, and why — already valid, or another instance is on it. */\n skipped: { index: string; reason: string }[];\n /** Not built. Logged; the next boot plans them again. */\n failed: { index: string; error: string }[];\n}\n\n/** What the catalogue says about one index name. `valid` is null when it does not exist. */\ninterface IndexState {\n valid: boolean | null;\n /** Another backend is running `CREATE INDEX` on the index's table right now. */\n building: boolean;\n}\n\n/** `42P01 undefined_table` — `pg_stat_progress_create_index` before Postgres 12. */\nconst isUndefinedTable = (err: unknown): boolean => extractPgError(err)?.code === \"42P01\";\n\n/** `25001 active_sql_transaction` — `CONCURRENTLY` on a connection inside a transaction block. */\nconst isTransactionBlockRefusal = (err: unknown): boolean => extractPgError(err)?.code === \"25001\";\n\n/**\n * The rows themselves violate a UNIQUE index being built: `23505` naming the\n * index (a lost catalogue race names a `pg_` index instead). Building it again\n * would only fail again, so it is not retried.\n */\nconst isDuplicateRows = (err: unknown, index: DeferredIndexBuild): boolean => {\n const pg = extractPgError(err);\n return pg?.code === \"23505\" && (pg.constraint === index.indexName || /could not create unique index/i.test(pg.message));\n};\n\nconst CONCURRENTLY_RE = /\\sCONCURRENTLY\\s/i;\n\n/** Why an index is skipped while a build of another index holds its table. */\nexport const TABLE_BUSY_REASON = \"another index on the table is being built\";\n\n/**\n * Run a `CONCURRENTLY` statement — or its plain form, when the connection\n * turns out to be inside a transaction block. Only a shared handle can be: an\n * application that builds its own adapter may hand over a connection already\n * in one. The plain form is always accepted and takes a write lock for the\n * build, which is the cost of getting the index at all — the same fallback the\n * ensure's own index actions have.\n */\nasync function runConcurrently(session: IndexBuildSession, sql: string, qualified: string): Promise<void> {\n try {\n await session.query(sql);\n } catch (err) {\n if (!isTransactionBlockRefusal(err) || !CONCURRENTLY_RE.test(sql)) throw err;\n logger.warn(\n `[schema] ${qualified}: this connection is inside a transaction, so the index is built with a write ` +\n \"lock rather than concurrently. Writes to the table block until it finishes.\"\n );\n await session.query(sql.replace(CONCURRENTLY_RE, \" \"));\n }\n}\n\nasync function readIndexState(session: IndexBuildSession, index: DeferredIndexBuild): Promise<IndexState> {\n const schema = quoteSqlLiteral(index.schema);\n const name = quoteSqlLiteral(index.indexName);\n const { rows } = await session.query<{ valid: boolean | null }>(\n `SELECT i.indisvalid AS valid\n FROM pg_index i\n JOIN pg_class c ON c.oid = i.indexrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ${schema} AND c.relname = ${name}`\n );\n const valid = rows.length === 0 ? null : rows[0].valid === true;\n if (valid !== false) return { valid, building: false };\n // Invalid is also what an index looks like *while* it is being built\n // concurrently, so before treating it as a husk, ask whether anyone is\n // building on that table now — another instance on a shared handle, or a\n // person with psql. Our own backend is excluded: this session runs one\n // statement at a time, so a row for it is a stale read. With no progress\n // view (Postgres < 12) the answer is \"no\", and dropping an in-flight\n // build is no worse than the husk it would otherwise leave.\n return { valid, building: await tableIsBeingIndexed(session, index) };\n}\n\n/**\n * Wait, within the boot's lock budget, until the table's lock is free.\n *\n * A probe rather than a `lock_timeout` on the build itself: the build waits on\n * lock *queues* in three phases, and only the first — getting the table — is\n * a wait worth bounding. The other two wait for transactions that were\n * already running, which block nobody while they run and must simply be let\n * finish. `true` when the table was free (or cannot be probed on this\n * handle), `false` when something held it for the whole budget.\n */\nasync function tableLockIsFree(\n session: IndexBuildSession,\n index: DeferredIndexBuild,\n options: DeferredIndexOptions\n): Promise<boolean> {\n const lock = resolveBootLockOptions(options);\n const probe = atomicBatch(\n [`LOCK TABLE \"${index.schema}\".\"${index.table}\" IN SHARE UPDATE EXCLUSIVE MODE`],\n lock.lockTimeoutMs\n );\n const deadline = Date.now() + (options.retryBudgetMs ?? BOOT_LOCK_RETRY_BUDGET_MS);\n for (let round = 1; ; round++) {\n try {\n await session.query(probe);\n return true;\n } catch (err) {\n // A handle that speaks only the extended protocol cannot send the\n // probe. Not knowing is not a reason to skip the index.\n if (isMultiStatementRefusal(err)) return true;\n if (!isLockTimeout(err)) throw err;\n if (round >= lock.attempts || Date.now() >= deadline) return false;\n await sleep(Math.min(lock.backoffMs(round), Math.max(0, deadline - Date.now())));\n }\n }\n}\n\n/** Whether another backend is running `CREATE INDEX` on the index's table right now. */\nasync function tableIsBeingIndexed(session: IndexBuildSession, index: DeferredIndexBuild): Promise<boolean> {\n const table = quoteSqlLiteral(`\"${index.schema}\".\"${index.table}\"`);\n try {\n const { rows } = await session.query<{ building: boolean }>(\n `SELECT EXISTS (\n SELECT 1 FROM pg_stat_progress_create_index\n WHERE relid = to_regclass(${table}) AND pid <> pg_backend_pid()\n ) AS building`\n );\n return rows[0]?.building === true;\n } catch (err) {\n if (isUndefinedTable(err)) return false;\n throw err;\n }\n}\n\n/**\n * The advisory-lock key one index is claimed under, across every instance.\n *\n * Without a claim, instances booting together all issue the same\n * `CREATE INDEX CONCURRENTLY`: one wins, the others skip by name — reporting\n * success while the winner is still building — or wait on each other's\n * transactions until Postgres breaks the deadlock by cancelling one, which\n * leaves a husk. With it, one instance builds and the rest step aside.\n */\nconst claimKey = (index: DeferredIndexBuild): string =>\n `hashtext(${quoteSqlLiteral(`rebase_fk_index:${index.schema}.${index.indexName}`)})`;\n\n/**\n * Build one index under its claim — session-level, so only on a connection\n * of our own. On a shared handle the claim could be taken on one backend and\n * released on another, so there is none, and concurrent instances fall back\n * on the state checks below.\n */\nasync function buildClaimed(\n session: IndexBuildSession,\n index: DeferredIndexBuild,\n options: DeferredIndexOptions,\n outcome: DeferredIndexOutcome\n): Promise<void> {\n if (!session.dedicated) return buildOne(session, index, options, outcome);\n const { rows } = await session.query<{ claimed: boolean }>(`SELECT pg_try_advisory_lock(${claimKey(index)}) AS claimed`);\n if (rows[0]?.claimed !== true) {\n outcome.skipped.push({ index: `${index.schema}.${index.indexName}`, reason: \"another instance is building it\" });\n options.log?.(`${index.schema}.${index.indexName}: another instance is building it — leaving it to that one`);\n return;\n }\n try {\n await buildOne(session, index, options, outcome);\n } finally {\n await session.query(`SELECT pg_advisory_unlock(${claimKey(index)})`);\n }\n}\n\n/** One index, from whatever state it is in to valid — or a reason it is not. */\nasync function buildOne(\n session: IndexBuildSession,\n index: DeferredIndexBuild,\n options: DeferredIndexOptions,\n outcome: DeferredIndexOutcome\n): Promise<void> {\n const qualified = `${index.schema}.${index.indexName}`;\n const target = `\"${index.schema}\".\"${index.indexName}\"`;\n const say = (message: string): void => options.log?.(message);\n\n // Two attempts: the build, and one rebuild if the first leaves a husk.\n for (let attempt = 1; attempt <= 2; attempt++) {\n const before = await readIndexState(session, index);\n if (before.valid === true) {\n if (attempt === 1) outcome.skipped.push({ index: qualified, reason: \"already built\" });\n else outcome.built.push(qualified);\n return;\n }\n if (before.building) {\n outcome.skipped.push({ index: qualified, reason: \"another instance is building it\" });\n say(`${qualified}: another instance is building it — leaving it to that one`);\n return;\n }\n if (!await tableLockIsFree(session, index, options)) {\n // Another instance building a different index on the same table\n // holds exactly this lock, for as long as its build takes. That\n // one builds this index next; nothing is wrong.\n if (await tableIsBeingIndexed(session, index)) {\n outcome.skipped.push({ index: qualified, reason: TABLE_BUSY_REASON });\n say(`${qualified}: another index on \"${index.schema}\".\"${index.table}\" is being built — leaving it for now`);\n return;\n }\n outcome.failed.push({\n index: qualified,\n error: `\"${index.schema}\".\"${index.table}\" stayed locked by another session for the whole lock ` +\n \"budget (an index build, a VACUUM, an ALTER TABLE). Nothing was changed; the next boot tries again.\"\n });\n return;\n }\n if (before.valid === false) {\n say(`${qualified}: an earlier build left it INVALID — dropping it to build it again`);\n await runConcurrently(session, `DROP INDEX CONCURRENTLY IF EXISTS ${target};`, qualified);\n }\n\n const started = Date.now();\n say(`${qualified}: building on \"${index.schema}\".\"${index.table}\"…`);\n try {\n await runConcurrently(session, index.sql, qualified);\n } catch (err) {\n // Whatever went wrong, what matters is the state it left, and a\n // peer is the usual cause: two instances issuing the same `CREATE`\n // at the same instant, where the loser fails on a catalogue key,\n // or two concurrent builds on one table each waiting for the\n // other's transaction, where Postgres kills one (40P01).\n const after = await readIndexState(session, index).catch(() => undefined);\n if (after?.valid === true || after?.building) {\n outcome.skipped.push({ index: qualified, reason: \"another instance built it\" });\n return;\n }\n // A build that died part-way leaves a husk, which the next round\n // drops and builds again — once. Not when the rows themselves are\n // what a UNIQUE index refuses: that fails again, as long again.\n if (after?.valid === false && attempt === 1 && !isDuplicateRows(err, index)) {\n say(`${qualified}: the build failed (${describe(err)}); retrying once`);\n continue;\n }\n outcome.failed.push({ index: qualified, error: describe(err) });\n return;\n }\n\n const after = await readIndexState(session, index);\n if (after.valid === true) {\n outcome.built.push(qualified);\n say(`${qualified}: built in ${((Date.now() - started) / 1000).toFixed(1)} s`);\n return;\n }\n if (after.building) {\n outcome.skipped.push({ index: qualified, reason: \"another instance is building it\" });\n return;\n }\n if (attempt === 2) {\n outcome.failed.push({ index: qualified, error: \"left INVALID by two builds in a row\" });\n return;\n }\n }\n}\n\nconst describe = (err: unknown): string => {\n const pg = extractPgError(err);\n if (pg) return pg.code ? `${pg.message} [${pg.code}]` : pg.message;\n return err instanceof Error ? err.message : String(err);\n};\n\n/**\n * Build every deferred index, one at a time, on one connection.\n *\n * Never throws for an index: each failure is recorded and the next one is\n * attempted. Throws only when no connection can be had at all.\n */\nexport async function buildDeferredIndexes(\n openSession: OpenIndexBuildSession,\n indexes: readonly DeferredIndexBuild[],\n options: DeferredIndexOptions = {}\n): Promise<DeferredIndexOutcome> {\n const outcome: DeferredIndexOutcome = { built: [], skipped: [], failed: [] };\n if (indexes.length === 0) return outcome;\n for (const index of indexes) {\n assertSafeIdentifier(index.schema, \"schema name\");\n assertSafeIdentifier(index.table, \"table name\");\n assertSafeIdentifier(index.indexName, \"index name\");\n }\n\n const session = await openSession();\n try {\n // Only on a connection of our own — see `IndexBuildSession.dedicated`.\n // `lock_timeout` stays at the session default: the probe above is\n // where the lock budget applies.\n if (session.dedicated) await session.query(\"SET statement_timeout = 0\");\n for (const index of indexes) {\n if (options.cancelled?.()) break;\n try {\n await buildClaimed(session, index, options, outcome);\n } catch (err) {\n outcome.failed.push({ index: `${index.schema}.${index.indexName}`, error: describe(err) });\n }\n }\n } finally {\n try {\n if (session.dedicated) await session.query(\"RESET statement_timeout\");\n } finally {\n await session.release();\n }\n }\n\n for (const failure of outcome.failed) {\n logger.warn(\n `[schema] Index ${failure.index} was not built: ${failure.error}. ` +\n \"Queries it would serve scan the table until it is; the next boot tries again.\"\n );\n }\n return outcome;\n}\n\n/** Every deferred build in this process, chained so they run one at a time. */\nlet queue: Promise<unknown> = Promise.resolve();\n\n/**\n * Start {@link buildDeferredIndexes} later, in the background.\n *\n * `start()` begins it after `delayMs`; the fallback timer begins it after\n * `fallbackMs` if nothing calls `start()` — so a process whose boot never\n * reaches the step that would have started it still builds. Both timers are\n * unref'd: a pending build never keeps a process alive, and a process that\n * exits mid-build leaves a husk the next boot rebuilds.\n */\nexport interface ScheduledIndexBuild {\n /** Begin after the schedule's `delayMs`, instead of waiting for the fallback timer. */\n start(): void;\n /** Start nothing further. An index already building runs to completion. */\n cancel(): void;\n /** Settles when the run ends — `undefined` if it never ran or could not open a connection. */\n done: Promise<DeferredIndexOutcome | undefined>;\n}\n\nexport function scheduleDeferredIndexBuild(\n openSession: OpenIndexBuildSession,\n indexes: readonly DeferredIndexBuild[],\n options: DeferredIndexOptions & { delayMs?: number; fallbackMs?: number } = {}\n): ScheduledIndexBuild {\n let cancelled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let resolveDone!: (outcome: DeferredIndexOutcome | undefined) => void;\n const done = new Promise<DeferredIndexOutcome | undefined>(resolve => { resolveDone = resolve; });\n\n const run = (): void => {\n if (timer) clearTimeout(timer);\n timer = undefined;\n if (cancelled) {\n resolveDone(undefined);\n return;\n }\n const job = queue.then(async () => {\n if (cancelled) return undefined;\n logger.info(\n `[schema] Building ${indexes.length} index(es) in the background, one at a time ` +\n \"(CREATE INDEX CONCURRENTLY — reads and writes are not blocked).\"\n );\n return buildDeferredIndexes(openSession, indexes, { ...options, cancelled: () => cancelled });\n }).catch((err: unknown) => {\n logger.warn(`[schema] Indexes were not built this boot: ${describe(err)}`);\n return undefined;\n });\n queue = job;\n void job.then(resolveDone);\n };\n\n const arm = (ms: number): void => {\n if (timer) clearTimeout(timer);\n timer = setTimeout(run, ms);\n timer.unref?.();\n };\n arm(options.fallbackMs ?? 60_000);\n\n return {\n start: () => {\n if (cancelled || timer === undefined) return;\n arm(options.delayMs ?? 0);\n },\n cancel: () => {\n cancelled = true;\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n resolveDone(undefined);\n }\n },\n done\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8DA,IAAM,WAAmC;CAErC,MAAM;CAAU,UAAU;CAC1B,MAAM;CAAU,KAAK;CAAU,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AExC;GACA,OAAO,qBAAqB,aAAa,SAAS;IAAE,GAAG;IAAS,iBAAiB;GAAU,CAAC;EAChG,CAAC,CAAC,CAAC,OAAO,QAAiB;GACvB,OAAO,KAAK,8CAA8C,SAAS,GAAG,GAAG;EAE7E,CAAC;EACD,QAAQ;EACR,IAAS,KAAK,WAAW;CAC7B;CAEA,MAAM,OAAO,OAAqB;EAC9B,IAAI,OAAO,aAAa,KAAK;EAC7B,QAAQ,WAAW,KAAK,EAAE;EAC1B,MAAM,QAAQ;CAClB;CACA,IAAI,QAAQ,cAAc,GAAM;CAEhC,OAAO;EACH,aAAa;GACT,IAAI,aAAa,UAAU,KAAA,GAAW;GACtC,IAAI,QAAQ,WAAW,CAAC;EAC5B;EACA,cAAc;GACV,YAAY;GACZ,IAAI,OAAO;IACP,aAAa,KAAK;IAClB,QAAQ,KAAA;IACR,YAAY,KAAA,CAAS;GACzB;EACJ;EACA;CACJ;AACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"ensure-collection-tables-BK--gDo6.js","names":[],"sources":["../src/schema/ensure-collection-tables.ts"],"sourcesContent":["/**\n * Applying a schema plan to a database that is already running.\n *\n * ## What this module is\n *\n * A managed runtime boots someone else's compiled project against a database it\n * has never seen. Auth tables are ensured at boot already, but collection tables\n * were not created by anything: the platform ran the app and every `/api/data/*`\n * request answered 500 on a missing relation. `rebase db push` cannot help — it\n * is an Atlas-driven CLI command, and the runtime image ships no CLI.\n *\n * Two halves, and only one of them is here. *What the collections ask for* is\n * `schema/plan/plan-schema.ts`, shared with `db push` and the generated Drizzle\n * file; *what the database already has, and which of those statements are safe\n * to run against it* is `schema/plan/diff-plan.ts`. This module reads the\n * catalogue, runs the statements, and reports what happened.\n *\n * ## Why additive-only, forever\n *\n * This runs unattended, against a database with customers' data in it, with no\n * human reading a diff. So it may only ever do things that cannot lose data.\n * See `diff-plan.ts` for the whole of that argument.\n */\nimport {\n declaredDatabaseExtensions,\n REBASE_SCHEMA,\n type CollectionConfig\n} from \"@rebasepro/types\";\nimport { getTableName, relationalCollections } from \"@rebasepro/common\";\nimport { logger, isConcurrentDdlRace, isDuplicateObjectRace } from \"@rebasepro/server\";\nimport { SEARCH_STAMP_PREFIX } from \"./search-column\";\nimport { vectorExtensionHint } from \"./vector-index\";\nimport { planJunctionTables, quoteSqlLiteral } from \"./generate-postgres-ddl-logic\";\nimport { quoteRelation } from \"./introspect-db-queries\";\nimport { planSchema } from \"./plan/plan-schema\";\nimport { renderViewsDdl } from \"./plan/render-ddl\";\nimport type { SchemaPlan } from \"./plan/types\";\nimport {\n assertSafeIdentifier,\n describeHelperFunction,\n diffPlanAgainstCatalogue,\n helperFunctionKey,\n HELPER_FUNCTIONS,\n type ConstraintPolicy,\n type DeferredIndexBuild,\n type DiffOptions,\n type EnsureAction,\n type EnsurePlan,\n type ExistingSchema,\n type LegacyForeignKey,\n type OrphanedRequiredColumn,\n type SearchColumnDrift,\n type WithheldConstraint\n} from \"./plan/diff-plan\";\nimport { extractCauseMessage, extractPgError } from \"../utils/pg-error-utils\";\nimport { atomicBatch, isLockTimeout, isMultiStatementRefusal, joinStatements, sleep } from \"./boot-ddl\";\nimport {\n buildDeferredIndexes,\n TABLE_BUSY_REASON,\n type DeferredIndexOutcome,\n type OpenIndexBuildSession\n} from \"./deferred-index-build\";\nimport { columnTypeDriftMessage, type ColumnTypeDrift } from \"./column-type-drift\";\n\nexport type {\n ConstraintPolicy,\n DeferredIndexBuild,\n EnsureAction,\n EnsurePlan,\n ExistingSchema,\n LegacyForeignKey,\n OrphanedRequiredColumn,\n SearchColumnDrift,\n WithheldConstraint\n};\n\n/**\n * The subset of a database handle this needs: run a statement, get rows back.\n *\n * Deliberately parameterless. Everything here is DDL or catalogue reads keyed by\n * schema name, and schema names are identifiers — they cannot be bound as\n * parameters anyway. They are validated by `assertSafeIdentifier` before they\n * reach a statement, so a config that somehow carried a quote is refused rather\n * than concatenated.\n */\nexport interface Queryable {\n query<T = unknown>(sql: string): Promise<{ rows: T[] }>;\n}\n\nexport interface EnsureOptions extends DiffOptions {\n /**\n * Server extensions the project's databases gave Rebase leave to install —\n * `declaredDatabaseExtensions()`. Absent means none, which is a refusal and\n * is the right default for a planner given no configuration at all.\n *\n * Explicit rather than read from the resource registry in here, because the\n * planner is pure and several callers plan against fixtures: reaching for a\n * process-wide registry would make the plan depend on whatever some other\n * module happened to import. `ensureCollectionTables` is the boundary that\n * reads the world.\n */\n databaseExtensions?: readonly string[];\n /**\n * Run each statement that changes an existing table under this\n * `lock_timeout` (ms), retrying a timeout with backoff — see\n * `schema/boot-ddl`. The boot sets it; absent, statements wait on locks for\n * as long as the connection's `statement_timeout` allows, as the live schema\n * editor's confirmed changes do.\n */\n lockTimeoutMs?: number;\n /**\n * Apply the statements that build tables this run creates — and the enum\n * types they use — in transactions of up to {@link NEW_TABLE_BATCH}\n * statements instead of one autocommit each. The boot sets it; see\n * `ensureCollectionTables`.\n */\n batchNewTables?: boolean;\n /**\n * Leave the indexes a live table is missing (or holds INVALID) to the\n * caller, in {@link EnsureOutcome.deferredIndexes}, instead of building\n * them before returning. The boot sets it and builds them in the\n * background once it serves — see `deferred-index-build`. A UNIQUE one is\n * built before returning either way: see {@link DeferredIndexBuild.unique}.\n */\n deferIndexBuilds?: boolean;\n /**\n * The connection those builds run on when they are not deferred. Absent,\n * they share `client` — fine for a small table, and cut short by the\n * pool's `statement_timeout` on a large one, which is why the boot hands\n * over a dedicated connection.\n */\n openIndexBuildSession?: OpenIndexBuildSession;\n}\n\n/**\n * Most statements in one new-table transaction. Bounds how many locks one\n * transaction holds — each new table is several relations (the heap, its TOAST\n * table, its key index) — well inside the default `max_locks_per_transaction`.\n */\nconst NEW_TABLE_BATCH = 100;\n\nexport interface EnsureOutcome extends EnsurePlan {\n /**\n * Actions that could not be applied and are non-fatal by nature.\n *\n * Two kinds qualify. A foreign key can only fail on data that already\n * violates it, and the column it would police exists either way, so the\n * collection still serves; refusing to boot over one would turn a\n * pre-existing data problem into an outage. A column comment is the search\n * fingerprint, which needs table ownership — losing it costs drift\n * detection on the next boot, not the deployment. Both are reported loudly.\n */\n failures: { kind: EnsureAction[\"kind\"]; target: string; error: string }[];\n /**\n * What happened to the indexes built here rather than left to the caller —\n * every one of {@link EnsurePlan.deferredIndexes}, or under\n * `deferIndexBuilds` the UNIQUE ones only; absent when there were none.\n * An index on a table that already exists reports here, not in\n * {@link failures}.\n */\n indexBuilds?: DeferredIndexOutcome;\n}\n\n/** The schema a collection lives in, validated before it reaches any DDL. */\nfunction schemaOf(collection: CollectionConfig): string {\n const schema = (collection as { schema?: string }).schema || \"public\";\n return assertSafeIdentifier(schema, \"schema name\");\n}\n\n/**\n * Decide what to add. Pure — the caller supplies what exists and runs the\n * result.\n *\n * A plan and a diff: the collections are read once, by `planSchema`, into the\n * same {@link SchemaPlan} `db push` renders `schema.sql` from, and the diff\n * subtracts what the database already has. Before that split this function had\n * its own reading of every `Property`, and the audit found twelve places where\n * it disagreed with the two generators — a required `author_id` that was\n * NOT NULL after a push and nullable after a boot among them, on the one path\n * with no developer in the loop.\n */\nexport function planCollectionSchemaEnsure(\n allCollections: CollectionConfig[],\n existing: ExistingSchema,\n options: EnsureOptions = {}\n): EnsurePlan {\n const plan = planSchema(allCollections, { databaseExtensions: options.databaseExtensions });\n return diffPlanAgainstCatalogue(plan, existing, { constraints: options.constraints });\n}\n\nexport interface ReadSchemaOptions {\n /**\n * The existing tables worth probing for rows, given every table's columns.\n *\n * Whether a table holds rows decides one thing: whether a NOT NULL or a\n * UNIQUE can be added with a column *being added* to it. So the boot asks\n * only about tables gaining a column — none at all on a boot that changes\n * nothing — rather than probing every table in the schema, adopted and\n * unmanaged ones included, on every boot. A table that is not probed is\n * reported as holding rows: the answer that never plans a constraint that\n * could fail against data. Absent, every table is probed.\n */\n probeTables?: (tables: ReadonlyMap<string, ReadonlySet<string>>) => Iterable<string>;\n}\n\n/** Read what the database has, for the schemas the collections live in. */\nexport async function readExistingSchema(\n client: Queryable,\n schemas: string[],\n options: ReadSchemaOptions = {}\n): Promise<ExistingSchema> {\n const tables = new Map<string, Set<string>>();\n const enums = new Set<string>();\n if (schemas.length === 0) return { tables, enums };\n\n const inList = schemas\n .map(schema => `'${assertSafeIdentifier(schema, \"schema name\")}'`)\n .join(\", \");\n\n const notNullColumns = new Set<string>();\n // `udt_name` rather than `data_type`: `data_type` collapses every array to\n // the literal string `ARRAY` and every extension type to `USER-DEFINED`,\n // which cannot be compared with anything. `udt_name` names the actual type\n // — `int4`, `jsonb`, `_numeric`, `vector` — which is what the drift check\n // needs.\n const columnTypes = new Map<string, string>();\n // A NOT NULL column that has a DEFAULT is not a problem for a write that\n // omits it, so orphan detection needs the default as well as the nullability\n // — otherwise every `created_at DEFAULT now()` on a table whose collection\n // does not declare it would be reported as a blocker.\n const columnDefaults = new Set<string>();\n const { rows: columns } = await client.query<{\n table_schema: string;\n table_name: string;\n column_name: string;\n is_nullable: string;\n udt_name: string | null;\n column_default: string | null;\n numeric_precision: number | null;\n numeric_scale: number | null;\n }>(\n // `numeric_precision`/`numeric_scale` because `udt_name` is `numeric`\n // for both `NUMERIC` and `NUMERIC(10, 2)`, and a property that declares\n // a precision means it: money stored in an unbounded column keeps the\n // third decimal the rounding was supposed to remove. Only carried for\n // `numeric`, where the modifier changes what a value *is*; a `varchar`\n // width is a limit on the same family and `typesAgree` ignores it.\n `SELECT table_schema, table_name, column_name, is_nullable, udt_name, column_default,\n numeric_precision, numeric_scale\n FROM information_schema.columns\n WHERE table_schema IN (${inList})`\n );\n for (const row of columns) {\n const key = `${row.table_schema}.${row.table_name}`;\n if (!tables.has(key)) tables.set(key, new Set());\n tables.get(key)!.add(row.column_name);\n if (row.is_nullable === \"NO\") notNullColumns.add(`${key}.${row.column_name}`);\n if (row.udt_name) {\n const modifier = row.udt_name === \"numeric\" && row.numeric_precision !== null\n ? `(${row.numeric_precision},${row.numeric_scale ?? 0})`\n : \"\";\n columnTypes.set(`${key}.${row.column_name}`, `${row.udt_name}${modifier}`);\n }\n if (row.column_default !== null) columnDefaults.add(`${key}.${row.column_name}`);\n }\n\n // Trigger names, so `autoValue: \"on_update\"` is installed once rather than\n // re-issued on every boot. `tgisinternal` excludes the ones Postgres itself\n // creates to enforce foreign keys.\n const triggers = new Set<string>();\n const { rows: triggerRows } = await client.query<{ schema: string; table: string; name: string }>(\n `SELECT n.nspname AS schema, c.relname AS table, t.tgname AS name\n FROM pg_trigger t\n JOIN pg_class c ON t.tgrelid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE NOT t.tgisinternal AND n.nspname IN (${inList})`\n );\n for (const row of triggerRows) triggers.add(`${row.schema}.${row.table}.${row.name}`);\n\n // Which tables hold rows. This is the only fact that decides whether a\n // NOT NULL can be added without reading the data, so it is worth a query.\n //\n // `reltuples` would be cheaper and is wrong for this: it is a planner\n // estimate, it is -1 on a table that has never been analyzed, and a table\n // that was full an hour ago still reads as full after a DELETE. A wrong\n // \"empty\" here means a boot that aborts on a constraint violation, so the\n // estimate is not good enough. `EXISTS … LIMIT 1` stops at the first row,\n // which makes the true cost one page read per table.\n //\n // Restricted to ordinary and partitioned tables: `information_schema.columns`\n // also lists views and materialized views, and probing those runs whatever\n // query defines them.\n //\n // Indexes come back from the same read: an index already in the catalogue\n // under its planned name is not planned again (see `diffPlanAgainstCatalogue`).\n const populatedTables = new Set<string>();\n const indexes = new Set<string>();\n const { rows: relations } = await client.query<{ schema: string; name: string; kind: string }>(\n `SELECT n.nspname AS schema, c.relname AS name, c.relkind::text AS kind\n FROM pg_class c\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE c.relkind IN ('r', 'p', 'i', 'I') AND n.nspname IN (${inList})`\n );\n const allRealTables = relations.filter(row => row.kind === \"r\" || row.kind === \"p\");\n for (const row of relations) {\n if (row.kind === \"i\" || row.kind === \"I\") indexes.add(`${row.schema}.${row.name}`);\n }\n // Only the tables the caller will ask about; every other one reads as\n // holding rows — see `ReadSchemaOptions.probeTables`.\n const wanted = options.probeTables ? new Set(options.probeTables(tables)) : undefined;\n const realTables = wanted\n ? allRealTables.filter(row => wanted.has(`${row.schema}.${row.name}`))\n : allRealTables;\n if (wanted) {\n for (const row of allRealTables) {\n const key = `${row.schema}.${row.name}`;\n if (!wanted.has(key)) populatedTables.add(key);\n }\n }\n // The names come from `pg_class`, not from the configuration, so on an\n // adopted database they include tables nobody declared — `2024_archive`,\n // `order-items`, `Sales Data`. Those are quoted, not refused: refusing a\n // name here refuses the boot over a table Rebase will never touch.\n if (realTables.length > 0) {\n const probes = realTables.map(row =>\n `SELECT ${quoteSqlLiteral(`${row.schema}.${row.name}`)} AS key, ` +\n `EXISTS(SELECT 1 FROM ${quoteRelation(row.schema, row.name)} LIMIT 1) AS populated`\n );\n const { rows: populationRows } = await client.query<{ key: string; populated: boolean }>(\n probes.join(\" UNION ALL \")\n );\n for (const row of populationRows) {\n if (row.populated) populatedTables.add(row.key);\n }\n }\n\n const enumValues = new Map<string, string[]>();\n const { rows: enumValueRows } = await client.query<{\n schema: string;\n name: string;\n value: string;\n }>(\n // Ordered by `enumsortorder`, not by label: an enum's order is part of\n // its meaning (it is what `<` compares), and reading it back sorted\n // alphabetically would make a correct type look drifted.\n `SELECT n.nspname AS schema, t.typname AS name, e.enumlabel AS value\n FROM pg_enum e\n JOIN pg_type t ON e.enumtypid = t.oid\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE n.nspname IN (${inList})\n ORDER BY t.typname, e.enumsortorder`\n );\n for (const row of enumValueRows) {\n const key = `${row.schema}.${row.name}`;\n if (!enumValues.has(key)) enumValues.set(key, []);\n enumValues.get(key)!.push(row.value);\n }\n\n const { rows: enumRows } = await client.query<{ schema: string; name: string }>(\n `SELECT n.nspname AS schema, t.typname AS name\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE t.typtype = 'e' AND n.nspname IN (${inList})`\n );\n for (const row of enumRows) enums.add(`${row.schema}.${row.name}`);\n\n // `ADD CONSTRAINT` has no IF NOT EXISTS, so an existing foreign key is\n // skipped by name rather than guarded in SQL.\n const constraints = new Set<string>();\n const { rows: constraintRows } = await client.query<{\n schema: string;\n table: string;\n name: string;\n }>(\n `SELECT n.nspname AS schema, c.relname AS table, con.conname AS name\n FROM pg_constraint con\n JOIN pg_class c ON con.conrelid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n WHERE n.nspname IN (${inList})`\n );\n for (const row of constraintRows) constraints.add(`${row.schema}.${row.table}.${row.name}`);\n\n // Indexes a `CREATE INDEX CONCURRENTLY` left INVALID. They are in\n // `indexes` under their name, so without this a husk reads as built and\n // `IF NOT EXISTS` keeps skipping it — see `deferred-index-build`.\n const invalidIndexes = new Set<string>();\n const { rows: invalidRows } = await client.query<{ schema: string; name: string }>(\n `SELECT n.nspname AS schema, c.relname AS name\n FROM pg_index i\n JOIN pg_class c ON c.oid = i.indexrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE NOT i.indisvalid AND n.nspname IN (${inList})`\n );\n for (const row of invalidRows) invalidIndexes.add(`${row.schema}.${row.name}`);\n\n // Column comments, which is where a generated search column records the\n // expression it was built from. `objsubid > 0` is what makes a row a\n // *column* comment rather than the table's own.\n const columnComments = new Map<string, string>();\n const { rows: commentRows } = await client.query<{\n schema: string;\n table: string;\n column: string;\n comment: string | null;\n }>(\n `SELECT n.nspname AS schema, c.relname AS table, a.attname AS column, d.description AS comment\n FROM pg_description d\n JOIN pg_class c ON d.objoid = c.oid\n JOIN pg_namespace n ON c.relnamespace = n.oid\n JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = d.objsubid\n WHERE d.objsubid > 0 AND n.nspname IN (${inList})`\n );\n for (const row of commentRows) {\n if (row.comment == null) continue;\n columnComments.set(`${row.schema}.${row.table}.${row.column}`, row.comment);\n }\n\n // The helper functions the plan `CREATE OR REPLACE`s, as the catalogue has\n // them, so an unchanged one is not rewritten on every boot. Looked up by\n // qualified name rather than by the schemas read above: `set_updated_at`\n // lives in `rebase`, which is auth's schema and not in that list.\n const functions = new Map<string, string>();\n const helperNames = HELPER_FUNCTIONS\n .map(qualified => qualified.split(\".\"))\n .map(([schema, name]) => `(${quoteSqlLiteral(schema)}, ${quoteSqlLiteral(name)})`)\n .join(\", \");\n const { rows: functionRows } = await client.query<{\n schema: string;\n name: string;\n args: string;\n returns: string;\n language: string;\n volatility: string;\n strict: boolean;\n parallel: string;\n security_definer: boolean;\n leakproof: boolean;\n cost: number | string;\n has_config: boolean;\n body: string;\n }>(\n `SELECT n.nspname AS schema, p.proname AS name, pg_get_function_identity_arguments(p.oid) AS args,\n format_type(p.prorettype, NULL) AS returns, l.lanname AS language,\n p.provolatile::text AS volatility, p.proisstrict AS strict, p.proparallel::text AS parallel,\n p.prosecdef AS security_definer, p.proleakproof AS leakproof, p.procost AS cost,\n p.proconfig IS NOT NULL AS has_config, p.prosrc AS body\n FROM pg_proc p\n JOIN pg_namespace n ON p.pronamespace = n.oid\n JOIN pg_language l ON p.prolang = l.oid\n WHERE (n.nspname, p.proname) IN (${helperNames})`\n );\n for (const row of functionRows) {\n functions.set(helperFunctionKey(row.schema, row.name, row.args), describeHelperFunction({\n returns: row.returns,\n language: row.language,\n volatility: row.volatility,\n strict: row.strict,\n parallel: row.parallel,\n securityDefiner: row.security_definer,\n leakproof: row.leakproof,\n cost: Number(row.cost),\n hasConfig: row.has_config,\n body: row.body\n }));\n }\n\n const extensions = new Set<string>();\n const { rows: extensionRows } = await client.query<{ name: string }>(\"SELECT extname AS name FROM pg_extension\");\n for (const row of extensionRows) extensions.add(row.name);\n\n return {\n tables, enums, constraints, columnComments, enumValues, notNullColumns, populatedTables, columnTypes,\n columnDefaults, triggers, indexes, invalidIndexes, extensions, functions\n };\n}\n\n/**\n * The planned tables that exist and lack at least one planned column — the\n * only ones whose emptiness the diff consults (a NOT NULL or UNIQUE arriving\n * with a new column). A superset, never a subset: a column the plan renames\n * from a legacy name reads as missing here too.\n */\nfunction tablesGainingColumns(plan: SchemaPlan, catalogue: ReadonlyMap<string, ReadonlySet<string>>): string[] {\n const gaining: string[] = [];\n for (const table of plan.tables) {\n const columns = catalogue.get(table.qualified);\n if (columns && table.columns.some(column => !columns.has(column.column))) gaining.push(table.qualified);\n }\n return gaining;\n}\n\n/**\n * What to tell an operator whose `search` block no longer matches its column.\n *\n * Every line here is doing work: naming the collection is not enough, because\n * the symptom (a search that finds nothing) points at the data, not the schema;\n * and the remediation has to be exact, because it is a table rewrite the\n * operator is being asked to schedule rather than discover.\n */\nfunction searchDriftMessage(drift: SearchColumnDrift[]): string {\n const blocks = drift.map(d =>\n ` \"${d.table}\".\"${d.column}\" was generated from a different \\`search\\` block ` +\n `(recorded ${d.found}, current ${d.expected}).\\n` +\n d.rebuild.map(s => ` ${s}`).join(\"\\n\")\n );\n return (\n \"The `search` block changed after its generated column was created, and Postgres cannot alter a \" +\n \"generated expression in place.\\n\" +\n \"Rebase will not rebuild it for you: dropping and re-adding a STORED generated column rewrites the whole \" +\n \"table under an ACCESS EXCLUSIVE lock and rebuilds its GIN index, which is an outage this unattended path \" +\n \"may not schedule on your behalf.\\n\" +\n \"Until it is rebuilt the column keeps indexing the previous fields, weights and language — searches for \" +\n \"anything added since return nothing, which reads from outside as \\\"no such row\\\".\\n\" +\n \"Run these (or revert the block to what the column was built from), then boot again:\\n\" +\n blocks.join(\"\\n\") +\n \"\\n The GIN index is dropped with the column and recreated concurrently on the next boot.\"\n );\n}\n\n\n/**\n * Read what the database looks like, for the schemas a set of collections\n * lives in.\n *\n * The same read `ensureCollectionTables` does at boot, exposed on its own for\n * the callers that want to *plan* against a real database without changing it —\n * the live schema editor, which has to tell somebody what a change would do\n * before they agree to it.\n */\nexport async function readSchemaFactsFor(\n client: Queryable,\n collections: CollectionConfig[]\n): Promise<ExistingSchema> {\n const relational = relationalCollections(collections);\n const junctions = planJunctionTables(relational);\n const schemas = Array.from(new Set([\n ...relational.map(schemaOf),\n ...junctions.map(junction => junction.schema)\n ]));\n // Row probes for the declared tables only: the classifier asks about the\n // collections it is given, never about a table nobody declared.\n const declared = [\n ...relational.map(collection => `${schemaOf(collection)}.${getTableName(collection)}`),\n ...junctions.map(junction => `${junction.schema}.${junction.table}`)\n ];\n return readExistingSchema(client, schemas, { probeTables: () => declared });\n}\n\n/**\n * Bring the database up to date. Returns what it did.\n *\n * Each statement runs on its own rather than in one transaction: they are all\n * independently safe and idempotent, and a single failure (an enum label that\n * cannot be added, say) should not roll back the tables that were created fine.\n * The error is surfaced with the statement that caused it.\n */\nexport async function ensureCollectionTables(\n client: Queryable,\n collections: CollectionConfig[],\n log?: (message: string) => void,\n options: EnsureOptions = {}\n): Promise<EnsureOutcome> {\n // This is the boundary, so this is where the world is read: the planner\n // itself takes the permission as an argument and never reaches for the\n // registry. By the time boot gets here `loadBundleResourceGraph` has\n // evaluated the project's `resources.ts`, so the declarations are there —\n // and a caller that already knows them can still say so.\n const schema = planSchema(collections, {\n databaseExtensions: options.databaseExtensions ?? declaredDatabaseExtensions()\n });\n\n // Junctions live alongside the collections that declare them, so their\n // schema has to be read too — otherwise an existing junction reads as\n // missing and its constraints as unplanned. Taken off the plan, which lists\n // both kinds of table.\n const schemas = Array.from(new Set(schema.tables.map(table => table.schema)));\n for (const name of schemas) {\n assertSafeIdentifier(name, \"schema name\");\n if (name !== \"public\") {\n await client.query(`CREATE SCHEMA IF NOT EXISTS \"${name}\";`);\n }\n }\n // `rebase` is where the `updated_at` trigger's function lives. Every real\n // boot has the schema by the time this runs (auth ensures it first) and\n // `db push` creates it in `schema.sql`, but this path is also driven by the\n // live schema editor and by tests, where \"the function's schema happens to\n // exist already\" is not a thing to rely on. Only when something needs it,\n // so a project with no trigger issues no statement — and not added to the\n // read set: what is *in* `rebase` is auth's business, not this planner's.\n if (schema.tables.some(table => table.triggers.length > 0)) {\n await client.query(`CREATE SCHEMA IF NOT EXISTS \"${REBASE_SCHEMA}\";`);\n }\n\n const existing = await readExistingSchema(client, schemas, {\n probeTables: catalogue => tablesGainingColumns(schema, catalogue)\n });\n // Every index on a table that already exists goes to the index builder,\n // which this function runs or hands to the caller — see `buildIndexes`.\n const plan = diffPlanAgainstCatalogue(schema, existing, { constraints: options.constraints, deferLiveIndexes: true });\n const failures: EnsureOutcome[\"failures\"] = [];\n\n // Reported, not warned: this is a rename the ensure is about to perform, and\n // the operator should be able to see in the log why a column changed name.\n // The interesting case is the one that no longer happens — before this,\n // ensure added the new column empty beside the populated old one, every\n // statement succeeded, and the relation read the empty one.\n for (const legacy of plan.legacyForeignKeys) {\n const message =\n `Renaming \"${legacy.table}\".\"${legacy.legacy}\" to \"${legacy.expected}\". The old name is ` +\n \"the one Rebase derived for this relation before it singularized properly; the column \" +\n \"keeps its data, indexes and constraints. To keep the old name instead, set \" +\n `\\`localKey: \"${legacy.legacy}\"\\` on the relation and this will stop.`;\n logger.info(`[schema] ${message}`);\n log?.(message);\n }\n\n // Before anything is applied: a `search` block that changed after its column\n // was generated cannot be honoured by an additive plan, and serving the old\n // index while the config describes a new one is the silent failure this\n // check exists to end. Refusing is the loud half — boot is fatal on purpose\n // (see `ensureCollectionSchema` in the server's boot) and the message\n // carries the exact statements that resolve it.\n if (plan.searchDrift.length > 0) {\n throw new Error(searchDriftMessage(plan.searchDrift));\n }\n\n // Said once per column, at the moment the stamp is applied: from here on a\n // change is detected, but whether *this* column matches the block it is\n // being stamped with is not knowable — it predates the stamp.\n for (const adopted of plan.searchAdopted) {\n const message =\n `Adopting the existing generated column \"${adopted.table}\".\"${adopted.column}\" and recording what the ` +\n \"current `search` block would generate. Any later change to that block will be detected and refused; a \" +\n \"change made *before* this version was deployed cannot be, so if search has been missing content, \" +\n `rebuild the column once: ALTER TABLE \"${adopted.table.split(\".\").join('\".\"')}\" DROP COLUMN \"${adopted.column}\"; and boot again.`;\n logger.info(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per column, every boot: an unindexed vector column and an\n // indexed one behave identically apart from latency, so the only way anyone\n // learns which one they have is if the boot says so.\n for (const skip of plan.vectorIndexSkipped) {\n const message = `No ANN index on \"${skip.table}\".\"${skip.column}\": ${skip.reason}`;\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per column, every boot, because the alternative is what this\n // whole feature exists to end: a column the configuration calls required,\n // sitting there nullable, with every surface reporting success. The boot\n // does not fail over it — the column is usable and the data is intact — but\n // it stops being invisible.\n for (const withheld of plan.withheldConstraints) {\n const message =\n `No ${withheld.kind === \"unique\" ? \"UNIQUE\" : \"NOT NULL\"} on \"${withheld.target}\": ` +\n `${withheld.reason} ${withheld.remedy}`;\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per drifted column, every boot, and this is the one report here\n // that describes a system which currently *looks* healthy. Everything else\n // in this function explains a statement that did not run; this explains a\n // statement that was never planned, on a deploy that reported success, and\n // whose first symptom is a write rejected long afterwards.\n for (const drift of plan.columnTypeDrift) {\n const message = columnTypeDriftMessage(drift);\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // Said once per column, every boot, and it matters more than the rest here\n // because the table is not merely imperfect — it is unwritable, and the\n // error the API returns names a field the author has already deleted.\n // This is what a renamed property looks like to an additive provisioner.\n for (const orphan of plan.orphanedRequiredColumns) {\n const message =\n `\"${orphan.table}\".\"${orphan.column}\" is NOT NULL with no default, and the \"${orphan.slug}\" ` +\n \"collection no longer declares it. Every insert will be rejected for a field you cannot set \" +\n `(PG_23502, naming \"${orphan.column}\"). This is what a removed or renamed property looks like: ` +\n \"boot neither relaxes nor drops a column unattended. Fix it with ONE of (each shows the plan and asks):\\n\" +\n ` rebase schema reconcile -- keep the data, stop requiring it\\n` +\n ` rebase schema reconcile --drop ${orphan.slug}.${orphan.column} -- the column is no longer wanted\\n` +\n \" ...or declare the property again, if the column is still wanted.\";\n logger.warn(`[schema] ${message}`);\n log?.(message);\n }\n\n // The indexes of tables that already exist. Built here unless the caller\n // defers them — and a UNIQUE one is built here regardless, before this\n // returns, so nothing serves the collection without the promise it makes.\n const builtHere = options.deferIndexBuilds\n ? plan.deferredIndexes.filter(index => index.unique === true)\n : plan.deferredIndexes;\n const leftToCaller = options.deferIndexBuilds\n ? plan.deferredIndexes.filter(index => index.unique !== true)\n : plan.deferredIndexes;\n\n // After every action, so the columns they index exist — whether this run\n // added them or a previous one did.\n const buildIndexes = async (): Promise<DeferredIndexOutcome | undefined> => {\n if (builtHere.length === 0) return undefined;\n const outcome = await buildDeferredIndexes(\n options.openIndexBuildSession ?? (async () => ({\n query: <T>(sql: string) => client.query<T>(sql),\n dedicated: false,\n release: () => undefined\n })),\n builtHere,\n { log, lockTimeoutMs: options.lockTimeoutMs }\n );\n assertUniqueIndexesBuilt(builtHere, outcome);\n return outcome;\n };\n const finish = async (): Promise<EnsureOutcome> => {\n const indexBuilds = await buildIndexes();\n // Last: a view reads the tables everything above created. The block\n // creates a missing view, recreates one whose query changed and leaves\n // the rest alone (see `renderViewsDdl`).\n const views = renderViewsDdl(schema);\n if (views) {\n await client.query(views);\n log?.(`views: ${schema.views.map(view => view.qualified).join(\", \")}`);\n }\n return { ...plan, deferredIndexes: leftToCaller, failures, indexBuilds };\n };\n\n if (plan.actions.length === 0) {\n if (plan.deferredIndexes.length === 0) log?.(\"Schema is up to date; nothing to create.\");\n return finish();\n }\n\n const lockBudget = options.lockTimeoutMs !== undefined\n ? { lockTimeoutMs: options.lockTimeoutMs, atomic: true }\n : undefined;\n // Whether the handle takes a multi-statement string; shared with the lock\n // budget, which needs the same thing.\n const multi = lockBudget ?? { atomic: true };\n\n // A table this run creates has no rows, no readers and no writers, so its\n // statements — the CREATE, the ENABLE, every column, its triggers, the\n // indexes on it — can share a transaction: one commit instead of one per\n // statement. A first deploy of 200 collections was 3,767 autocommits, 11.7 s\n // on a disk that really flushes. If a batch fails for any reason, its\n // statements are applied again one at a time below, exactly as before, so\n // the races and survivable failures that path handles end the same way.\n const createdTables = new Set(plan.actions.filter(a => a.kind === \"create-table\").map(a => a.target));\n const batchable = (action: EnsureAction): boolean =>\n options.batchNewTables === true &&\n multi.atomic &&\n (action.kind === \"create-enum\" || createdTables.has(action.target.split(\".\").slice(0, 2).join(\".\"))) &&\n action.kind !== \"add-enum-value\" &&\n !CONCURRENTLY_RE.test(action.sql);\n\n const applyBatch = async (group: EnsureAction[]): Promise<boolean> => {\n const statements = group.map(action => action.sql);\n try {\n await client.query(lockBudget\n ? atomicBatch(statements, lockBudget.lockTimeoutMs)\n : joinStatements(statements));\n return true;\n } catch (err) {\n if (isMultiStatementRefusal(err)) {\n multi.atomic = false;\n } else {\n log?.(`${group.length} statement(s) for new tables failed as one transaction ` +\n `(${describeDriverError(err).split(\"\\n\")[0]}); applying them one at a time`);\n }\n return false;\n }\n };\n\n const applyOne = async (action: EnsureAction): Promise<void> => {\n try {\n if (await applyAction(client, action, lockBudget)) {\n log?.(`${action.kind}: ${action.target}`);\n } else {\n log?.(`${action.kind}: ${action.target} (already created by a peer)`);\n }\n } catch (err) {\n const message = describeDriverError(err);\n // A foreign key is the only action that can fail on the customer's\n // data rather than on the schema. The column it polices is already\n // there, so the collection serves either way — record it and carry\n // on rather than crash-looping the deployment.\n //\n // A comment is metadata about a column that was just created\n // successfully, and it can only fail on ownership (COMMENT requires\n // owning the table, which an adopted table may not grant). Losing\n // the stamp costs drift detection on the next boot; it must not cost\n // the deployment.\n //\n // An index that is not UNIQUE is an optimization, and losing an\n // optimization must not cost the deployment. This was the difference\n // between a slow collection and a tenant that would not boot: on a\n // managed runtime the throw killed the process, the pod never went\n // ready, and the deploy reported a 300-second readiness timeout — for\n // an ANN index whose absence changes latency and nothing else.\n //\n // UNIQUE is excluded because it is not an optimization. It is the\n // collection declaring that two rows cannot share a value, and\n // serving without it is serving a promise the database is not\n // keeping.\n const survivable =\n action.kind === \"add-constraint\" ||\n action.kind === \"comment-column\" ||\n (action.kind === \"create-index\" && !/CREATE\\s+UNIQUE\\s+INDEX/i.test(action.sql));\n if (survivable) {\n failures.push({ kind: action.kind, target: action.target, error: message });\n return;\n }\n const lockHint = isLockTimeout(err)\n ? \"\\n hint: another session held this table's lock for every attempt (a long transaction, a \" +\n \"report or a dump). Nothing was changed; boot again once it has finished.\"\n : \"\";\n throw new Error(\n `Failed to ${action.kind} ${action.target}: ${message}${vectorExtensionHint(message)}${lockHint}\\n ${action.sql}`\n );\n }\n };\n\n for (let i = 0; i < plan.actions.length;) {\n let end = i;\n while (end < plan.actions.length && end - i < NEW_TABLE_BATCH && batchable(plan.actions[end])) end++;\n if (end - i > 1 && await applyBatch(plan.actions.slice(i, end))) {\n for (const action of plan.actions.slice(i, end)) log?.(`${action.kind}: ${action.target}`);\n i = end;\n continue;\n }\n const last = Math.max(end, i + 1);\n for (; i < last; i++) await applyOne(plan.actions[i]);\n }\n return finish();\n}\n\n/**\n * Fail the ensure for a UNIQUE index on a live table that could not be built,\n * exactly as a failed UNIQUE `create-index` action always has (see `applyOne`).\n *\n * \"Another index on the table is being built\" counts: the table's lock is\n * held by a build that may run for minutes, and serving the collection\n * meanwhile would be serving a promise the database is not keeping. Another\n * instance building *this* index does not: once its build commits the\n * constraint holds, which is also what a peer's `IF NOT EXISTS` race meant.\n */\nfunction assertUniqueIndexesBuilt(indexes: readonly DeferredIndexBuild[], outcome: DeferredIndexOutcome): void {\n for (const index of indexes) {\n if (index.unique !== true) continue;\n const qualified = `${index.schema}.${index.indexName}`;\n const reason = outcome.failed.find(failure => failure.index === qualified)?.error\n ?? outcome.skipped.find(skip => skip.index === qualified && skip.reason === TABLE_BUSY_REASON)?.reason;\n if (reason === undefined) continue;\n throw new Error(`Failed to create-index ${index.schema}.${index.table}: ${qualified}: ${reason}\\n ${index.sql}`);\n }\n}\n\n/**\n * What actually went wrong, rather than what the ORM said about it.\n *\n * Drizzle wraps every driver error, and its `message` is literally\n * ``Failed query: ${sql}\\nparams: ${params}`` — the statement we already know,\n * and not one word of Postgres's answer. Reporting `err.message` therefore\n * produced a failure that named the statement twice and the *reason* zero\n * times, so four unrelated boot failures — a missing extension, a wrong\n * privilege, a bad index method, a constraint the rows violate — all read\n * identically to whoever had to fix them.\n *\n * Two consequences, both observed in the field before this existed:\n *\n * 1. On a managed deployment the reason never reaches anybody. Boot dies, the\n * pod never goes ready, and the deploy reports a readiness timeout — so the\n * one line that says why is the one line that was thrown away here.\n * 2. {@link vectorExtensionHint} matches on the error text. Against the\n * wrapper it matched nothing, so the hint written specifically to explain a\n * missing pgvector never fired on the path that raises it.\n *\n * `detail` and `hint` come along because they are the fields Postgres uses to\n * say which object it meant and what to do about it — `CREATE EXTENSION` names\n * the missing library there, and a rejected constraint names the row. This\n * writes into the tenant's own boot log, about the tenant's own database.\n */\nexport function describeDriverError(err: unknown): string {\n const pg = extractPgError(err);\n if (pg) {\n const parts = [pg.code ? `${pg.message} [${pg.code}]` : pg.message];\n if (pg.detail) parts.push(` detail: ${pg.detail}`);\n if (pg.hint) parts.push(` hint: ${pg.hint}`);\n return parts.join(\"\\n\");\n }\n // No SQLSTATE anywhere in the chain: not a database answer at all — a\n // socket that closed, a bug in this file. The deepest cause still beats the\n // wrapper, and the wrapper still beats nothing.\n const cause = extractCauseMessage(err);\n if (cause) return cause;\n return err instanceof Error ? err.message : String(err);\n}\n\n/** ` CONCURRENTLY ` as it appears in a rendered `CREATE [UNIQUE] INDEX`. */\nconst CONCURRENTLY_RE = /\\sCONCURRENTLY\\s/i;\n\n/**\n * `25001 active_sql_transaction` — \"cannot run inside a transaction block\".\n *\n * Only ever raised here by `CREATE INDEX CONCURRENTLY`, and only when the\n * connection we were handed is inside a transaction. Deliberately narrow: it\n * decides to retry a *different* statement, so it must not fire on anything it\n * has not been reasoned about.\n */\nfunction isTransactionBlockRefusal(err: unknown): boolean {\n return extractPgError(err)?.code === \"25001\";\n}\n\n/** Attempts per action, including the first. Matches the server's bootstraps. */\nconst DDL_ATTEMPTS = 4;\n\n/**\n * Attempts at an action whose table lock is held, including the first.\n *\n * Unlike a policy, a schema change cannot be deferred — the collection's code\n * expects the column — so a lock that never frees still fails the boot, as a\n * statement timeout did. Ten one-second attempts with backoff between them wait\n * about as long as the old 30 s statement timeout did, but a live query on that\n * table now waits at most one second at a time instead of thirty.\n */\nconst LOCK_ATTEMPTS = 10;\n\n/**\n * Whether an action may be sent as `SET LOCAL lock_timeout; <statement>` — one\n * implicit transaction. Not `CREATE INDEX CONCURRENTLY`, which Postgres refuses\n * inside any transaction block (and which waits on no lock a reader holds), and\n * not `ALTER TYPE … ADD VALUE`, which Postgres before 12 refuses there too and\n * which locks a type, not a table.\n */\nconst takesLockBudget = (action: EnsureAction, sql: string): boolean =>\n action.kind !== \"add-enum-value\" && !CONCURRENTLY_RE.test(sql);\n\n/**\n * Run one planned statement, surviving a simultaneous boot.\n *\n * Every statement in a plan is written to be idempotent, and that is not the\n * same as being safe to run concurrently: `CREATE … IF NOT EXISTS` reads the\n * catalog and then writes to it as two steps, so peers starting together both\n * see \"absent\" and the loser gets a duplicate key on a *catalog* index. Measured\n * against Postgres 18: five instances, 8 of 10 calls lost. `CREATE TYPE` is\n * worse, because Postgres has no `IF NOT EXISTS` for it at all.\n *\n * What made that fatal here rather than merely noisy is the loop this sits in.\n * A losing statement threw, and the throw abandoned **every remaining action in\n * the plan** — so a replica that lost one race came up missing tables it never\n * attempted, and the boot log blamed the one statement that failed.\n *\n * @returns `true` if this process applied the statement, `false` if a peer had\n * already created the object. The distinction is only for the log; both mean\n * the object is now there.\n * @throws the original error for anything that is not a race — a syntax error, a\n * permission failure, a unique constraint the customer's own rows violate.\n */\nasync function applyAction(\n client: Queryable,\n action: EnsureAction,\n lockBudget?: { lockTimeoutMs: number; atomic: boolean }\n): Promise<boolean> {\n let sqlText = action.sql;\n let lockAttempts = 0;\n for (let attempt = 1; ; attempt++) {\n const budgeted = lockBudget?.atomic === true && takesLockBudget(action, sqlText);\n try {\n await client.query(budgeted ? atomicBatch([sqlText], lockBudget.lockTimeoutMs) : sqlText);\n return true;\n } catch (err) {\n // A handle that takes one statement per query (extended protocol)\n // cannot carry the `SET LOCAL`. Nothing ran; say it once and send\n // every statement as it is from here on.\n if (budgeted && isMultiStatementRefusal(err)) {\n lockBudget.atomic = false;\n attempt--;\n continue;\n }\n // Something held the table for longer than the budget — a long\n // transaction, a report, a dump. The statement did nothing; let\n // the queue behind it drain, then ask again.\n if (budgeted && isLockTimeout(err) && ++lockAttempts < LOCK_ATTEMPTS) {\n logger.debug(\n `[schema] ${action.kind} ${action.target}: the table's lock is held by another session ` +\n `(attempt ${lockAttempts}/${LOCK_ATTEMPTS}) — retrying`\n );\n attempt--;\n await sleep(Math.min(500 * lockAttempts, 2_000) * (1 + Math.random()));\n continue;\n }\n // `CREATE INDEX CONCURRENTLY` is the one statement here Postgres\n // refuses inside a transaction block (25001), and whether we are in\n // one is not ours to know: the client is whatever handle the caller\n // bootstrapped with, and an application that builds its own adapter\n // can hand us a connection already inside a transaction. The plain\n // form is always correct and never refused — it takes a write lock\n // for the build, which is the cost of getting the index at all.\n if (isTransactionBlockRefusal(err) && CONCURRENTLY_RE.test(sqlText)) {\n sqlText = sqlText.replace(CONCURRENTLY_RE, \" \");\n logger.warn(\n `[schema] ${action.kind} ${action.target}: this connection is inside a transaction, ` +\n \"so the index is being built with a write lock rather than concurrently. Writes to \" +\n \"this table block until it finishes.\"\n );\n continue;\n }\n // Already there. Not \"retry\" — the end state this statement wanted\n // is the end state the database is in, so carry on to the next\n // action rather than spending three more attempts proving it.\n if (isDuplicateObjectRace(err)) {\n logger.debug(\n `[schema] ${action.kind} ${action.target}: already created by another instance`\n );\n return false;\n }\n // Retryable but not yet satisfied — a deadlock between two boots\n // taking catalog locks in step. The statement did nothing; run it\n // again after a jittered pause so peers that collided once do not\n // collide again in lockstep.\n if (isConcurrentDdlRace(err) && attempt < DDL_ATTEMPTS) {\n logger.debug(\n `[schema] ${action.kind} ${action.target}: lost a race with another instance ` +\n `(attempt ${attempt}/${DDL_ATTEMPTS}) — retrying`\n );\n await new Promise(resolve => setTimeout(resolve, 40 * attempt * (1 + Math.random())));\n continue;\n }\n throw err;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA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