@rebasepro/server-postgres 0.26.0 → 0.28.0

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 (105) hide show
  1. package/README.md +1 -1
  2. package/dist/{BranchService-CWBnDhcv.js → BranchService-BPssiD8_.js} +37 -11
  3. package/dist/BranchService-BPssiD8_.js.map +1 -0
  4. package/dist/PostgresBackendDriver.d.ts +7 -0
  5. package/dist/auth/services.d.ts +34 -8
  6. package/dist/backup/pg-tools.d.ts +14 -0
  7. package/dist/backup/retention.d.ts +14 -1
  8. package/dist/{backup-cli-PoRG-zEq.js → backup-cli-C1wcj-rc.js} +60 -12
  9. package/dist/backup-cli-C1wcj-rc.js.map +1 -0
  10. package/dist/{boot-ddl-EsgqDkx0.js → boot-ddl-CIGoIGcC.js} +2 -2
  11. package/dist/{boot-ddl-EsgqDkx0.js.map → boot-ddl-CIGoIGcC.js.map} +1 -1
  12. package/dist/branch-argv.d.ts +20 -0
  13. package/dist/{cli-console-f0k6_TsJ.js → cli-console-C0FYkICX.js} +5 -5
  14. package/dist/{cli-console-f0k6_TsJ.js.map → cli-console-C0FYkICX.js.map} +1 -1
  15. package/dist/{cli-errors-DsYyNYzd.js → cli-errors-DYets7cp.js} +6 -6
  16. package/dist/{cli-errors-DsYyNYzd.js.map → cli-errors-DYets7cp.js.map} +1 -1
  17. package/dist/cli.js +43 -41
  18. package/dist/cli.js.map +1 -1
  19. package/dist/{column-plan-helpers-IG6uFb1s.js → column-plan-helpers-BeSztMor.js} +5 -1
  20. package/dist/{column-plan-helpers-IG6uFb1s.js.map → column-plan-helpers-BeSztMor.js.map} +1 -1
  21. package/dist/data-transformer.d.ts +11 -1
  22. package/dist/{databasePoolManager-3stMNFL-.js → databasePoolManager-BjoVvuAq.js} +2 -2
  23. package/dist/databasePoolManager-BjoVvuAq.js.map +1 -0
  24. package/dist/{deferred-index-build-CqaOv1Xx.js → deferred-index-build-BcJ_oulu.js} +5 -5
  25. package/dist/{deferred-index-build-CqaOv1Xx.js.map → deferred-index-build-BcJ_oulu.js.map} +1 -1
  26. package/dist/{doctor-DW_mlTzz.js → doctor-TJApVglQ.js} +6 -6
  27. package/dist/{doctor-DW_mlTzz.js.map → doctor-TJApVglQ.js.map} +1 -1
  28. package/dist/{ensure-collection-policies-DLWgabQ2.js → ensure-collection-policies-BNwSQfVx.js} +63 -25
  29. package/dist/ensure-collection-policies-BNwSQfVx.js.map +1 -0
  30. package/dist/{ensure-collection-tables-CFIRq8ni.js → ensure-collection-tables-CSbgkTBx.js} +8 -9
  31. package/dist/{ensure-collection-tables-CFIRq8ni.js.map → ensure-collection-tables-CSbgkTBx.js.map} +1 -1
  32. package/dist/{ensure-tables-4nA-tfwi.js → ensure-tables-CF-8zgYA.js} +3 -3
  33. package/dist/{ensure-tables-4nA-tfwi.js.map → ensure-tables-CF-8zgYA.js.map} +1 -1
  34. package/dist/{enum-labels-kept-PcPW65xy.js → enum-labels-kept-BCgFGAbJ.js} +3 -3
  35. package/dist/{enum-labels-kept-PcPW65xy.js.map → enum-labels-kept-BCgFGAbJ.js.map} +1 -1
  36. package/dist/{generate-drizzle-schema-DC0BOUpn.js → generate-drizzle-schema-BAIp9nKT.js} +2 -2
  37. package/dist/{generate-drizzle-schema-DC0BOUpn.js.map → generate-drizzle-schema-BAIp9nKT.js.map} +1 -1
  38. package/dist/{generate-drizzle-schema-logic-CPzCRD-8.js → generate-drizzle-schema-logic-CVRmZjP3.js} +2 -2
  39. package/dist/{generate-drizzle-schema-logic-CPzCRD-8.js.map → generate-drizzle-schema-logic-CVRmZjP3.js.map} +1 -1
  40. package/dist/{generate-files-BP-4W_gm.js → generate-files-DutUrsSS.js} +3 -3
  41. package/dist/{generate-files-BP-4W_gm.js.map → generate-files-DutUrsSS.js.map} +1 -1
  42. package/dist/{generate-postgres-ddl-logic-DPl1oH_z.js → generate-postgres-ddl-logic-0rbAqwYT.js} +22 -10
  43. package/dist/generate-postgres-ddl-logic-0rbAqwYT.js.map +1 -0
  44. package/dist/{generated-schema-diff-eZCklRZQ.js → generated-schema-diff-ChFg6UxI.js} +13 -4
  45. package/dist/{generated-schema-diff-eZCklRZQ.js.map → generated-schema-diff-ChFg6UxI.js.map} +1 -1
  46. package/dist/history/HistoryService.d.ts +5 -0
  47. package/dist/index.es.js +14 -13
  48. package/dist/index.es.js.map +1 -1
  49. package/dist/{migrate-baseline-B-2Ef4Mv.js → migrate-baseline-DPawvckr.js} +54 -11
  50. package/dist/{migrate-baseline-B-2Ef4Mv.js.map → migrate-baseline-DPawvckr.js.map} +1 -1
  51. package/dist/{migrate-policy-stamps-BQtFHApx.js → migrate-policy-stamps-B-8vTSIm.js} +6 -6
  52. package/dist/{migrate-policy-stamps-BQtFHApx.js.map → migrate-policy-stamps-B-8vTSIm.js.map} +1 -1
  53. package/dist/{open-rebase-C8jQ6s5a.js → open-rebase-D9n8idex.js} +1685 -201
  54. package/dist/open-rebase-D9n8idex.js.map +1 -0
  55. package/dist/{pg-error-utils-DhiUTlVx.js → pg-error-utils-BIHfsGZL.js} +2 -2
  56. package/dist/{pg-error-utils-DhiUTlVx.js.map → pg-error-utils-BIHfsGZL.js.map} +1 -1
  57. package/dist/{plan-schema-Czf3q4-Q.js → plan-schema-DMVh77yb.js} +29 -2
  58. package/dist/plan-schema-DMVh77yb.js.map +1 -0
  59. package/dist/{policy-drift-X4A-xAzv.js → policy-drift-0Cp4Lc0x.js} +13 -4
  60. package/dist/policy-drift-0Cp4Lc0x.js.map +1 -0
  61. package/dist/{push-index-prebuild-UTvB5pqH.js → push-index-prebuild-DR3P4yOw.js} +4 -4
  62. package/dist/{push-index-prebuild-UTvB5pqH.js.map → push-index-prebuild-DR3P4yOw.js.map} +1 -1
  63. package/dist/{push-kept-defaults-BGOlOqRQ.js → push-kept-defaults-BSqPzp0T.js} +3 -3
  64. package/dist/{push-kept-defaults-BGOlOqRQ.js.map → push-kept-defaults-BSqPzp0T.js.map} +1 -1
  65. package/dist/{push-legacy-renames-BwaKi8xF.js → push-legacy-renames-BIxBmVLl.js} +4 -4
  66. package/dist/{push-legacy-renames-BwaKi8xF.js.map → push-legacy-renames-BIxBmVLl.js.map} +1 -1
  67. package/dist/{push-policy-plan-DQ2tWceD.js → push-policy-plan-BHsasXa7.js} +4 -4
  68. package/dist/{push-policy-plan-DQ2tWceD.js.map → push-policy-plan-BHsasXa7.js.map} +1 -1
  69. package/dist/{render-ddl-4v88y-Gv.js → render-ddl-NpPPDACz.js} +20 -3
  70. package/dist/render-ddl-NpPPDACz.js.map +1 -0
  71. package/dist/schema/doctor-cli.js +3 -3
  72. package/dist/schema/ensure-collection-policies.d.ts +6 -4
  73. package/dist/schema/generate-drizzle-schema.js +1 -1
  74. package/dist/schema/generate-postgres-ddl-logic.d.ts +16 -0
  75. package/dist/schema/generate-postgres-ddl.js +1 -1
  76. package/dist/schema/generated-schema-diff.d.ts +6 -0
  77. package/dist/schema/introspect-db.js +1 -1
  78. package/dist/schema/plan/render-ddl.d.ts +11 -0
  79. package/dist/schema/reconcile-schema.d.ts +21 -0
  80. package/dist/security/policy-drift.d.ts +9 -1
  81. package/dist/services/BranchService.d.ts +6 -0
  82. package/dist/services/RelationService.d.ts +6 -6
  83. package/dist/services/cdc/CdcListener.d.ts +12 -0
  84. package/dist/services/cdc/WalCdcListener.d.ts +92 -0
  85. package/dist/services/cdc/pgoutput.d.ts +121 -0
  86. package/dist/services/cdc/wal-cdc.d.ts +29 -0
  87. package/dist/services/channel-bus/PostgresChannelBus.d.ts +1 -0
  88. package/dist/services/collection-helpers.d.ts +14 -0
  89. package/dist/services/junction-writes.d.ts +9 -1
  90. package/dist/services/nested-path.d.ts +2 -1
  91. package/dist/services/realtimeService.d.ts +77 -3
  92. package/dist/utils/drizzle-conditions.d.ts +11 -0
  93. package/dist/{websocket-CKYc3V4N.js → websocket-D4wrzF3b.js} +35 -8
  94. package/dist/websocket-D4wrzF3b.js.map +1 -0
  95. package/package.json +7 -7
  96. package/dist/BranchService-CWBnDhcv.js.map +0 -1
  97. package/dist/backup-cli-PoRG-zEq.js.map +0 -1
  98. package/dist/databasePoolManager-3stMNFL-.js.map +0 -1
  99. package/dist/ensure-collection-policies-DLWgabQ2.js.map +0 -1
  100. package/dist/generate-postgres-ddl-logic-DPl1oH_z.js.map +0 -1
  101. package/dist/open-rebase-C8jQ6s5a.js.map +0 -1
  102. package/dist/plan-schema-Czf3q4-Q.js.map +0 -1
  103. package/dist/policy-drift-X4A-xAzv.js.map +0 -1
  104. package/dist/render-ddl-4v88y-Gv.js.map +0 -1
  105. package/dist/websocket-CKYc3V4N.js.map +0 -1
@@ -140,6 +140,10 @@ var idColumnDefault = (propName, prop, collection) => {
140
140
  if (typeof isId !== "string") return void 0;
141
141
  if (prop.type === "string" && isId === "uuid") return { kind: "uuid" };
142
142
  if (prop.type === "number" && isId === "increment") return { kind: "identity" };
143
+ if (isId === "increment" || isId === "uuid") {
144
+ const needs = isId === "increment" ? "number" : "string";
145
+ throw new Error(`Property "${propName}" of collection "${collection.slug ?? collection.name ?? "(unnamed)"}" is a ${prop.type} property, and \`isId: "${isId}"\` needs a ${needs} property. ` + (isId === "increment" ? "Make the key `type: \"number\"`, or use `isId: \"uuid\"` for a string key." : "Make the key `type: \"string\"`, or use `isId: \"increment\"` for a number key."));
146
+ }
143
147
  if (isId === "cuid") throw new Error(`Property "${propName}" of collection "${collection.slug ?? collection.name ?? "(unnamed)"}" uses \`isId: "cuid"\`, which Postgres cannot honour: the generated default calls a \`cuid()\` function that Rebase has never created, so every insert relying on it fails. Use \`isId: "uuid"\`, or give the strategy as SQL — \`\`isId: "sql\`my_id()\`"\`\` — and create that function in a migration.`);
144
148
  return {
145
149
  kind: "sql",
@@ -154,4 +158,4 @@ var sqlExpressionText = (value) => value.startsWith("sql`") && value.endsWith("`
154
158
  //#endregion
155
159
  export { getPrimaryKeyName as a, isIdProperty as c, sqlExpressionText as d, getPrimaryKeyColumn as i, primaryKeyPropertyNames as l, declaresEnumType as n, getPrimaryKeyProp as o, enumLabelsOf as r, idColumnDefault as s, column_plan_helpers_exports as t, resolveColumnName as u };
156
160
 
157
- //# sourceMappingURL=column-plan-helpers-IG6uFb1s.js.map
161
+ //# sourceMappingURL=column-plan-helpers-BeSztMor.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"column-plan-helpers-IG6uFb1s.js","names":[],"sources":["../src/schema/column-plan-helpers.ts"],"sourcesContent":["/**\n * The questions about a property that the schema planner asks first.\n *\n * What is the primary key, what is this column called, what does an id default\n * to, what labels does this enum have. `schema/plan/plan-schema.ts` is the only\n * caller — it is the only reader of a `Property` — and these live beside it\n * rather than inside it because they are also where the *refusals* are, and a\n * refusal wants to be reachable and testable on its own.\n *\n * They were extracted while there were still three emitters, each carrying its\n * own verbatim copy of all four rules until one of them was edited: the audit\n * that produced this module counted twelve open disagreements and found that a\n * third of the commits touching those files were re-synchronisations. The\n * emitters are renderers now and there is nothing left to keep in step, but the\n * questions are still questions about a property rather than about a plan, so\n * this is where they belong.\n *\n * Everything here is pure and synchronous, and it throws rather than guesses:\n * an enum with no values, a `cuid` id on Postgres and a foreign key into a\n * composite key are all configurations that produce a broken database in\n * silence, so they are refused where every path passes.\n */\nimport type {\n CollectionConfig,\n NumberProperty,\n Property,\n StringProperty\n} from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\n/**\n * Resolve the SQL column name for a property.\n *\n * Uses the explicit `columnName` when set (e.g. from introspection), falling\n * back to `toSnakeCase(propName)` for manually-authored collections.\n */\nexport const resolveColumnName = (propName: string, prop?: Property | null): string => {\n if (prop && \"columnName\" in prop && typeof prop.columnName === \"string\") {\n return prop.columnName;\n }\n return toSnakeCase(propName);\n};\n\n/** Every property that carries a truthy `isId`, in declaration order. */\nconst idPropertyEntries = (collection: CollectionConfig): [string, Property][] =>\n Object.entries(collection.properties ?? {}).filter(\n ([, prop]) => prop && typeof prop === \"object\" && \"isId\" in prop && Boolean((prop as { isId?: unknown }).isId)\n ) as [string, Property][];\n\n/**\n * The properties marked `isId`, in declaration order.\n *\n * Several of them are one composite primary key: the table carries a single\n * `PRIMARY KEY (a, b)` constraint over their columns, and a row's address lists\n * the parts in this same order (`buildCompositeId`), which is the order the\n * admin reads them in too.\n */\nexport const primaryKeyPropertyNames = (collection: CollectionConfig): string[] =>\n idPropertyEntries(collection).map(([name]) => name);\n\n/**\n * A collection's primary key, by both of its names.\n *\n * `name` is the property key — what the generated Drizzle table is keyed by,\n * so it is what a relation's `references` names. `column` is the SQL\n * identifier, so it is what a foreign key's `REFERENCES` names. They differ\n * whenever the key is camelCase or carries a `columnName` (`authorId` is\n * `author_id`, and every table `rebase schema introspect` adopts is spelled\n * that way), and a constraint written with the key named a column that does\n * not exist: `db push` could not build its desired state, and boot failed the\n * constraint on every start.\n */\nexport interface PrimaryKey {\n /** Property key: the Drizzle object key and the JSON field. */\n name: string;\n /** SQL column. */\n column: string;\n /** The declaring property; absent for the implicit `id TEXT` of a collection that declares none. */\n prop?: Property;\n}\n\n/**\n * The one column a link into this collection points at.\n *\n * A foreign key column references a single column, and Postgres only accepts\n * that column when it is unique on its own — `REFERENCES t (a)` against a\n * composite key `(a, b)` fails with \"there is no unique constraint matching\n * given keys for referenced table\". So a link into a collection whose key\n * spans several columns has no column to point at, and it is refused here,\n * naming the link, rather than emitted as a constraint `db push` or boot would\n * then fail to create.\n *\n * @param via the link that needs the column, for the refusal: `relation \"posts.author\"`.\n */\nexport const getPrimaryKeyProp = (collection: CollectionConfig, via: string): PrimaryKey => {\n const ids = idPropertyEntries(collection);\n if (ids.length > 1) {\n throw new Error(\n `${via} points at collection \"${collection.slug ?? collection.name ?? \"(unnamed)\"}\", whose primary ` +\n `key spans ${ids.length} columns (${ids.map(([name]) => `\"${name}\"`).join(\", \")}). A foreign key is ` +\n \"one column and cannot reference a composite key. Point the link at a collection with a \" +\n \"single-column key, or reach these rows with a `via` relation, whose `joinPath` compares every \" +\n \"key column.\"\n );\n }\n const idPropEntry = ids[0];\n if (idPropEntry) {\n const [name, prop] = idPropEntry;\n return { name, column: resolveColumnName(name, prop), prop };\n }\n // Fallback: a collection that declares no `isId` gets an implicit `id`.\n const idProp = collection.properties?.[\"id\"] as Property | undefined;\n return { name: \"id\", column: resolveColumnName(\"id\", idProp), prop: idProp };\n};\n\n/**\n * The primary key's property key. What a Drizzle relation's `references`\n * names. Refused on the same terms as {@link getPrimaryKeyProp}.\n */\nexport const getPrimaryKeyName = (collection: CollectionConfig, via: string): string =>\n getPrimaryKeyProp(collection, via).name;\n\n/**\n * The primary key's column. What a foreign key's `REFERENCES` names. Refused\n * on the same terms as {@link getPrimaryKeyProp}.\n */\nexport const getPrimaryKeyColumn = (collection: CollectionConfig, via: string): string =>\n getPrimaryKeyProp(collection, via).column;\n\nexport const isIdProperty = (propName: string, prop: Property, collection: CollectionConfig): boolean => {\n if (\"isId\" in prop && Boolean(prop.isId)) return true;\n\n // Only fall back to \"id\" when NO property is explicitly marked.\n return idPropertyEntries(collection).length === 0 && propName === \"id\";\n};\n\n/**\n * The labels an `enum` declares, in order, whichever form it was written in.\n *\n * `EnumValues` is `EnumValueConfig[] | Record<id, label>` and the docs recommend\n * the record. Boot-ensure read only the array form — `(p.enum as unknown[]).map`\n * — so a record-form enum threw `p.enum.map is not a function` on a managed\n * tenant, at boot, with no developer in the loop. The other two emitters each\n * carried their own copy of the both-forms walk.\n *\n * An empty list throws rather than returning `[]`. `CREATE TYPE … AS ENUM ()`\n * is not valid SQL, so every emitter \"handled\" it by skipping the type and then\n * typing the column with it anyway: Drizzle referenced an enum variable it never\n * declared (the generated file does not compile), the DDL named a type nothing\n * creates, and boot-ensure's `ADD COLUMN` failed — and add-column is not a\n * survivable action, so the boot died. There is no useful column at the end of\n * any of those paths.\n */\nexport const enumLabelsOf = (propName: string, prop: Property, collection: CollectionConfig): string[] => {\n const values = (prop as { enum?: unknown }).enum;\n if (values === undefined || values === null) return [];\n\n const labels = Array.isArray(values)\n ? values.map((entry: unknown) =>\n String(entry !== null && typeof entry === \"object\" && \"id\" in (entry as Record<string, unknown>)\n ? (entry as Record<string, unknown>).id\n : entry))\n : Object.keys(values as Record<string, unknown>).map(String);\n\n const usable = labels.filter(label => label.length > 0);\n if (usable.length === 0) {\n throw new Error(\n `Property \"${propName}\" of collection \"${collection.slug ?? collection.name ?? \"(unnamed)\"}\" ` +\n \"declares an empty `enum`. A Postgres enum type needs at least one label — \" +\n \"`CREATE TYPE … AS ENUM ()` is not valid SQL — so the column would reference a type \" +\n \"nothing creates. List the values, or drop the `enum` for a plain column.\"\n );\n }\n return usable;\n};\n\n/**\n * Does this property compile to a Postgres enum *type*?\n *\n * Strings only. A `number` property with an `enum` used to create a type on all\n * three paths and then declare the column `NUMERIC`/`INTEGER`, so the type was\n * orphaned the moment it was created and the values it listed were enforced by\n * nothing. The dropdown in the panel is driven by the config, not the column, so\n * nothing is lost by not creating it — and a type no column uses is one more\n * object `db push` has to plan a DROP for.\n */\nexport const declaresEnumType = (prop: Property): boolean =>\n prop.type === \"string\" && Boolean((prop as StringProperty).enum);\n\n/**\n * The `DEFAULT` an id column carries, as the thing itself rather than a\n * rendered string — each emitter spells it differently.\n *\n * The three of them disagreed on all four strategies. The DDL generator wrote\n * `DEFAULT ${prop.isId}` verbatim, so the documented `` isId: \"sql`gen_id()`\" ``\n * reached Postgres with the template wrapper still on it — a syntax error in\n * `schema.sql`. Boot-ensure gave a default to `uuid` and to nothing else, so on\n * a managed tenant every other strategy produced a column with no default at\n * all, and the first insert that trusted the config failed on a NULL primary\n * key. Only the Drizzle generator stripped the wrapper.\n */\nexport type IdColumnDefault =\n /** `gen_random_uuid()` / `.defaultRandom()`. */\n | { kind: \"uuid\" }\n /** `GENERATED BY DEFAULT AS IDENTITY` / `.generatedByDefaultAsIdentity()` — part of the type, not a DEFAULT. */\n | { kind: \"identity\" }\n /** A raw SQL expression, wrapper already stripped. */\n | { kind: \"sql\"; expression: string };\n\n/**\n * Refuses `isId: \"cuid\"`.\n *\n * `DEFAULT cuid()` has been emitted since the option existed and no `cuid()`\n * function has ever been created — not by the generators, not by boot, not by\n * any migration. So the column has never had a working default on Postgres: the\n * first insert that relied on it failed with `function cuid() does not exist`.\n * There is nothing to keep compatible.\n *\n * It is refused rather than implemented. Shipping a real `rebase.cuid()` means a\n * new SQL function in the same carved-out class as the search helpers — excluded\n * from Atlas by pattern, applied by boot, re-applied by push, checked by the\n * doctor, and versioned across the fleet forever — to reproduce a monotonic id\n * that `uuid` already provides and that a project wanting cuid's exact shape can\n * write itself in one line of SQL.\n */\nexport const idColumnDefault = (propName: string, prop: Property, collection: CollectionConfig): IdColumnDefault | undefined => {\n if (!(\"isId\" in prop)) return undefined;\n const isId = (prop as { isId?: unknown }).isId;\n // `true` and `\"manual\"` both mean \"the application supplies it\".\n if (isId === undefined || isId === null || isId === true || isId === \"manual\" || isId === false) return undefined;\n if (typeof isId !== \"string\") return undefined;\n\n if (prop.type === \"string\" && (isId as StringProperty[\"isId\"]) === \"uuid\") return { kind: \"uuid\" };\n if (prop.type === \"number\" && (isId as NumberProperty[\"isId\"]) === \"increment\") return { kind: \"identity\" };\n\n if (isId === \"cuid\") {\n throw new Error(\n `Property \"${propName}\" of collection \"${collection.slug ?? collection.name ?? \"(unnamed)\"}\" ` +\n \"uses `isId: \\\"cuid\\\"`, which Postgres cannot honour: the generated default calls a `cuid()` \" +\n \"function that Rebase has never created, so every insert relying on it fails. \" +\n \"Use `isId: \\\"uuid\\\"`, or give the strategy as SQL — ``isId: \\\"sql`my_id()`\\\"`` — and create that \" +\n \"function in a migration.\"\n );\n }\n\n // Any other string is a raw SQL default. Written either bare\n // (`gen_random_uuid()::text`) or in the documented template form\n // (``sql`gen_random_uuid()::text` ``); the wrapper is markup, not SQL.\n return { kind: \"sql\", expression: sqlExpressionText(isId) };\n};\n\n/**\n * The SQL inside a template-form expression (``sql`now()` `` → `now()`); a\n * bare expression is returned as it is.\n */\nexport const sqlExpressionText = (value: string): string =>\n value.startsWith(\"sql`\") && value.endsWith(\"`\") && value.length >= 5\n ? value.substring(4, value.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AAqB,UAC9B,MAAM,WAAW,MAAM,KAAK,MAAM,SAAS,GAAG,KAAK,MAAM,UAAU,IAC7D,MAAM,UAAU,GAAG,MAAM,SAAS,CAAC,IACnC"}
1
+ {"version":3,"file":"column-plan-helpers-BeSztMor.js","names":[],"sources":["../src/schema/column-plan-helpers.ts"],"sourcesContent":["/**\n * The questions about a property that the schema planner asks first.\n *\n * What is the primary key, what is this column called, what does an id default\n * to, what labels does this enum have. `schema/plan/plan-schema.ts` is the only\n * caller — it is the only reader of a `Property` — and these live beside it\n * rather than inside it because they are also where the *refusals* are, and a\n * refusal wants to be reachable and testable on its own.\n *\n * They were extracted while there were still three emitters, each carrying its\n * own verbatim copy of all four rules until one of them was edited: the audit\n * that produced this module counted twelve open disagreements and found that a\n * third of the commits touching those files were re-synchronisations. The\n * emitters are renderers now and there is nothing left to keep in step, but the\n * questions are still questions about a property rather than about a plan, so\n * this is where they belong.\n *\n * Everything here is pure and synchronous, and it throws rather than guesses:\n * an enum with no values, a `cuid` id on Postgres and a foreign key into a\n * composite key are all configurations that produce a broken database in\n * silence, so they are refused where every path passes.\n */\nimport type {\n CollectionConfig,\n NumberProperty,\n Property,\n StringProperty\n} from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\n/**\n * Resolve the SQL column name for a property.\n *\n * Uses the explicit `columnName` when set (e.g. from introspection), falling\n * back to `toSnakeCase(propName)` for manually-authored collections.\n */\nexport const resolveColumnName = (propName: string, prop?: Property | null): string => {\n if (prop && \"columnName\" in prop && typeof prop.columnName === \"string\") {\n return prop.columnName;\n }\n return toSnakeCase(propName);\n};\n\n/** Every property that carries a truthy `isId`, in declaration order. */\nconst idPropertyEntries = (collection: CollectionConfig): [string, Property][] =>\n Object.entries(collection.properties ?? {}).filter(\n ([, prop]) => prop && typeof prop === \"object\" && \"isId\" in prop && Boolean((prop as { isId?: unknown }).isId)\n ) as [string, Property][];\n\n/**\n * The properties marked `isId`, in declaration order.\n *\n * Several of them are one composite primary key: the table carries a single\n * `PRIMARY KEY (a, b)` constraint over their columns, and a row's address lists\n * the parts in this same order (`buildCompositeId`), which is the order the\n * admin reads them in too.\n */\nexport const primaryKeyPropertyNames = (collection: CollectionConfig): string[] =>\n idPropertyEntries(collection).map(([name]) => name);\n\n/**\n * A collection's primary key, by both of its names.\n *\n * `name` is the property key — what the generated Drizzle table is keyed by,\n * so it is what a relation's `references` names. `column` is the SQL\n * identifier, so it is what a foreign key's `REFERENCES` names. They differ\n * whenever the key is camelCase or carries a `columnName` (`authorId` is\n * `author_id`, and every table `rebase schema introspect` adopts is spelled\n * that way), and a constraint written with the key named a column that does\n * not exist: `db push` could not build its desired state, and boot failed the\n * constraint on every start.\n */\nexport interface PrimaryKey {\n /** Property key: the Drizzle object key and the JSON field. */\n name: string;\n /** SQL column. */\n column: string;\n /** The declaring property; absent for the implicit `id TEXT` of a collection that declares none. */\n prop?: Property;\n}\n\n/**\n * The one column a link into this collection points at.\n *\n * A foreign key column references a single column, and Postgres only accepts\n * that column when it is unique on its own — `REFERENCES t (a)` against a\n * composite key `(a, b)` fails with \"there is no unique constraint matching\n * given keys for referenced table\". So a link into a collection whose key\n * spans several columns has no column to point at, and it is refused here,\n * naming the link, rather than emitted as a constraint `db push` or boot would\n * then fail to create.\n *\n * @param via the link that needs the column, for the refusal: `relation \"posts.author\"`.\n */\nexport const getPrimaryKeyProp = (collection: CollectionConfig, via: string): PrimaryKey => {\n const ids = idPropertyEntries(collection);\n if (ids.length > 1) {\n throw new Error(\n `${via} points at collection \"${collection.slug ?? collection.name ?? \"(unnamed)\"}\", whose primary ` +\n `key spans ${ids.length} columns (${ids.map(([name]) => `\"${name}\"`).join(\", \")}). A foreign key is ` +\n \"one column and cannot reference a composite key. Point the link at a collection with a \" +\n \"single-column key, or reach these rows with a `via` relation, whose `joinPath` compares every \" +\n \"key column.\"\n );\n }\n const idPropEntry = ids[0];\n if (idPropEntry) {\n const [name, prop] = idPropEntry;\n return { name, column: resolveColumnName(name, prop), prop };\n }\n // Fallback: a collection that declares no `isId` gets an implicit `id`.\n const idProp = collection.properties?.[\"id\"] as Property | undefined;\n return { name: \"id\", column: resolveColumnName(\"id\", idProp), prop: idProp };\n};\n\n/**\n * The primary key's property key. What a Drizzle relation's `references`\n * names. Refused on the same terms as {@link getPrimaryKeyProp}.\n */\nexport const getPrimaryKeyName = (collection: CollectionConfig, via: string): string =>\n getPrimaryKeyProp(collection, via).name;\n\n/**\n * The primary key's column. What a foreign key's `REFERENCES` names. Refused\n * on the same terms as {@link getPrimaryKeyProp}.\n */\nexport const getPrimaryKeyColumn = (collection: CollectionConfig, via: string): string =>\n getPrimaryKeyProp(collection, via).column;\n\nexport const isIdProperty = (propName: string, prop: Property, collection: CollectionConfig): boolean => {\n if (\"isId\" in prop && Boolean(prop.isId)) return true;\n\n // Only fall back to \"id\" when NO property is explicitly marked.\n return idPropertyEntries(collection).length === 0 && propName === \"id\";\n};\n\n/**\n * The labels an `enum` declares, in order, whichever form it was written in.\n *\n * `EnumValues` is `EnumValueConfig[] | Record<id, label>` and the docs recommend\n * the record. Boot-ensure read only the array form — `(p.enum as unknown[]).map`\n * — so a record-form enum threw `p.enum.map is not a function` on a managed\n * tenant, at boot, with no developer in the loop. The other two emitters each\n * carried their own copy of the both-forms walk.\n *\n * An empty list throws rather than returning `[]`. `CREATE TYPE … AS ENUM ()`\n * is not valid SQL, so every emitter \"handled\" it by skipping the type and then\n * typing the column with it anyway: Drizzle referenced an enum variable it never\n * declared (the generated file does not compile), the DDL named a type nothing\n * creates, and boot-ensure's `ADD COLUMN` failed — and add-column is not a\n * survivable action, so the boot died. There is no useful column at the end of\n * any of those paths.\n */\nexport const enumLabelsOf = (propName: string, prop: Property, collection: CollectionConfig): string[] => {\n const values = (prop as { enum?: unknown }).enum;\n if (values === undefined || values === null) return [];\n\n const labels = Array.isArray(values)\n ? values.map((entry: unknown) =>\n String(entry !== null && typeof entry === \"object\" && \"id\" in (entry as Record<string, unknown>)\n ? (entry as Record<string, unknown>).id\n : entry))\n : Object.keys(values as Record<string, unknown>).map(String);\n\n const usable = labels.filter(label => label.length > 0);\n if (usable.length === 0) {\n throw new Error(\n `Property \"${propName}\" of collection \"${collection.slug ?? collection.name ?? \"(unnamed)\"}\" ` +\n \"declares an empty `enum`. A Postgres enum type needs at least one label — \" +\n \"`CREATE TYPE … AS ENUM ()` is not valid SQL — so the column would reference a type \" +\n \"nothing creates. List the values, or drop the `enum` for a plain column.\"\n );\n }\n return usable;\n};\n\n/**\n * Does this property compile to a Postgres enum *type*?\n *\n * Strings only. A `number` property with an `enum` used to create a type on all\n * three paths and then declare the column `NUMERIC`/`INTEGER`, so the type was\n * orphaned the moment it was created and the values it listed were enforced by\n * nothing. The dropdown in the panel is driven by the config, not the column, so\n * nothing is lost by not creating it — and a type no column uses is one more\n * object `db push` has to plan a DROP for.\n */\nexport const declaresEnumType = (prop: Property): boolean =>\n prop.type === \"string\" && Boolean((prop as StringProperty).enum);\n\n/**\n * The `DEFAULT` an id column carries, as the thing itself rather than a\n * rendered string — each emitter spells it differently.\n *\n * The three of them disagreed on all four strategies. The DDL generator wrote\n * `DEFAULT ${prop.isId}` verbatim, so the documented `` isId: \"sql`gen_id()`\" ``\n * reached Postgres with the template wrapper still on it — a syntax error in\n * `schema.sql`. Boot-ensure gave a default to `uuid` and to nothing else, so on\n * a managed tenant every other strategy produced a column with no default at\n * all, and the first insert that trusted the config failed on a NULL primary\n * key. Only the Drizzle generator stripped the wrapper.\n */\nexport type IdColumnDefault =\n /** `gen_random_uuid()` / `.defaultRandom()`. */\n | { kind: \"uuid\" }\n /** `GENERATED BY DEFAULT AS IDENTITY` / `.generatedByDefaultAsIdentity()` — part of the type, not a DEFAULT. */\n | { kind: \"identity\" }\n /** A raw SQL expression, wrapper already stripped. */\n | { kind: \"sql\"; expression: string };\n\n/**\n * Refuses `isId: \"cuid\"`.\n *\n * `DEFAULT cuid()` has been emitted since the option existed and no `cuid()`\n * function has ever been created — not by the generators, not by boot, not by\n * any migration. So the column has never had a working default on Postgres: the\n * first insert that relied on it failed with `function cuid() does not exist`.\n * There is nothing to keep compatible.\n *\n * It is refused rather than implemented. Shipping a real `rebase.cuid()` means a\n * new SQL function in the same carved-out class as the search helpers — excluded\n * from Atlas by pattern, applied by boot, re-applied by push, checked by the\n * doctor, and versioned across the fleet forever — to reproduce a monotonic id\n * that `uuid` already provides and that a project wanting cuid's exact shape can\n * write itself in one line of SQL.\n */\nexport const idColumnDefault = (propName: string, prop: Property, collection: CollectionConfig): IdColumnDefault | undefined => {\n if (!(\"isId\" in prop)) return undefined;\n const isId = (prop as { isId?: unknown }).isId;\n // `true` and `\"manual\"` both mean \"the application supplies it\".\n if (isId === undefined || isId === null || isId === true || isId === \"manual\" || isId === false) return undefined;\n if (typeof isId !== \"string\") return undefined;\n\n if (prop.type === \"string\" && (isId as StringProperty[\"isId\"]) === \"uuid\") return { kind: \"uuid\" };\n if (prop.type === \"number\" && (isId as NumberProperty[\"isId\"]) === \"increment\") return { kind: \"identity\" };\n\n // A strategy keyword on a type that cannot honour it. Without this it fell\n // through to \"any other string is raw SQL\", and `DEFAULT increment` on a\n // TEXT key — or `DEFAULT uuid` on an INTEGER one — names a column that does\n // not exist, refused by Postgres at the first CREATE TABLE.\n if (isId === \"increment\" || isId === \"uuid\") {\n const needs = isId === \"increment\" ? \"number\" : \"string\";\n throw new Error(\n `Property \"${propName}\" of collection \"${collection.slug ?? collection.name ?? \"(unnamed)\"}\" ` +\n `is a ${prop.type} property, and \\`isId: \"${isId}\"\\` needs a ${needs} property. ` +\n (isId === \"increment\"\n ? \"Make the key `type: \\\"number\\\"`, or use `isId: \\\"uuid\\\"` for a string key.\"\n : \"Make the key `type: \\\"string\\\"`, or use `isId: \\\"increment\\\"` for a number key.\")\n );\n }\n\n if (isId === \"cuid\") {\n throw new Error(\n `Property \"${propName}\" of collection \"${collection.slug ?? collection.name ?? \"(unnamed)\"}\" ` +\n \"uses `isId: \\\"cuid\\\"`, which Postgres cannot honour: the generated default calls a `cuid()` \" +\n \"function that Rebase has never created, so every insert relying on it fails. \" +\n \"Use `isId: \\\"uuid\\\"`, or give the strategy as SQL — ``isId: \\\"sql`my_id()`\\\"`` — and create that \" +\n \"function in a migration.\"\n );\n }\n\n // Any other string is a raw SQL default. Written either bare\n // (`gen_random_uuid()::text`) or in the documented template form\n // (``sql`gen_random_uuid()::text` ``); the wrapper is markup, not SQL.\n return { kind: \"sql\", expression: sqlExpressionText(isId) };\n};\n\n/**\n * The SQL inside a template-form expression (``sql`now()` `` → `now()`); a\n * bare expression is returned as it is.\n */\nexport const sqlExpressionText = (value: string): string =>\n value.startsWith(\"sql`\") && value.endsWith(\"`\") && value.length >= 5\n ? value.substring(4, value.length - 1)\n : value;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,qBAAqB,UAAkB,SAAmC;CACnF,IAAI,QAAQ,gBAAgB,QAAQ,OAAO,KAAK,eAAe,UAC3D,OAAO,KAAK;CAEhB,OAAO,YAAY,QAAQ;AAC/B;;AAGA,IAAM,qBAAqB,eACvB,OAAO,QAAQ,WAAW,cAAc,CAAC,CAAC,CAAC,CAAC,QACvC,GAAG,UAAU,QAAQ,OAAO,SAAS,YAAY,UAAU,QAAQ,QAAS,KAA4B,IAAI,CACjH;;;;;;;;;AAUJ,IAAa,2BAA2B,eACpC,kBAAkB,UAAU,CAAC,CAAC,KAAK,CAAC,UAAU,IAAI;;;;;;;;;;;;;;AAoCtD,IAAa,qBAAqB,YAA8B,QAA4B;CACxF,MAAM,MAAM,kBAAkB,UAAU;CACxC,IAAI,IAAI,SAAS,GACb,MAAM,IAAI,MACN,GAAG,IAAI,yBAAyB,WAAW,QAAQ,WAAW,QAAQ,YAAY,6BACrE,IAAI,OAAO,YAAY,IAAI,KAAK,CAAC,UAAU,IAAI,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,yNAIpF;CAEJ,MAAM,cAAc,IAAI;CACxB,IAAI,aAAa;EACb,MAAM,CAAC,MAAM,QA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,KAAa,SAAS,QAAQ,SAAS,QAAQ,SAAS,YAAY,SAAS,OAAO,OAAO,KAAA;CACxG,IAAI,OAAO,SAAS,UAAU,OAAO,KAAA;CAErC,IAAI,KAAK,SAAS,YAAa,SAAoC,QAAQ,OAAO,EAAE,MAAM,OAAO;CACjG,IAAI,KAAK,SAAS,YAAa,SAAoC,aAAa,OAAO,EAAE,MAAM,WAAW;CAM1G,IAAI,SAAS,eAAe,SAAS,QAAQ;EACzC,MAAM,QAAQ,SAAS,cAAc,WAAW;EAChD,MAAM,IAAI,MACN,aAAa,SAAS,mBAAmB,WAAW,QAAQ,WAAW,QAAQ,YAAY,SACnF,KAAK,KAAK,0BAA0B,KAAK,cAAc,MAAM,gBACpE,SAAS,cACJ,+EACA,kFACV;CACJ;CAEA,IAAI,SAAS,QACT,MAAM,IAAI,MACN,aAAa,SAAS,mBAAmB,WAAW,QAAQ,WAAW,QAAQ,YAAY,2SAK/F;CAMJ,OAAO;EAAE,MAAM;EAAO,YAAY,kBAAkB,IAAI;CAAE;AAC9D;;;;;AAMA,IAAa,qBAAqB,UAC9B,MAAM,WAAW,MAAM,KAAK,MAAM,SAAS,GAAG,KAAK,MAAM,UAAU,IAC7D,MAAM,UAAU,GAAG,MAAM,SAAS,CAAC,IACnC"}
@@ -34,7 +34,17 @@ export interface SerializedEntityData {
34
34
  }>;
35
35
  }
36
36
  /**
37
- * Helper function to sanitize and convert dates to ISO strings
37
+ * The last pass over a row before it is written: `undefined` and `NaN` become
38
+ * `null`, a `Date` becomes its ISO string, recursively through arrays and
39
+ * objects.
40
+ *
41
+ * Strings are left as they came. This pass knows no property types, and a
42
+ * string is text unless its property says otherwise: reading `"Nan"` as a
43
+ * failed number nulled a person's name, and re-printing anything shaped like
44
+ * an ISO timestamp cut the microseconds out of text that happened to hold one.
45
+ * The coercions a string *does* need are made by its property, in
46
+ * {@link serializePropertyToServer}: `"NaN"` on a `number`, a date's text on a
47
+ * `date`.
38
48
  */
39
49
  export declare function sanitizeAndConvertDates(obj: unknown): unknown;
40
50
  /**
@@ -16,7 +16,7 @@ var DatabasePoolManager = class {
16
16
  this.rootConnectionString = adminConnectionString;
17
17
  try {
18
18
  const url = new URL(adminConnectionString);
19
- this.defaultDatabaseName = url.pathname.slice(1);
19
+ this.defaultDatabaseName = decodeURI(url.pathname.slice(1));
20
20
  } catch (e) {
21
21
  throw new Error(`Invalid adminConnectionString provided: ${e}`);
22
22
  }
@@ -114,4 +114,4 @@ var DatabasePoolManager = class {
114
114
  //#endregion
115
115
  export { databasePoolManager_exports as n, DatabasePoolManager as t };
116
116
 
117
- //# sourceMappingURL=databasePoolManager-3stMNFL-.js.map
117
+ //# sourceMappingURL=databasePoolManager-BjoVvuAq.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"databasePoolManager-BjoVvuAq.js","names":[],"sources":["../src/databasePoolManager.ts"],"sourcesContent":["import { Pool } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport { logger } from \"@rebasepro/server\";\nimport { guardPoolAgainstDirtyRelease, pinSearchPath, cappedPoolMax, defaultPoolTimeouts } from \"./connection\";\nimport { reportPoolError } from \"./pool-disconnects\";\n\nexport class DatabasePoolManager {\n private pools: Map<string, Pool> = new Map();\n private drizzleInstances: Map<string, NodePgDatabase> = new Map();\n public readonly defaultDatabaseName: string;\n private readonly rootConnectionString: string;\n\n constructor(adminConnectionString: string) {\n this.rootConnectionString = adminConnectionString;\n try {\n const url = new URL(adminConnectionString);\n // Decoded as pg decodes it to connect (`decodeURI`): the URL holds\n // `caf%C3%A9` for the database `café`, and this name is used as an\n // SQL identifier and as the key of the pool `getPool` builds back\n // from it.\n this.defaultDatabaseName = decodeURI(url.pathname.slice(1));\n } catch (e) {\n throw new Error(`Invalid adminConnectionString provided: ${e}`);\n }\n }\n\n public getDrizzle(databaseName: string): NodePgDatabase<Record<string, never>> {\n const existing = this.drizzleInstances.get(databaseName);\n if (existing) {\n return existing;\n }\n\n const pool = this.getPool(databaseName);\n const db = drizzle(pool);\n this.drizzleInstances.set(databaseName, db);\n return db;\n }\n\n public getPool(databaseName: string): Pool {\n if (this.pools.has(databaseName)) {\n return this.pools.get(databaseName)!;\n }\n\n const url = new URL(this.rootConnectionString);\n url.pathname = `/${databaseName}`;\n\n const pool = new Pool({\n // Same pin as the primary pool: these are branch/multi-database\n // connections to the *same* server, so they inherit the same\n // `\"$user\"` hazard. See `pinSearchPath`.\n connectionString: pinSearchPath(url.toString()),\n // Capped by REBASE_DB_POOL_MAX, which the managed development\n // database sets to 1: PGlite multiplexes onto a single session and\n // overlapping transactions deadlock there.\n max: cappedPoolMax(10),\n idleTimeoutMillis: 10000, // Reduced from 30000 for aggressive cleanup\n allowExitOnIdle: true, // Prevent idle clients from hanging the Node.js process\n // The main pool's limits: a full pool answers 503 after 10 s rather\n // than queueing forever, and a statement stops at 30 s server-side.\n ...defaultPoolTimeouts()\n });\n\n // Prevent idle client errors from crashing the Node.js process\n pool.on(\"error\", (err) => reportPoolError(`DatabasePoolManager:${databaseName}`, err));\n guardPoolAgainstDirtyRelease(pool, `pg-pool:${databaseName}`);\n\n this.pools.set(databaseName, pool);\n return pool;\n }\n\n /**\n * Disconnect and remove the pool for a specific database.\n * Required before `CREATE DATABASE ... TEMPLATE` or `DROP DATABASE`,\n * which need exclusive access to the target database.\n */\n public async disconnectDatabase(databaseName: string): Promise<void> {\n const pool = this.pools.get(databaseName);\n if (pool) {\n await pool.end();\n this.pools.delete(databaseName);\n this.drizzleInstances.delete(databaseName);\n }\n }\n\n /** Check if a pool exists for a given database name. */\n public hasPool(databaseName: string): boolean {\n return this.pools.has(databaseName);\n }\n\n /**\n * Does this server serve exactly one database?\n *\n * The managed development database is PGlite, and PGlite serves exactly\n * one. `CREATE DATABASE \"rb_feature\" TEMPLATE \"postgres\"` there writes a\n * `pg_database` catalogue row and nothing else: nothing errors, the row is\n * listable, `pg_database_size` answers — and connecting to the \"branch\"\n * lands you in the parent. Every write made in the belief that it is\n * sandboxed goes to the developer's real development database.\n *\n * The CLI already refuses `rebase db branch` on this ground, but it does it\n * by parsing argv, so Studio — which reaches `BranchService` over the\n * websocket — walked straight past it. The connection is the only thing\n * both callers share, so the answer belongs here.\n *\n * Measured, not assumed: `select version()` over the PGlite socket returns\n * `PostgreSQL 18.3 (PGlite 0.5.6) on wasm32-…`, which is how a wasm build\n * announces itself and what `dev-db/constraints.ts` documents. A real\n * Postgres never carries `(PGlite `.\n *\n * Cached, because a live connection cannot change engine underneath us, and\n * a `PostgresBackendDriver` — which builds a `BranchService` — is\n * constructed per transaction.\n */\n public servesOneDatabase(): Promise<boolean> {\n this.oneDatabaseProbe ??= this.probeOneDatabase();\n return this.oneDatabaseProbe;\n }\n\n private oneDatabaseProbe?: Promise<boolean>;\n\n private async probeOneDatabase(): Promise<boolean> {\n try {\n const result = await this.getPool(this.defaultDatabaseName)\n .query<{ version: string }>(\"SELECT version() AS version\");\n return /\\(PGlite\\b/i.test(result.rows[0]?.version ?? \"\");\n } catch (err) {\n // Fail open, and do not cache the failure. The cost of a wrong\n // \"yes\" is refusing branching on a real Postgres that momentarily\n // could not answer; the cost of a wrong \"no\" is one fake branch,\n // which is what this exists to prevent — but a server that cannot\n // run `select version()` is not one we can conclude anything about.\n this.oneDatabaseProbe = undefined;\n logger.warn(\"[DatabasePoolManager] Could not read the server version\", { error: err });\n return false;\n }\n }\n\n public async shutdown(): Promise<void> {\n const promises = [];\n for (const [dbName, pool] of this.pools.entries()) {\n // Debug: every CLI command that reaches a database ends here, and\n // the reader of `rebase db branch create` did not ask about pools.\n logger.debug(`[DatabasePoolManager] Shutting down pool for ${dbName}`);\n promises.push(pool.end());\n }\n await Promise.all(promises);\n this.pools.clear();\n this.drizzleInstances.clear();\n }\n}\n"],"mappings":";;;;;;;;;AAOA,IAAa,sBAAb,MAAiC;CAC7B,wBAAmC,IAAI,IAAI;CAC3C,mCAAwD,IAAI,IAAI;CAChE;CACA;CAEA,YAAY,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AChB;CAEA;CAEA,MAAc,mBAAqC;EAC/C,IAAI;GACA,MAAM,SAAS,MAAM,KAAK,QAAQ,KAAK,mBAAmB,CAAC,CACtD,MAA2B,6BAA6B;GAC7D,OAAO,cAAc,KAAK,OAAO,KAAK,EAAE,EAAE,WAAW,EAAE;EAC3D,SAAS,KAAK;GAMV,KAAK,mBAAmB,KAAA;GACxB,OAAO,KAAK,2DAA2D,EAAE,OAAO,IAAI,CAAC;GACrF,OAAO;EACX;CACJ;CAEA,MAAa,WAA0B;EACnC,MAAM,WAAW,CAAC;EAClB,KAAK,MAAM,CAAC,QAAQ,SAAS,KAAK,MAAM,QAAQ,GAAG;GAG/C,OAAO,MAAM,gDAAgD,QAAQ;GACrE,SAAS,KAAK,KAAK,IAAI,CAAC;EAC5B;EACA,MAAM,QAAQ,IAAI,QAAQ;EAC1B,KAAK,MAAM,MAAM;EACjB,KAAK,iBAAiB,MAAM;CAChC;AACJ"}
@@ -2,12 +2,12 @@ import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
3
  import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
4
4
  import { h as searchIndexStatements, n as SEARCH_TEXT_FN, r as SEARCH_UNACCENT_FN, u as searchColumnStamps } from "./search-column-BM-GV6vH.js";
5
- import { n as extractPgError } from "./pg-error-utils-DhiUTlVx.js";
5
+ import { n as extractPgError } from "./pg-error-utils-BIHfsGZL.js";
6
6
  import { u as vectorIndexStatement } from "./vector-index-DsQ3V2d2.js";
7
7
  import { _ as sortIndexSpecs, l as collectionIndexStatement } from "./source-fZb92pN8.js";
8
- import { a as triggerStatements, i as SET_UPDATED_AT_FN, r as quoteSqlLiteral } from "./plan-schema-Czf3q4-Q.js";
9
- import { n as renderEnableRls, r as renderPgType, s as renderPrimaryKeyConstraint, t as renderColumnDefinition } from "./render-ddl-4v88y-Gv.js";
10
- import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, o as isMultiStatementRefusal, r as atomicBatch } from "./boot-ddl-EsgqDkx0.js";
8
+ import { a as triggerStatements, i as SET_UPDATED_AT_FN, r as quoteSqlLiteral } from "./plan-schema-DMVh77yb.js";
9
+ import { c as renderPrimaryKeyConstraint, i as renderPgType, r as renderEnableRls, t as renderColumnDefinition } from "./render-ddl-NpPPDACz.js";
10
+ import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, o as isMultiStatementRefusal, r as atomicBatch } from "./boot-ddl-CIGoIGcC.js";
11
11
  import { logger } from "@rebasepro/server";
12
12
  //#region src/schema/column-type-drift.ts
13
13
  /**
@@ -1048,4 +1048,4 @@ function scheduleDeferredIndexBuild(openSession, indexes, options = {}) {
1048
1048
  //#endregion
1049
1049
  export { assertSafeIdentifier as a, helperFunctionKey as c, HELPER_FUNCTIONS as i, columnTypeDriftMessage as l, buildDeferredIndexes as n, describeHelperFunction as o, deferred_index_build_exports as r, diffPlanAgainstCatalogue as s, TABLE_BUSY_REASON as t, typesAgree as u };
1050
1050
 
1051
- //# sourceMappingURL=deferred-index-build-CqaOv1Xx.js.map
1051
+ //# sourceMappingURL=deferred-index-build-BcJ_oulu.js.map