@prisma-next/target-postgres 0.16.0-dev.22 → 0.16.0-dev.23

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 (92) hide show
  1. package/dist/{authoring-34L18kA1.mjs → authoring-BCzcFRay.mjs} +27 -9
  2. package/dist/authoring-BCzcFRay.mjs.map +1 -0
  3. package/dist/codecs-CGE5dh94.d.mts.map +1 -1
  4. package/dist/{codecs-DOgD_C1A.mjs → codecs-Deand7sy.mjs} +75 -19
  5. package/dist/codecs-Deand7sy.mjs.map +1 -0
  6. package/dist/codecs.mjs +1 -1
  7. package/dist/contract-free.mjs +2 -2
  8. package/dist/{control-policy-BrcqeM82.mjs → control-policy-B-_34g05.mjs} +8 -7
  9. package/dist/control-policy-B-_34g05.mjs.map +1 -0
  10. package/dist/control.mjs +28 -17
  11. package/dist/control.mjs.map +1 -1
  12. package/dist/{ddl-DHXKzQ99.mjs → ddl-DYEob9xQ.mjs} +2 -2
  13. package/dist/{ddl-DHXKzQ99.mjs.map → ddl-DYEob9xQ.mjs.map} +1 -1
  14. package/dist/{descriptor-meta-CiYV9DzH.mjs → descriptor-meta-D_0ZKcj-.mjs} +4 -4
  15. package/dist/{descriptor-meta-CiYV9DzH.mjs.map → descriptor-meta-D_0ZKcj-.mjs.map} +1 -1
  16. package/dist/{diff-database-schema-CK0FM2Z-.mjs → diff-database-schema-C9H09OD3.mjs} +17 -6
  17. package/dist/diff-database-schema-C9H09OD3.mjs.map +1 -0
  18. package/dist/diff-database-schema.mjs +1 -1
  19. package/dist/{errors-ByDS0xJL.mjs → errors-DBSNx7EJ.mjs} +6 -2
  20. package/dist/errors-DBSNx7EJ.mjs.map +1 -0
  21. package/dist/errors.d.mts +1 -0
  22. package/dist/errors.d.mts.map +1 -1
  23. package/dist/errors.mjs +1 -1
  24. package/dist/issue-planner.mjs +1 -1
  25. package/dist/migration.mjs +2 -2
  26. package/dist/{op-factory-call-PBYfcv8h.mjs → op-factory-call-BVYLIojV.mjs} +49 -38
  27. package/dist/op-factory-call-BVYLIojV.mjs.map +1 -0
  28. package/dist/op-factory-call-DT7kdjVP.d.mts.map +1 -1
  29. package/dist/op-factory-call.mjs +1 -1
  30. package/dist/pack.d.mts.map +1 -1
  31. package/dist/pack.mjs +1 -1
  32. package/dist/{planner-CiXCo6BT.mjs → planner-4sj5cJCY.mjs} +7 -7
  33. package/dist/{planner-CiXCo6BT.mjs.map → planner-4sj5cJCY.mjs.map} +1 -1
  34. package/dist/{planner-ddl-builders-AIpFmG1i.mjs → planner-ddl-builders-CVo3L7Nd.mjs} +11 -7
  35. package/dist/planner-ddl-builders-CVo3L7Nd.mjs.map +1 -0
  36. package/dist/planner-ddl-builders.d.mts.map +1 -1
  37. package/dist/planner-ddl-builders.mjs +1 -1
  38. package/dist/{planner-produced-postgres-migration-PIgjJYrY.mjs → planner-produced-postgres-migration-CcQPDWmX.mjs} +3 -3
  39. package/dist/{planner-produced-postgres-migration-PIgjJYrY.mjs.map → planner-produced-postgres-migration-CcQPDWmX.mjs.map} +1 -1
  40. package/dist/planner-produced-postgres-migration.mjs +1 -1
  41. package/dist/{planner-sql-checks-BuB877wH.mjs → planner-sql-checks-CmiQ6Nei.mjs} +3 -3
  42. package/dist/{planner-sql-checks-BuB877wH.mjs.map → planner-sql-checks-CmiQ6Nei.mjs.map} +1 -1
  43. package/dist/planner-sql-checks.mjs +1 -1
  44. package/dist/planner.d.mts.map +1 -1
  45. package/dist/planner.mjs +2 -2
  46. package/dist/{postgres-contract-view-DebHMqGR.mjs → postgres-contract-view-B8yXVWYe.mjs} +3 -3
  47. package/dist/{postgres-contract-view-DebHMqGR.mjs.map → postgres-contract-view-B8yXVWYe.mjs.map} +1 -1
  48. package/dist/postgres-migration-DLIvzHjX.d.mts.map +1 -1
  49. package/dist/{postgres-migration-BkIplcRz.mjs → postgres-migration-GIOABsAa.mjs} +5 -5
  50. package/dist/{postgres-migration-BkIplcRz.mjs.map → postgres-migration-GIOABsAa.mjs.map} +1 -1
  51. package/dist/{postgres-schema-CewLYHB7.mjs → postgres-schema-CTplQZDK.mjs} +2 -2
  52. package/dist/{postgres-schema-CewLYHB7.mjs.map → postgres-schema-CTplQZDK.mjs.map} +1 -1
  53. package/dist/{render-ops-BREh1kHe.mjs → render-ops-TcY9XEkz.mjs} +7 -2
  54. package/dist/render-ops-TcY9XEkz.mjs.map +1 -0
  55. package/dist/render-ops.d.mts.map +1 -1
  56. package/dist/render-ops.mjs +1 -1
  57. package/dist/{resolve-ddl-schema-D0wi_P9Q.mjs → resolve-ddl-schema-BAsJEKW8.mjs} +2 -2
  58. package/dist/{resolve-ddl-schema-D0wi_P9Q.mjs.map → resolve-ddl-schema-BAsJEKW8.mjs.map} +1 -1
  59. package/dist/runtime.mjs +1 -1
  60. package/dist/schema-ir-annotations.mjs +1 -1
  61. package/dist/{sql-utils-SU4FDvIV.mjs → sql-utils-B2lzkKfP.mjs} +22 -19
  62. package/dist/sql-utils-B2lzkKfP.mjs.map +1 -0
  63. package/dist/sql-utils.d.mts +4 -9
  64. package/dist/sql-utils.d.mts.map +1 -1
  65. package/dist/sql-utils.mjs +2 -2
  66. package/dist/types.mjs +1 -1
  67. package/package.json +20 -20
  68. package/src/core/authoring.ts +28 -7
  69. package/src/core/codec-helpers.ts +69 -16
  70. package/src/core/codecs.ts +11 -2
  71. package/src/core/errors.ts +30 -0
  72. package/src/core/migrations/column-ddl-rendering.ts +2 -1
  73. package/src/core/migrations/contract-to-postgres-database-schema-node.ts +14 -2
  74. package/src/core/migrations/op-factory-call.ts +88 -29
  75. package/src/core/migrations/operations/constraints.ts +3 -2
  76. package/src/core/migrations/operations/indexes.ts +4 -1
  77. package/src/core/migrations/operations/rls.ts +4 -1
  78. package/src/core/migrations/planner-ddl-builders.ts +13 -4
  79. package/src/core/migrations/render-ops.ts +4 -1
  80. package/src/core/migrations/runner.ts +7 -3
  81. package/src/core/psl-infer/infer-psl-contract.ts +22 -6
  82. package/src/core/sql-utils.ts +16 -27
  83. package/src/exports/sql-utils.ts +0 -1
  84. package/dist/authoring-34L18kA1.mjs.map +0 -1
  85. package/dist/codecs-DOgD_C1A.mjs.map +0 -1
  86. package/dist/control-policy-BrcqeM82.mjs.map +0 -1
  87. package/dist/diff-database-schema-CK0FM2Z-.mjs.map +0 -1
  88. package/dist/errors-ByDS0xJL.mjs.map +0 -1
  89. package/dist/op-factory-call-PBYfcv8h.mjs.map +0 -1
  90. package/dist/planner-ddl-builders-AIpFmG1i.mjs.map +0 -1
  91. package/dist/render-ops-BREh1kHe.mjs.map +0 -1
  92. package/dist/sql-utils-SU4FDvIV.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { b as PG_TEXT_CODEC_ID } from "./codec-ids-D3G8K0YM.mjs";
2
- import { i as postgresCreateNamespace, l as PostgresTableSource } from "./postgres-schema-CewLYHB7.mjs";
2
+ import { i as postgresCreateNamespace, l as PostgresTableSource } from "./postgres-schema-CTplQZDK.mjs";
3
3
  import { a as PostgresCreatePolicy, c as PostgresCreateType, d as PostgresDropPolicy, f as PostgresDropType, i as PostgresAlterTable, n as DropDefaultAction, o as PostgresCreateSchema, r as PostgresAlterPolicyRename, s as PostgresCreateTable, t as AddColumnAction, u as PostgresDisableRowLevelSecurity } from "./nodes-DJC5B8Id.mjs";
4
4
  import { cfExpr, cfTable, exprSelect } from "@prisma-next/sql-relational-core/contract-free";
5
5
  //#region src/contract-free/checks.ts
@@ -370,4 +370,4 @@ function disableRowLevelSecurity(options) {
370
370
  //#endregion
371
371
  export { rlsPolicyExistsAst as C, toRegclass as D, tablePrimaryKeyAst as E, rlsEnabledAst as S, tableIsEmptyAst as T, extensionExistsAst as _, createSchema as a, nativeEnumValueExistsAst as b, disableRowLevelSecurity as c, dropType as d, columnDefaultAst as f, constraintExistsAst as g, columnTypeAst as h, createPolicy as i, dropDefaultAction as l, columnNullabilityAst as m, alterPolicyRename as n, createTable as o, columnExistsAst as p, alterTable as r, createType as s, addColumnAction as t, dropPolicy as u, indexExistsAst as v, tableExistsAst as w, noNullValuesAst as x, nativeEnumTypeExistsAst as y };
372
372
 
373
- //# sourceMappingURL=ddl-DHXKzQ99.mjs.map
373
+ //# sourceMappingURL=ddl-DYEob9xQ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ddl-DHXKzQ99.mjs","names":[],"sources":["../src/contract-free/checks.ts","../src/contract-free/ddl.ts"],"sourcesContent":["import type { SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport {\n type CfExpr,\n type CfExprSelectQuery,\n cfExpr,\n cfTable,\n exprSelect,\n} from '@prisma-next/sql-relational-core/contract-free';\nimport { PostgresTableSource } from '../core/ast/table-source';\nimport { PG_TEXT_CODEC_ID } from '../core/codec-ids';\nimport { postgresCreateNamespace } from '../core/postgres-schema';\n\n/**\n * `to_regclass($1)` with the qualified table name bound as a text parameter.\n * Thin vocabulary wrapper over the core `cfExpr.fn` helper — the target\n * supplies only the template and the codec'd operand.\n */\nexport function toRegclass(qualifiedName: string): CfExpr {\n return cfExpr.fn({\n method: 'to_regclass',\n template: 'to_regclass({{self}})',\n self: cfExpr.param(qualifiedName, PG_TEXT_CODEC_ID),\n returns: { codecId: PG_TEXT_CODEC_ID, nullable: true },\n });\n}\n\nexport interface TableExistsCheckBuilder {\n tableAbsent(): SelectAst;\n tablePresent(): SelectAst;\n}\n\n/**\n * Typed builder for the migration planner's table-existence checks. Produces\n * FROM-less `SELECT to_regclass($1) IS [NOT] NULL AS \"result\"` ASTs with the\n * qualified table name bound as a text parameter — never inlined into the SQL.\n *\n * `schema` is a namespace coordinate: the framework `__unbound__` sentinel\n * elides the qualifier (search_path decides at runtime); any other id\n * qualifies as `\"schema\".\"table\"`.\n */\nexport function tableExistsAst(schema: string, table: string): TableExistsCheckBuilder {\n const qualified = postgresCreateNamespace({ id: schema, entries: { table: {} } }).qualifyTable(\n table,\n );\n const regclass = toRegclass(qualified);\n return {\n tableAbsent: () => exprSelect().project('result', regclass.isNull()).build(),\n tablePresent: () => exprSelect().project('result', regclass.isNotNull()).build(),\n };\n}\n\nexport interface ConstraintExistsCheckBuilder {\n constraintPresent(): SelectAst;\n constraintAbsent(): SelectAst;\n}\n\n/**\n * Typed builder for the migration planner's constraint-existence checks.\n * Produces `SELECT [NOT ]EXISTS (SELECT 1 FROM pg_constraint c JOIN\n * pg_namespace n ON n.oid = c.connamespace WHERE c.conname = $1 AND\n * n.nspname = $2 [AND c.conrelid = to_regclass($3)]) AS \"result\"` with the\n * constraint name, schema name, and qualified table name bound as text\n * parameters.\n *\n * When `table` is omitted the check matches by name + schema across all\n * tables. Pass `table` to scope the check to a single table (prevents false\n * matches on identically-named constraints in different tables). `schema`\n * is a namespace coordinate: the `__unbound__` sentinel compares `nspname`\n * against `current_schema()` instead of a bound parameter.\n */\nexport function constraintExistsAst(options: {\n readonly constraintName: string;\n readonly schema: string;\n readonly table?: string;\n}): ConstraintExistsCheckBuilder {\n const namespace = postgresCreateNamespace({ id: options.schema, entries: { table: {} } });\n const conditions = [\n cfExpr.columnRef('c', 'conname').eqParam(options.constraintName, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('n', 'nspname').eqExpr(namespace.schemaFilterExpression()),\n ];\n if (options.table !== undefined) {\n conditions.push(\n cfExpr.columnRef('c', 'conrelid').eqExpr(toRegclass(namespace.qualifyTable(options.table))),\n );\n }\n const inner = (): CfExprSelectQuery =>\n exprSelect()\n .from(cfTable('pg_constraint', 'c'))\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('c', 'connamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(cfExpr.allOf(conditions));\n return {\n constraintPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n constraintAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nfunction checkNamespace(schema: string) {\n return postgresCreateNamespace({ id: schema, entries: { table: {} } });\n}\n\nfunction informationSchemaColumns(): PostgresTableSource {\n return new PostgresTableSource({ schema: 'information_schema', name: 'columns' });\n}\n\nfunction infoSchemaColumnConditions(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n}): CfExpr[] {\n return [\n cfExpr\n .identifierRef('table_schema')\n .eqExpr(checkNamespace(options.schema).schemaFilterExpression()),\n cfExpr.identifierRef('table_name').eqParam(options.table, PG_TEXT_CODEC_ID),\n cfExpr.identifierRef('column_name').eqParam(options.column, PG_TEXT_CODEC_ID),\n ];\n}\n\nfunction infoSchemaColumnQuery(conditions: ReadonlyArray<CfExpr>): CfExprSelectQuery {\n return exprSelect()\n .from(informationSchemaColumns())\n .project('one', cfExpr.lit(1))\n .where(cfExpr.allOf(conditions));\n}\n\nexport interface ColumnExistsCheckBuilder {\n columnPresent(): SelectAst;\n columnAbsent(): SelectAst;\n}\n\n/**\n * Typed builder for column-existence checks over\n * `information_schema.columns`, with schema, table, and column names bound\n * as text parameters.\n */\nexport function columnExistsAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n}): ColumnExistsCheckBuilder {\n const inner = () => infoSchemaColumnQuery(infoSchemaColumnConditions(options));\n return {\n columnPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n columnAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\n/**\n * Typed nullability check: EXISTS over `information_schema.columns` with\n * `is_nullable` compared against the bound `'YES'` / `'NO'` marker.\n */\nexport function columnNullabilityAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly nullable: boolean;\n}): SelectAst {\n const conditions = [\n ...infoSchemaColumnConditions(options),\n cfExpr.identifierRef('is_nullable').eqParam(options.nullable ? 'YES' : 'NO', PG_TEXT_CODEC_ID),\n ];\n return exprSelect()\n .project('result', cfExpr.exists(infoSchemaColumnQuery(conditions)))\n .build();\n}\n\nexport interface ColumnDefaultCheckBuilder {\n defaultPresent(): SelectAst;\n defaultAbsent(): SelectAst;\n noDefault(): SelectAst;\n}\n\n/**\n * Typed default-presence checks over `information_schema.columns`.\n * `defaultPresent` / `defaultAbsent` assert the column row exists with a\n * non-null / null `column_default`; `noDefault` is the NOT EXISTS variant\n * (also true when the column row is missing entirely).\n */\nexport function columnDefaultAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n}): ColumnDefaultCheckBuilder {\n const withDefault = () =>\n infoSchemaColumnQuery([\n ...infoSchemaColumnConditions(options),\n cfExpr.identifierRef('column_default').isNotNull(),\n ]);\n const withoutDefault = () =>\n infoSchemaColumnQuery([\n ...infoSchemaColumnConditions(options),\n cfExpr.identifierRef('column_default').isNull(),\n ]);\n return {\n defaultPresent: () => exprSelect().project('result', cfExpr.exists(withDefault())).build(),\n defaultAbsent: () => exprSelect().project('result', cfExpr.exists(withoutDefault())).build(),\n noDefault: () => exprSelect().project('result', cfExpr.notExists(withDefault())).build(),\n };\n}\n\n/**\n * Typed column-type check: EXISTS over `pg_attribute` joined to `pg_class`\n * and `pg_namespace`, comparing `format_type(a.atttypid, a.atttypmod)`\n * against the bound expected display type and excluding dropped columns.\n */\nexport function columnTypeAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly expectedType: string;\n}): SelectAst {\n const formatType = cfExpr.fn({\n method: 'format_type',\n template: 'format_type({{self}}, {{arg0}})',\n self: cfExpr.columnRef('a', 'atttypid'),\n args: [cfExpr.columnRef('a', 'atttypmod')],\n returns: { codecId: PG_TEXT_CODEC_ID, nullable: false },\n });\n const inner = exprSelect()\n .from(cfTable('pg_attribute', 'a'))\n .join(\n cfTable('pg_class', 'c'),\n cfExpr.columnRef('c', 'oid').eqExpr(cfExpr.columnRef('a', 'attrelid')),\n )\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('c', 'relnamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr\n .columnRef('n', 'nspname')\n .eqExpr(checkNamespace(options.schema).schemaFilterExpression()),\n cfExpr.columnRef('c', 'relname').eqParam(options.table, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('a', 'attname').eqParam(options.column, PG_TEXT_CODEC_ID),\n formatType.eqParam(options.expectedType, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('a', 'attisdropped').not(),\n ]),\n );\n return exprSelect().project('result', cfExpr.exists(inner)).build();\n}\n\nexport interface TablePrimaryKeyCheckBuilder {\n pkPresent(): SelectAst;\n pkAbsent(): SelectAst;\n}\n\n/**\n * Typed primary-key existence check over `pg_index` joined to `pg_class`\n * and `pg_namespace`, with a LEFT JOIN on the index relation so an\n * optional `constraintName` can scope the match to a named constraint.\n */\nexport function tablePrimaryKeyAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraintName?: string;\n}): TablePrimaryKeyCheckBuilder {\n const conditions = [\n cfExpr\n .columnRef('n', 'nspname')\n .eqExpr(checkNamespace(options.schema).schemaFilterExpression()),\n cfExpr.columnRef('c', 'relname').eqParam(options.table, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('i', 'indisprimary'),\n ];\n if (options.constraintName !== undefined) {\n conditions.push(\n cfExpr.columnRef('c2', 'relname').eqParam(options.constraintName, PG_TEXT_CODEC_ID),\n );\n }\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_index', 'i'))\n .join(\n cfTable('pg_class', 'c'),\n cfExpr.columnRef('c', 'oid').eqExpr(cfExpr.columnRef('i', 'indrelid')),\n )\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('c', 'relnamespace')),\n )\n .leftJoin(\n cfTable('pg_class', 'c2'),\n cfExpr.columnRef('c2', 'oid').eqExpr(cfExpr.columnRef('i', 'indexrelid')),\n )\n .project('one', cfExpr.lit(1))\n .where(cfExpr.allOf(conditions));\n return {\n pkPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n pkAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\n/**\n * Typed emptiness check: NOT EXISTS over the user table itself with\n * `LIMIT 1`. The table is addressed through the namespace's polymorphic\n * `tableSource` (qualified for named schemas, bare for the unbound slot).\n */\nexport function tableIsEmptyAst(schema: string, table: string): SelectAst {\n const inner = exprSelect()\n .from(checkNamespace(schema).tableSource(table))\n .project('one', cfExpr.lit(1))\n .limit(1);\n return exprSelect().project('result', cfExpr.notExists(inner)).build();\n}\n\n/**\n * Typed no-NULL-values data check used by `SET NOT NULL` prechecks:\n * NOT EXISTS over the user table where the column IS NULL.\n */\nexport function noNullValuesAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n}): SelectAst {\n const inner = exprSelect()\n .from(checkNamespace(options.schema).tableSource(options.table))\n .project('one', cfExpr.lit(1))\n .where(cfExpr.identifierRef(options.column).isNull());\n return exprSelect().project('result', cfExpr.notExists(inner)).build();\n}\n\nexport interface ExtensionExistsCheckBuilder {\n extensionPresent(): SelectAst;\n extensionAbsent(): SelectAst;\n}\n\n/**\n * Typed extension existence check over `pg_extension`, with the extension\n * name bound as a text parameter.\n */\nexport function extensionExistsAst(extensionName: string): ExtensionExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_extension'))\n .project('one', cfExpr.lit(1))\n .where(cfExpr.identifierRef('extname').eqParam(extensionName, PG_TEXT_CODEC_ID));\n return {\n extensionPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n extensionAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nexport interface RlsPolicyExistsCheckBuilder {\n policyPresent(): SelectAst;\n policyAbsent(): SelectAst;\n}\n\n/**\n * Typed RLS-policy existence check over `pg_policies`, with schema, table,\n * and policy names bound as text parameters (never inlined). The `schema`\n * coordinate is the resolved live-database schema name (e.g. `'public'`),\n * compared against `pg_policies.schemaname` as a bound parameter.\n */\nexport function rlsPolicyExistsAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly policyName: string;\n}): RlsPolicyExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_policies'))\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr.identifierRef('schemaname').eqParam(options.schema, PG_TEXT_CODEC_ID),\n cfExpr.identifierRef('tablename').eqParam(options.table, PG_TEXT_CODEC_ID),\n cfExpr.identifierRef('policyname').eqParam(options.policyName, PG_TEXT_CODEC_ID),\n ]),\n );\n return {\n policyPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n policyAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nexport interface RlsEnabledCheckBuilder {\n rlsEnabled(): SelectAst;\n rlsDisabled(): SelectAst;\n}\n\n/**\n * Typed row-level-security enabled check over `pg_class` joined to\n * `pg_namespace`, comparing `pg_class.relrowsecurity` against the expected\n * boolean. Schema and table names are bound as text parameters.\n */\nexport function rlsEnabledAst(schema: string, table: string): RlsEnabledCheckBuilder {\n const inner = (enabled: boolean) =>\n exprSelect()\n .from(cfTable('pg_class', 'c'))\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('c', 'relnamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr.columnRef('n', 'nspname').eqParam(schema, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('c', 'relname').eqParam(table, PG_TEXT_CODEC_ID),\n enabled\n ? cfExpr.columnRef('c', 'relrowsecurity')\n : cfExpr.columnRef('c', 'relrowsecurity').not(),\n ]),\n );\n return {\n rlsEnabled: () =>\n exprSelect()\n .project('result', cfExpr.exists(inner(true)))\n .build(),\n rlsDisabled: () =>\n exprSelect()\n .project('result', cfExpr.exists(inner(false)))\n .build(),\n };\n}\n\nexport interface IndexExistsCheckBuilder {\n indexPresent(): SelectAst;\n indexAbsent(): SelectAst;\n}\n\n/**\n * Typed index existence check riding the same `to_regclass` vocabulary as\n * `tableExistsAst`, with the qualified index name bound as a text parameter.\n */\nexport function indexExistsAst(schema: string, indexName: string): IndexExistsCheckBuilder {\n const regclass = toRegclass(checkNamespace(schema).qualifyTable(indexName));\n return {\n indexPresent: () => exprSelect().project('result', regclass.isNotNull()).build(),\n indexAbsent: () => exprSelect().project('result', regclass.isNull()).build(),\n };\n}\n\nexport interface NativeEnumTypeExistsCheckBuilder {\n typePresent(): SelectAst;\n typeAbsent(): SelectAst;\n}\n\n/**\n * Typed native-enum type existence check over `pg_type` joined to\n * `pg_namespace`, restricted to enum types (`typtype = 'e'`). Schema and\n * type name are bound as text parameters; `schema` is a namespace\n * coordinate (the `__unbound__` sentinel compares against\n * `current_schema()`), matching {@link tableExistsAst} et al.\n */\nexport function nativeEnumTypeExistsAst(\n schema: string,\n typeName: string,\n): NativeEnumTypeExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_type', 't'))\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('t', 'typnamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr.columnRef('n', 'nspname').eqExpr(checkNamespace(schema).schemaFilterExpression()),\n cfExpr.columnRef('t', 'typname').eqParam(typeName, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('t', 'typtype').eqParam('e', PG_TEXT_CODEC_ID),\n ]),\n );\n return {\n typePresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n typeAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nexport interface NativeEnumValueExistsCheckBuilder {\n valuePresent(): SelectAst;\n valueAbsent(): SelectAst;\n}\n\n/**\n * Typed native-enum member-value existence check over `pg_enum` joined to\n * `pg_type` and `pg_namespace`. Schema, type name, and the candidate member\n * value are bound as text parameters — used by `addNativeEnumValue`'s\n * precheck (value absent) and postcheck (value present).\n */\nexport function nativeEnumValueExistsAst(options: {\n readonly schema: string;\n readonly typeName: string;\n readonly value: string;\n}): NativeEnumValueExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_enum', 'e'))\n .join(\n cfTable('pg_type', 't'),\n cfExpr.columnRef('t', 'oid').eqExpr(cfExpr.columnRef('e', 'enumtypid')),\n )\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('t', 'typnamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr\n .columnRef('n', 'nspname')\n .eqExpr(checkNamespace(options.schema).schemaFilterExpression()),\n cfExpr.columnRef('t', 'typname').eqParam(options.typeName, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('e', 'enumlabel').eqParam(options.value, PG_TEXT_CODEC_ID),\n ]),\n );\n return {\n valuePresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n valueAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n","import type { DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport {\n AddColumnAction,\n type AnyAlterTableAction,\n DropDefaultAction,\n PostgresAlterPolicyRename,\n PostgresAlterTable,\n PostgresCreatePolicy,\n PostgresCreateSchema,\n PostgresCreateTable,\n PostgresCreateType,\n PostgresDisableRowLevelSecurity,\n PostgresDropPolicy,\n PostgresDropType,\n type RlsPolicyOperation,\n} from '../core/ddl/nodes';\n\n/**\n * Build a Postgres `CREATE TABLE` query node.\n *\n * Pass `constraints` for table-level composite primary keys, foreign keys, and\n * unique constraints — use the {@link PrimaryKeyConstraint}, {@link ForeignKeyConstraint},\n * and {@link UniqueConstraint} classes from `@prisma-next/sql-relational-core/ast`.\n *\n * Precondition: identifiers (`table`, `schema`, column names/types) are\n * emitted to SQL verbatim — they are not quoted or escaped, so callers must\n * pass pre-trusted values (e.g. fixed control-plane identifiers). String-literal\n * default values, by contrast, are single-quote-escaped (embedded `'` doubled)\n * by the renderer. Identifier quoting for untrusted identifiers is added when\n * the migration planner adopts this lowering path.\n */\nexport function createTable(options: {\n readonly table: string;\n readonly schema?: string;\n readonly ifNotExists?: boolean;\n readonly columns: readonly DdlColumn[];\n readonly constraints?: readonly DdlTableConstraint[];\n}): PostgresCreateTable {\n return new PostgresCreateTable(options);\n}\n\n/**\n * Build a Postgres `CREATE SCHEMA` query node. See {@link createTable} for the\n * pre-trusted-identifier precondition.\n */\nexport function createSchema(options: {\n readonly schema: string;\n readonly ifNotExists?: boolean;\n}): PostgresCreateSchema {\n return new PostgresCreateSchema(options);\n}\n\n/**\n * Build a Postgres `CREATE TYPE … AS ENUM (…)` DDL node. The type name (and\n * optional schema) are quoted by the renderer; the enum member `values` are\n * emitted as single-quote-escaped string literals. An absent `schema` renders\n * the type name unqualified so the connection's `search_path` resolves it.\n */\nexport function createType(options: {\n readonly schema?: string;\n readonly name: string;\n readonly values: readonly string[];\n}): PostgresCreateType {\n return new PostgresCreateType(options);\n}\n\n/**\n * Build a Postgres `DROP TYPE` DDL node. See {@link createType} for the\n * identifier-quoting and unqualified-when-schemaless behaviour.\n */\nexport function dropType(options: {\n readonly schema?: string;\n readonly name: string;\n}): PostgresDropType {\n return new PostgresDropType(options);\n}\n\n/**\n * Build an `ADD COLUMN` action for use inside {@link alterTable}.\n * The column is a structured `DdlColumn` so codec-encoded defaults flow\n * through the adapter's `pgRenderDdlColumn` → `pgRenderDdlColumnDefault` path.\n */\nexport function addColumnAction(column: DdlColumn): AddColumnAction {\n return new AddColumnAction(column);\n}\n\n/**\n * Build a `DROP DEFAULT` action (`ALTER COLUMN \"<name>\" DROP DEFAULT`) for\n * use inside {@link alterTable}. The renderer quotes the column name.\n */\nexport function dropDefaultAction(columnName: string): DropDefaultAction {\n return new DropDefaultAction(columnName);\n}\n\n/**\n * Build a Postgres `ALTER TABLE` query node carrying one or more actions.\n * See {@link addColumnAction} / {@link dropDefaultAction} for building actions.\n */\nexport function alterTable(options: {\n readonly table: string;\n readonly schema?: string;\n readonly actions: readonly AnyAlterTableAction[];\n}): PostgresAlterTable {\n return new PostgresAlterTable(options);\n}\n\n/**\n * Build a Postgres `CREATE POLICY` DDL node.\n *\n * Identifiers (`schema`, `table`, `name`) are quoted by the renderer.\n * `using` and `withCheck` are emitted verbatim as predicate SQL — callers\n * must supply safe, pre-validated SQL expressions.\n */\nexport function createPolicy(options: {\n readonly schema: string;\n readonly table: string;\n readonly name: string;\n readonly permissive: boolean;\n readonly operation: RlsPolicyOperation;\n readonly roles: readonly string[];\n readonly using?: string;\n readonly withCheck?: string;\n}): PostgresCreatePolicy {\n return new PostgresCreatePolicy(options);\n}\n\n/**\n * Build a Postgres `DROP POLICY` DDL node.\n * Identifiers (`schema`, `table`, `name`) are quoted by the renderer.\n */\nexport function dropPolicy(options: {\n readonly schema: string;\n readonly table: string;\n readonly name: string;\n}): PostgresDropPolicy {\n return new PostgresDropPolicy(options);\n}\n\n/**\n * Build a Postgres `ALTER POLICY … RENAME TO` DDL node.\n * Identifiers (`schema`, `table`, `name`, `newName`) are quoted by the renderer.\n */\nexport function alterPolicyRename(options: {\n readonly schema: string;\n readonly table: string;\n readonly name: string;\n readonly newName: string;\n}): PostgresAlterPolicyRename {\n return new PostgresAlterPolicyRename(options);\n}\n\n/**\n * Build a Postgres `ALTER TABLE … DISABLE ROW LEVEL SECURITY` DDL node.\n * Identifiers (`schema`, `table`) are quoted by the renderer.\n */\nexport function disableRowLevelSecurity(options: {\n readonly schema: string;\n readonly table: string;\n}): PostgresDisableRowLevelSecurity {\n return new PostgresDisableRowLevelSecurity(options);\n}\n"],"mappings":";;;;;;;;;;AAiBA,SAAgB,WAAW,eAA+B;CACxD,OAAO,OAAO,GAAG;EACf,QAAQ;EACR,UAAU;EACV,MAAM,OAAO,MAAM,eAAe,gBAAgB;EAClD,SAAS;GAAE,SAAS;GAAkB,UAAU;EAAK;CACvD,CAAC;AACH;;;;;;;;;;AAgBA,SAAgB,eAAe,QAAgB,OAAwC;CAIrF,MAAM,WAAW,WAHC,wBAAwB;EAAE,IAAI;EAAQ,SAAS,EAAE,OAAO,CAAC,EAAE;CAAE,CAAC,CA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E,OAAO,IAAI,kBAAkB,UAAU;AACzC;;;;;AAMA,SAAgB,WAAW,SAIJ;CACrB,OAAO,IAAI,mBAAmB,OAAO;AACvC;;;;;;;;AASA,SAAgB,aAAa,SASJ;CACvB,OAAO,IAAI,qBAAqB,OAAO;AACzC;;;;;AAMA,SAAgB,WAAW,SAIJ;CACrB,OAAO,IAAI,mBAAmB,OAAO;AACvC;;;;;AAMA,SAAgB,kBAAkB,SAKJ;CAC5B,OAAO,IAAI,0BAA0B,OAAO;AAC9C;;;;;AAMA,SAAgB,wBAAwB,SAGJ;CAClC,OAAO,IAAI,gCAAgC,OAAO;AACpD"}
1
+ {"version":3,"file":"ddl-DYEob9xQ.mjs","names":[],"sources":["../src/contract-free/checks.ts","../src/contract-free/ddl.ts"],"sourcesContent":["import type { SelectAst } from '@prisma-next/sql-relational-core/ast';\nimport {\n type CfExpr,\n type CfExprSelectQuery,\n cfExpr,\n cfTable,\n exprSelect,\n} from '@prisma-next/sql-relational-core/contract-free';\nimport { PostgresTableSource } from '../core/ast/table-source';\nimport { PG_TEXT_CODEC_ID } from '../core/codec-ids';\nimport { postgresCreateNamespace } from '../core/postgres-schema';\n\n/**\n * `to_regclass($1)` with the qualified table name bound as a text parameter.\n * Thin vocabulary wrapper over the core `cfExpr.fn` helper — the target\n * supplies only the template and the codec'd operand.\n */\nexport function toRegclass(qualifiedName: string): CfExpr {\n return cfExpr.fn({\n method: 'to_regclass',\n template: 'to_regclass({{self}})',\n self: cfExpr.param(qualifiedName, PG_TEXT_CODEC_ID),\n returns: { codecId: PG_TEXT_CODEC_ID, nullable: true },\n });\n}\n\nexport interface TableExistsCheckBuilder {\n tableAbsent(): SelectAst;\n tablePresent(): SelectAst;\n}\n\n/**\n * Typed builder for the migration planner's table-existence checks. Produces\n * FROM-less `SELECT to_regclass($1) IS [NOT] NULL AS \"result\"` ASTs with the\n * qualified table name bound as a text parameter — never inlined into the SQL.\n *\n * `schema` is a namespace coordinate: the framework `__unbound__` sentinel\n * elides the qualifier (search_path decides at runtime); any other id\n * qualifies as `\"schema\".\"table\"`.\n */\nexport function tableExistsAst(schema: string, table: string): TableExistsCheckBuilder {\n const qualified = postgresCreateNamespace({ id: schema, entries: { table: {} } }).qualifyTable(\n table,\n );\n const regclass = toRegclass(qualified);\n return {\n tableAbsent: () => exprSelect().project('result', regclass.isNull()).build(),\n tablePresent: () => exprSelect().project('result', regclass.isNotNull()).build(),\n };\n}\n\nexport interface ConstraintExistsCheckBuilder {\n constraintPresent(): SelectAst;\n constraintAbsent(): SelectAst;\n}\n\n/**\n * Typed builder for the migration planner's constraint-existence checks.\n * Produces `SELECT [NOT ]EXISTS (SELECT 1 FROM pg_constraint c JOIN\n * pg_namespace n ON n.oid = c.connamespace WHERE c.conname = $1 AND\n * n.nspname = $2 [AND c.conrelid = to_regclass($3)]) AS \"result\"` with the\n * constraint name, schema name, and qualified table name bound as text\n * parameters.\n *\n * When `table` is omitted the check matches by name + schema across all\n * tables. Pass `table` to scope the check to a single table (prevents false\n * matches on identically-named constraints in different tables). `schema`\n * is a namespace coordinate: the `__unbound__` sentinel compares `nspname`\n * against `current_schema()` instead of a bound parameter.\n */\nexport function constraintExistsAst(options: {\n readonly constraintName: string;\n readonly schema: string;\n readonly table?: string;\n}): ConstraintExistsCheckBuilder {\n const namespace = postgresCreateNamespace({ id: options.schema, entries: { table: {} } });\n const conditions = [\n cfExpr.columnRef('c', 'conname').eqParam(options.constraintName, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('n', 'nspname').eqExpr(namespace.schemaFilterExpression()),\n ];\n if (options.table !== undefined) {\n conditions.push(\n cfExpr.columnRef('c', 'conrelid').eqExpr(toRegclass(namespace.qualifyTable(options.table))),\n );\n }\n const inner = (): CfExprSelectQuery =>\n exprSelect()\n .from(cfTable('pg_constraint', 'c'))\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('c', 'connamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(cfExpr.allOf(conditions));\n return {\n constraintPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n constraintAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nfunction checkNamespace(schema: string) {\n return postgresCreateNamespace({ id: schema, entries: { table: {} } });\n}\n\nfunction informationSchemaColumns(): PostgresTableSource {\n return new PostgresTableSource({ schema: 'information_schema', name: 'columns' });\n}\n\nfunction infoSchemaColumnConditions(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n}): CfExpr[] {\n return [\n cfExpr\n .identifierRef('table_schema')\n .eqExpr(checkNamespace(options.schema).schemaFilterExpression()),\n cfExpr.identifierRef('table_name').eqParam(options.table, PG_TEXT_CODEC_ID),\n cfExpr.identifierRef('column_name').eqParam(options.column, PG_TEXT_CODEC_ID),\n ];\n}\n\nfunction infoSchemaColumnQuery(conditions: ReadonlyArray<CfExpr>): CfExprSelectQuery {\n return exprSelect()\n .from(informationSchemaColumns())\n .project('one', cfExpr.lit(1))\n .where(cfExpr.allOf(conditions));\n}\n\nexport interface ColumnExistsCheckBuilder {\n columnPresent(): SelectAst;\n columnAbsent(): SelectAst;\n}\n\n/**\n * Typed builder for column-existence checks over\n * `information_schema.columns`, with schema, table, and column names bound\n * as text parameters.\n */\nexport function columnExistsAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n}): ColumnExistsCheckBuilder {\n const inner = () => infoSchemaColumnQuery(infoSchemaColumnConditions(options));\n return {\n columnPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n columnAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\n/**\n * Typed nullability check: EXISTS over `information_schema.columns` with\n * `is_nullable` compared against the bound `'YES'` / `'NO'` marker.\n */\nexport function columnNullabilityAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly nullable: boolean;\n}): SelectAst {\n const conditions = [\n ...infoSchemaColumnConditions(options),\n cfExpr.identifierRef('is_nullable').eqParam(options.nullable ? 'YES' : 'NO', PG_TEXT_CODEC_ID),\n ];\n return exprSelect()\n .project('result', cfExpr.exists(infoSchemaColumnQuery(conditions)))\n .build();\n}\n\nexport interface ColumnDefaultCheckBuilder {\n defaultPresent(): SelectAst;\n defaultAbsent(): SelectAst;\n noDefault(): SelectAst;\n}\n\n/**\n * Typed default-presence checks over `information_schema.columns`.\n * `defaultPresent` / `defaultAbsent` assert the column row exists with a\n * non-null / null `column_default`; `noDefault` is the NOT EXISTS variant\n * (also true when the column row is missing entirely).\n */\nexport function columnDefaultAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n}): ColumnDefaultCheckBuilder {\n const withDefault = () =>\n infoSchemaColumnQuery([\n ...infoSchemaColumnConditions(options),\n cfExpr.identifierRef('column_default').isNotNull(),\n ]);\n const withoutDefault = () =>\n infoSchemaColumnQuery([\n ...infoSchemaColumnConditions(options),\n cfExpr.identifierRef('column_default').isNull(),\n ]);\n return {\n defaultPresent: () => exprSelect().project('result', cfExpr.exists(withDefault())).build(),\n defaultAbsent: () => exprSelect().project('result', cfExpr.exists(withoutDefault())).build(),\n noDefault: () => exprSelect().project('result', cfExpr.notExists(withDefault())).build(),\n };\n}\n\n/**\n * Typed column-type check: EXISTS over `pg_attribute` joined to `pg_class`\n * and `pg_namespace`, comparing `format_type(a.atttypid, a.atttypmod)`\n * against the bound expected display type and excluding dropped columns.\n */\nexport function columnTypeAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly expectedType: string;\n}): SelectAst {\n const formatType = cfExpr.fn({\n method: 'format_type',\n template: 'format_type({{self}}, {{arg0}})',\n self: cfExpr.columnRef('a', 'atttypid'),\n args: [cfExpr.columnRef('a', 'atttypmod')],\n returns: { codecId: PG_TEXT_CODEC_ID, nullable: false },\n });\n const inner = exprSelect()\n .from(cfTable('pg_attribute', 'a'))\n .join(\n cfTable('pg_class', 'c'),\n cfExpr.columnRef('c', 'oid').eqExpr(cfExpr.columnRef('a', 'attrelid')),\n )\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('c', 'relnamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr\n .columnRef('n', 'nspname')\n .eqExpr(checkNamespace(options.schema).schemaFilterExpression()),\n cfExpr.columnRef('c', 'relname').eqParam(options.table, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('a', 'attname').eqParam(options.column, PG_TEXT_CODEC_ID),\n formatType.eqParam(options.expectedType, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('a', 'attisdropped').not(),\n ]),\n );\n return exprSelect().project('result', cfExpr.exists(inner)).build();\n}\n\nexport interface TablePrimaryKeyCheckBuilder {\n pkPresent(): SelectAst;\n pkAbsent(): SelectAst;\n}\n\n/**\n * Typed primary-key existence check over `pg_index` joined to `pg_class`\n * and `pg_namespace`, with a LEFT JOIN on the index relation so an\n * optional `constraintName` can scope the match to a named constraint.\n */\nexport function tablePrimaryKeyAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraintName?: string;\n}): TablePrimaryKeyCheckBuilder {\n const conditions = [\n cfExpr\n .columnRef('n', 'nspname')\n .eqExpr(checkNamespace(options.schema).schemaFilterExpression()),\n cfExpr.columnRef('c', 'relname').eqParam(options.table, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('i', 'indisprimary'),\n ];\n if (options.constraintName !== undefined) {\n conditions.push(\n cfExpr.columnRef('c2', 'relname').eqParam(options.constraintName, PG_TEXT_CODEC_ID),\n );\n }\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_index', 'i'))\n .join(\n cfTable('pg_class', 'c'),\n cfExpr.columnRef('c', 'oid').eqExpr(cfExpr.columnRef('i', 'indrelid')),\n )\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('c', 'relnamespace')),\n )\n .leftJoin(\n cfTable('pg_class', 'c2'),\n cfExpr.columnRef('c2', 'oid').eqExpr(cfExpr.columnRef('i', 'indexrelid')),\n )\n .project('one', cfExpr.lit(1))\n .where(cfExpr.allOf(conditions));\n return {\n pkPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n pkAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\n/**\n * Typed emptiness check: NOT EXISTS over the user table itself with\n * `LIMIT 1`. The table is addressed through the namespace's polymorphic\n * `tableSource` (qualified for named schemas, bare for the unbound slot).\n */\nexport function tableIsEmptyAst(schema: string, table: string): SelectAst {\n const inner = exprSelect()\n .from(checkNamespace(schema).tableSource(table))\n .project('one', cfExpr.lit(1))\n .limit(1);\n return exprSelect().project('result', cfExpr.notExists(inner)).build();\n}\n\n/**\n * Typed no-NULL-values data check used by `SET NOT NULL` prechecks:\n * NOT EXISTS over the user table where the column IS NULL.\n */\nexport function noNullValuesAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n}): SelectAst {\n const inner = exprSelect()\n .from(checkNamespace(options.schema).tableSource(options.table))\n .project('one', cfExpr.lit(1))\n .where(cfExpr.identifierRef(options.column).isNull());\n return exprSelect().project('result', cfExpr.notExists(inner)).build();\n}\n\nexport interface ExtensionExistsCheckBuilder {\n extensionPresent(): SelectAst;\n extensionAbsent(): SelectAst;\n}\n\n/**\n * Typed extension existence check over `pg_extension`, with the extension\n * name bound as a text parameter.\n */\nexport function extensionExistsAst(extensionName: string): ExtensionExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_extension'))\n .project('one', cfExpr.lit(1))\n .where(cfExpr.identifierRef('extname').eqParam(extensionName, PG_TEXT_CODEC_ID));\n return {\n extensionPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n extensionAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nexport interface RlsPolicyExistsCheckBuilder {\n policyPresent(): SelectAst;\n policyAbsent(): SelectAst;\n}\n\n/**\n * Typed RLS-policy existence check over `pg_policies`, with schema, table,\n * and policy names bound as text parameters (never inlined). The `schema`\n * coordinate is the resolved live-database schema name (e.g. `'public'`),\n * compared against `pg_policies.schemaname` as a bound parameter.\n */\nexport function rlsPolicyExistsAst(options: {\n readonly schema: string;\n readonly table: string;\n readonly policyName: string;\n}): RlsPolicyExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_policies'))\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr.identifierRef('schemaname').eqParam(options.schema, PG_TEXT_CODEC_ID),\n cfExpr.identifierRef('tablename').eqParam(options.table, PG_TEXT_CODEC_ID),\n cfExpr.identifierRef('policyname').eqParam(options.policyName, PG_TEXT_CODEC_ID),\n ]),\n );\n return {\n policyPresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n policyAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nexport interface RlsEnabledCheckBuilder {\n rlsEnabled(): SelectAst;\n rlsDisabled(): SelectAst;\n}\n\n/**\n * Typed row-level-security enabled check over `pg_class` joined to\n * `pg_namespace`, comparing `pg_class.relrowsecurity` against the expected\n * boolean. Schema and table names are bound as text parameters.\n */\nexport function rlsEnabledAst(schema: string, table: string): RlsEnabledCheckBuilder {\n const inner = (enabled: boolean) =>\n exprSelect()\n .from(cfTable('pg_class', 'c'))\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('c', 'relnamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr.columnRef('n', 'nspname').eqParam(schema, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('c', 'relname').eqParam(table, PG_TEXT_CODEC_ID),\n enabled\n ? cfExpr.columnRef('c', 'relrowsecurity')\n : cfExpr.columnRef('c', 'relrowsecurity').not(),\n ]),\n );\n return {\n rlsEnabled: () =>\n exprSelect()\n .project('result', cfExpr.exists(inner(true)))\n .build(),\n rlsDisabled: () =>\n exprSelect()\n .project('result', cfExpr.exists(inner(false)))\n .build(),\n };\n}\n\nexport interface IndexExistsCheckBuilder {\n indexPresent(): SelectAst;\n indexAbsent(): SelectAst;\n}\n\n/**\n * Typed index existence check riding the same `to_regclass` vocabulary as\n * `tableExistsAst`, with the qualified index name bound as a text parameter.\n */\nexport function indexExistsAst(schema: string, indexName: string): IndexExistsCheckBuilder {\n const regclass = toRegclass(checkNamespace(schema).qualifyTable(indexName));\n return {\n indexPresent: () => exprSelect().project('result', regclass.isNotNull()).build(),\n indexAbsent: () => exprSelect().project('result', regclass.isNull()).build(),\n };\n}\n\nexport interface NativeEnumTypeExistsCheckBuilder {\n typePresent(): SelectAst;\n typeAbsent(): SelectAst;\n}\n\n/**\n * Typed native-enum type existence check over `pg_type` joined to\n * `pg_namespace`, restricted to enum types (`typtype = 'e'`). Schema and\n * type name are bound as text parameters; `schema` is a namespace\n * coordinate (the `__unbound__` sentinel compares against\n * `current_schema()`), matching {@link tableExistsAst} et al.\n */\nexport function nativeEnumTypeExistsAst(\n schema: string,\n typeName: string,\n): NativeEnumTypeExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_type', 't'))\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('t', 'typnamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr.columnRef('n', 'nspname').eqExpr(checkNamespace(schema).schemaFilterExpression()),\n cfExpr.columnRef('t', 'typname').eqParam(typeName, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('t', 'typtype').eqParam('e', PG_TEXT_CODEC_ID),\n ]),\n );\n return {\n typePresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n typeAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n\nexport interface NativeEnumValueExistsCheckBuilder {\n valuePresent(): SelectAst;\n valueAbsent(): SelectAst;\n}\n\n/**\n * Typed native-enum member-value existence check over `pg_enum` joined to\n * `pg_type` and `pg_namespace`. Schema, type name, and the candidate member\n * value are bound as text parameters — used by `addNativeEnumValue`'s\n * precheck (value absent) and postcheck (value present).\n */\nexport function nativeEnumValueExistsAst(options: {\n readonly schema: string;\n readonly typeName: string;\n readonly value: string;\n}): NativeEnumValueExistsCheckBuilder {\n const inner = () =>\n exprSelect()\n .from(cfTable('pg_enum', 'e'))\n .join(\n cfTable('pg_type', 't'),\n cfExpr.columnRef('t', 'oid').eqExpr(cfExpr.columnRef('e', 'enumtypid')),\n )\n .join(\n cfTable('pg_namespace', 'n'),\n cfExpr.columnRef('n', 'oid').eqExpr(cfExpr.columnRef('t', 'typnamespace')),\n )\n .project('one', cfExpr.lit(1))\n .where(\n cfExpr.allOf([\n cfExpr\n .columnRef('n', 'nspname')\n .eqExpr(checkNamespace(options.schema).schemaFilterExpression()),\n cfExpr.columnRef('t', 'typname').eqParam(options.typeName, PG_TEXT_CODEC_ID),\n cfExpr.columnRef('e', 'enumlabel').eqParam(options.value, PG_TEXT_CODEC_ID),\n ]),\n );\n return {\n valuePresent: () => exprSelect().project('result', cfExpr.exists(inner())).build(),\n valueAbsent: () => exprSelect().project('result', cfExpr.notExists(inner())).build(),\n };\n}\n","import type { DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport {\n AddColumnAction,\n type AnyAlterTableAction,\n DropDefaultAction,\n PostgresAlterPolicyRename,\n PostgresAlterTable,\n PostgresCreatePolicy,\n PostgresCreateSchema,\n PostgresCreateTable,\n PostgresCreateType,\n PostgresDisableRowLevelSecurity,\n PostgresDropPolicy,\n PostgresDropType,\n type RlsPolicyOperation,\n} from '../core/ddl/nodes';\n\n/**\n * Build a Postgres `CREATE TABLE` query node.\n *\n * Pass `constraints` for table-level composite primary keys, foreign keys, and\n * unique constraints — use the {@link PrimaryKeyConstraint}, {@link ForeignKeyConstraint},\n * and {@link UniqueConstraint} classes from `@prisma-next/sql-relational-core/ast`.\n *\n * Precondition: identifiers (`table`, `schema`, column names/types) are\n * emitted to SQL verbatim — they are not quoted or escaped, so callers must\n * pass pre-trusted values (e.g. fixed control-plane identifiers). String-literal\n * default values, by contrast, are single-quote-escaped (embedded `'` doubled)\n * by the renderer. Identifier quoting for untrusted identifiers is added when\n * the migration planner adopts this lowering path.\n */\nexport function createTable(options: {\n readonly table: string;\n readonly schema?: string;\n readonly ifNotExists?: boolean;\n readonly columns: readonly DdlColumn[];\n readonly constraints?: readonly DdlTableConstraint[];\n}): PostgresCreateTable {\n return new PostgresCreateTable(options);\n}\n\n/**\n * Build a Postgres `CREATE SCHEMA` query node. See {@link createTable} for the\n * pre-trusted-identifier precondition.\n */\nexport function createSchema(options: {\n readonly schema: string;\n readonly ifNotExists?: boolean;\n}): PostgresCreateSchema {\n return new PostgresCreateSchema(options);\n}\n\n/**\n * Build a Postgres `CREATE TYPE … AS ENUM (…)` DDL node. The type name (and\n * optional schema) are quoted by the renderer; the enum member `values` are\n * emitted as single-quote-escaped string literals. An absent `schema` renders\n * the type name unqualified so the connection's `search_path` resolves it.\n */\nexport function createType(options: {\n readonly schema?: string;\n readonly name: string;\n readonly values: readonly string[];\n}): PostgresCreateType {\n return new PostgresCreateType(options);\n}\n\n/**\n * Build a Postgres `DROP TYPE` DDL node. See {@link createType} for the\n * identifier-quoting and unqualified-when-schemaless behaviour.\n */\nexport function dropType(options: {\n readonly schema?: string;\n readonly name: string;\n}): PostgresDropType {\n return new PostgresDropType(options);\n}\n\n/**\n * Build an `ADD COLUMN` action for use inside {@link alterTable}.\n * The column is a structured `DdlColumn` so codec-encoded defaults flow\n * through the adapter's `pgRenderDdlColumn` → `pgRenderDdlColumnDefault` path.\n */\nexport function addColumnAction(column: DdlColumn): AddColumnAction {\n return new AddColumnAction(column);\n}\n\n/**\n * Build a `DROP DEFAULT` action (`ALTER COLUMN \"<name>\" DROP DEFAULT`) for\n * use inside {@link alterTable}. The renderer quotes the column name.\n */\nexport function dropDefaultAction(columnName: string): DropDefaultAction {\n return new DropDefaultAction(columnName);\n}\n\n/**\n * Build a Postgres `ALTER TABLE` query node carrying one or more actions.\n * See {@link addColumnAction} / {@link dropDefaultAction} for building actions.\n */\nexport function alterTable(options: {\n readonly table: string;\n readonly schema?: string;\n readonly actions: readonly AnyAlterTableAction[];\n}): PostgresAlterTable {\n return new PostgresAlterTable(options);\n}\n\n/**\n * Build a Postgres `CREATE POLICY` DDL node.\n *\n * Identifiers (`schema`, `table`, `name`) are quoted by the renderer.\n * `using` and `withCheck` are emitted verbatim as predicate SQL — callers\n * must supply safe, pre-validated SQL expressions.\n */\nexport function createPolicy(options: {\n readonly schema: string;\n readonly table: string;\n readonly name: string;\n readonly permissive: boolean;\n readonly operation: RlsPolicyOperation;\n readonly roles: readonly string[];\n readonly using?: string;\n readonly withCheck?: string;\n}): PostgresCreatePolicy {\n return new PostgresCreatePolicy(options);\n}\n\n/**\n * Build a Postgres `DROP POLICY` DDL node.\n * Identifiers (`schema`, `table`, `name`) are quoted by the renderer.\n */\nexport function dropPolicy(options: {\n readonly schema: string;\n readonly table: string;\n readonly name: string;\n}): PostgresDropPolicy {\n return new PostgresDropPolicy(options);\n}\n\n/**\n * Build a Postgres `ALTER POLICY … RENAME TO` DDL node.\n * Identifiers (`schema`, `table`, `name`, `newName`) are quoted by the renderer.\n */\nexport function alterPolicyRename(options: {\n readonly schema: string;\n readonly table: string;\n readonly name: string;\n readonly newName: string;\n}): PostgresAlterPolicyRename {\n return new PostgresAlterPolicyRename(options);\n}\n\n/**\n * Build a Postgres `ALTER TABLE … DISABLE ROW LEVEL SECURITY` DDL node.\n * Identifiers (`schema`, `table`) are quoted by the renderer.\n */\nexport function disableRowLevelSecurity(options: {\n readonly schema: string;\n readonly table: string;\n}): PostgresDisableRowLevelSecurity {\n return new PostgresDisableRowLevelSecurity(options);\n}\n"],"mappings":";;;;;;;;;;AAiBA,SAAgB,WAAW,eAA+B;CACxD,OAAO,OAAO,GAAG;EACf,QAAQ;EACR,UAAU;EACV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AgB,WAAW,SAIJ;CACrB,OAAO,IAAI,mBAAmB,OAAO;AACvC;;;;;AAMA,SAAgB,SAAS,SAGJ;CACnB,OAAO,IAAI,iBAAiB,OAAO;AACrC;;;;;;AAOA,SAAgB,gBAAgB,QAAoC;CAClE,OAAO,IAAI,gBAAgB,MAAM;AACnC;;;;;AAMA,SAAgB,kBAAkB,YAAuC;CACvE,OAAO,IAAI,kBAAkB,UAAU;AACzC;;;;;AAMA,SAAgB,WAAW,SAIJ;CACrB,OAAO,IAAI,mBAAmB,OAAO;AACvC;;;;;;;;AASA,SAAgB,aAAa,SASJ;CACvB,OAAO,IAAI,qBAAqB,OAAO;AACzC;;;;;AAMA,SAAgB,WAAW,SAIJ;CACrB,OAAO,IAAI,mBAAmB,OAAO;AACvC;;;;;AAMA,SAAgB,kBAAkB,SAKJ;CAC5B,OAAO,IAAI,0BAA0B,OAAO;AAC9C;;;;;AAMA,SAAgB,wBAAwB,SAGJ;CAClC,OAAO,IAAI,gCAAgC,OAAO;AACpD"}
@@ -1,7 +1,7 @@
1
- import { O as postgresQualifyColumnType } from "./codecs-DOgD_C1A.mjs";
1
+ import { O as postgresQualifyColumnType } from "./codecs-Deand7sy.mjs";
2
2
  import { t as DEFAULT_NAMESPACE_ID } from "./namespace-ids-xtp_ZY86.mjs";
3
- import { i as postgresCreateNamespace } from "./postgres-schema-CewLYHB7.mjs";
4
- import { a as postgresAuthoringTypes, i as postgresAuthoringPslBlockDescriptors, n as postgresAuthoringFieldPresets, o as postgresLowerEntityHandles, r as postgresAuthoringModelAttributes, t as postgresAuthoringEntityTypes } from "./authoring-34L18kA1.mjs";
3
+ import { i as postgresCreateNamespace } from "./postgres-schema-CTplQZDK.mjs";
4
+ import { a as postgresAuthoringTypes, i as postgresAuthoringPslBlockDescriptors, n as postgresAuthoringFieldPresets, o as postgresLowerEntityHandles, r as postgresAuthoringModelAttributes, t as postgresAuthoringEntityTypes } from "./authoring-BCzcFRay.mjs";
5
5
  import { t as postgresTargetDescriptorMetaRuntime } from "./descriptor-meta-runtime-UwYdV8fD.mjs";
6
6
  import { type } from "arktype";
7
7
  import { defineIndexTypes } from "@prisma-next/sql-contract/index-types";
@@ -25,4 +25,4 @@ const postgresTargetDescriptorMeta = {
25
25
  //#endregion
26
26
  export { postgresTargetDescriptorMeta as t };
27
27
 
28
- //# sourceMappingURL=descriptor-meta-CiYV9DzH.mjs.map
28
+ //# sourceMappingURL=descriptor-meta-D_0ZKcj-.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"descriptor-meta-CiYV9DzH.mjs","names":[],"sources":["../src/core/index-types.ts","../src/core/descriptor-meta.ts"],"sourcesContent":["import { defineIndexTypes } from '@prisma-next/sql-contract/index-types';\nimport { type } from 'arktype';\n\n// Postgres's built-in index access methods (`CREATE INDEX ... USING <method>`).\n// Per-method option validation (e.g. `gin` operator classes) is out of scope;\n// every method accepts any options object until a later slice narrows it.\nexport const postgresIndexTypes = defineIndexTypes()\n .add('btree', { options: type('object') })\n .add('hash', { options: type('object') })\n .add('gin', { options: type('object') })\n .add('gist', { options: type('object') })\n .add('spgist', { options: type('object') })\n .add('brin', { options: type('object') });\n\nexport type IndexTypes = typeof postgresIndexTypes.IndexTypes;\n","import type { CodecTypes } from '../exports/codec-types';\nimport {\n postgresAuthoringEntityTypes,\n postgresAuthoringFieldPresets,\n postgresAuthoringModelAttributes,\n postgresAuthoringPslBlockDescriptors,\n postgresAuthoringTypes,\n postgresLowerEntityHandles,\n} from './authoring';\nimport { postgresQualifyColumnType } from './codecs';\nimport { postgresTargetDescriptorMetaRuntime } from './descriptor-meta-runtime';\nimport { postgresIndexTypes } from './index-types';\nimport { DEFAULT_NAMESPACE_ID } from './namespace-ids';\nimport { postgresCreateNamespace } from './postgres-schema';\n\nconst postgresTargetDescriptorMetaBase = {\n ...postgresTargetDescriptorMetaRuntime,\n defaultNamespaceId: DEFAULT_NAMESPACE_ID,\n indexTypes: postgresIndexTypes,\n authoring: {\n type: postgresAuthoringTypes,\n field: postgresAuthoringFieldPresets,\n entityTypes: postgresAuthoringEntityTypes,\n pslBlockDescriptors: postgresAuthoringPslBlockDescriptors,\n modelAttributes: postgresAuthoringModelAttributes,\n createNamespace: postgresCreateNamespace,\n qualifyColumnType: postgresQualifyColumnType,\n lowerEntityHandles: postgresLowerEntityHandles,\n },\n} as const;\n\nexport const postgresTargetDescriptorMeta: typeof postgresTargetDescriptorMetaBase & {\n readonly __codecTypes?: CodecTypes;\n} = postgresTargetDescriptorMetaBase;\n"],"mappings":";;;;;;;;AAMA,MAAa,qBAAqB,iBAAiB,CAAC,CACjD,IAAI,SAAS,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC,CAAC,CACzC,IAAI,QAAQ,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC,CAAC,CACxC,IAAI,OAAO,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC,CAAC,CACvC,IAAI,QAAQ,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC,CAAC,CACxC,IAAI,UAAU,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC,CAAC,CAC1C,IAAI,QAAQ,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC;ACmB1C,MAAa,+BAET;CAjBF,GAAG;CACH,oBAAoB;CACpB,YAAY;CACZ,WAAW;EACT,MAAM;EACN,OAAO;EACP,aAAa;EACb,qBAAqB;EACrB,iBAAiB;EACjB,iBAAiB;EACjB,mBAAmB;EACnB,oBAAoB;CACtB;AAKE"}
1
+ {"version":3,"file":"descriptor-meta-D_0ZKcj-.mjs","names":[],"sources":["../src/core/index-types.ts","../src/core/descriptor-meta.ts"],"sourcesContent":["import { defineIndexTypes } from '@prisma-next/sql-contract/index-types';\nimport { type } from 'arktype';\n\n// Postgres's built-in index access methods (`CREATE INDEX ... USING <method>`).\n// Per-method option validation (e.g. `gin` operator classes) is out of scope;\n// every method accepts any options object until a later slice narrows it.\nexport const postgresIndexTypes = defineIndexTypes()\n .add('btree', { options: type('object') })\n .add('hash', { options: type('object') })\n .add('gin', { options: type('object') })\n .add('gist', { options: type('object') })\n .add('spgist', { options: type('object') })\n .add('brin', { options: type('object') });\n\nexport type IndexTypes = typeof postgresIndexTypes.IndexTypes;\n","import type { CodecTypes } from '../exports/codec-types';\nimport {\n postgresAuthoringEntityTypes,\n postgresAuthoringFieldPresets,\n postgresAuthoringModelAttributes,\n postgresAuthoringPslBlockDescriptors,\n postgresAuthoringTypes,\n postgresLowerEntityHandles,\n} from './authoring';\nimport { postgresQualifyColumnType } from './codecs';\nimport { postgresTargetDescriptorMetaRuntime } from './descriptor-meta-runtime';\nimport { postgresIndexTypes } from './index-types';\nimport { DEFAULT_NAMESPACE_ID } from './namespace-ids';\nimport { postgresCreateNamespace } from './postgres-schema';\n\nconst postgresTargetDescriptorMetaBase = {\n ...postgresTargetDescriptorMetaRuntime,\n defaultNamespaceId: DEFAULT_NAMESPACE_ID,\n indexTypes: postgresIndexTypes,\n authoring: {\n type: postgresAuthoringTypes,\n field: postgresAuthoringFieldPresets,\n entityTypes: postgresAuthoringEntityTypes,\n pslBlockDescriptors: postgresAuthoringPslBlockDescriptors,\n modelAttributes: postgresAuthoringModelAttributes,\n createNamespace: postgresCreateNamespace,\n qualifyColumnType: postgresQualifyColumnType,\n lowerEntityHandles: postgresLowerEntityHandles,\n },\n} as const;\n\nexport const postgresTargetDescriptorMeta: typeof postgresTargetDescriptorMetaBase & {\n readonly __codecTypes?: CodecTypes;\n} = postgresTargetDescriptorMetaBase;\n"],"mappings":";;;;;;;;AAMA,MAAa,qBAAqB,iBAAiB,CAAC,CACjD,IAAI,SAAS,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC,CAAC,CACzC,IAAI,QAAQ,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC,CAAC,CACxC,IAAI,OAAO,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC,CAAC,CACvC,IAAI,QAAQ,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC,CAAC,CACxC,IAAI,UAAU,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC,CAAC,CAC1C,IAAI,QAAQ,EAAE,SAAS,KAAK,QAAQ,EAAE,CAAC;ACmB1C,MAAa,+BAET;CAjBF,GAAG;CACH,oBAAoB;CACpB,YAAY;CACZ,WAAW;EACT,MAAM;EACN,OAAO;EACP,aAAa;EACb,qBAAqB;EACrB,iBAAiB;EACjB,iBAAiB;EACjB,mBAAmB;EACnB,oBAAoB;CACtB;AAKE"}
@@ -1,9 +1,10 @@
1
+ import { n as postgresError } from "./errors-DBSNx7EJ.mjs";
1
2
  import { n as postgresResolveDefault } from "./default-normalizer-B9ZUiyUE.mjs";
2
- import { r as isPostgresSchema } from "./postgres-schema-CewLYHB7.mjs";
3
+ import { r as isPostgresSchema } from "./postgres-schema-CTplQZDK.mjs";
3
4
  import { a as postgresDiffSubjectGranularity, n as PostgresNativeEnumSchemaNode, r as PostgresSchemaNodeKind, t as PostgresTableSchemaNode } from "./postgres-table-schema-node-D6LvInCe.mjs";
4
5
  import { i as PostgresDatabaseSchemaNode, n as PostgresPolicySchemaNode, r as PostgresNamespaceSchemaNode, t as PostgresRoleSchemaNode } from "./postgres-role-schema-node-bg32e7I-.mjs";
5
- import { t as resolveDdlSchemaForNamespaceStorage } from "./resolve-ddl-schema-D0wi_P9Q.mjs";
6
- import { i as resolvePostgresNodeIssueControlPolicySubject } from "./control-policy-BrcqeM82.mjs";
6
+ import { t as resolveDdlSchemaForNamespaceStorage } from "./resolve-ddl-schema-BAsJEKW8.mjs";
7
+ import { i as resolvePostgresNodeIssueControlPolicySubject } from "./control-policy-B-_34g05.mjs";
7
8
  import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
8
9
  import { blindCast } from "@prisma-next/utils/casts";
9
10
  import { buildNativeTypeExpander, contractNamespaceToSchemaIR } from "@prisma-next/family-sql/control";
@@ -168,11 +169,21 @@ function contractToPostgresDatabaseSchemaNode(contract, options) {
168
169
  for (const [tableName, tablePolicies] of policiesByTable) {
169
170
  if (!(tableName in tables)) {
170
171
  const policyName = tablePolicies[0]?.name ?? "(unknown)";
171
- throw new Error(`contract-to-postgres-database-schema-node: policy "${policyName}" references table "${tableName}" not present in namespace "${ddlSchema}"`);
172
+ throw postgresError("CONTRACT.POLICY_INVALID", `contract-to-postgres-database-schema-node: policy "${policyName}" references table "${tableName}" not present in namespace "${ddlSchema}"`, { meta: {
173
+ policyName,
174
+ tableName,
175
+ namespaceId: ddlSchema,
176
+ reason: "table-missing"
177
+ } });
172
178
  }
173
179
  if (!Object.hasOwn(ns.rls, tableName)) {
174
180
  const policyPrefix = tablePolicies[0]?.prefix ?? "(unknown)";
175
- throw new Error(`contract-to-postgres-database-schema-node: policy "${policyPrefix}" targets table "${tableName}" in namespace "${ddlSchema}", which is not RLS-controlled. Mark the model with @@rls (entries.rls["${tableName}"]) or remove the policy.`);
181
+ throw postgresError("CONTRACT.POLICY_INVALID", `contract-to-postgres-database-schema-node: policy "${policyPrefix}" targets table "${tableName}" in namespace "${ddlSchema}", which is not RLS-controlled. Mark the model with @@rls (entries.rls["${tableName}"]) or remove the policy.`, { meta: {
182
+ policyName: policyPrefix,
183
+ tableName,
184
+ namespaceId: ddlSchema,
185
+ reason: "table-not-rls-controlled"
186
+ } });
176
187
  }
177
188
  }
178
189
  namespaces[ddlSchema] = new PostgresNamespaceSchemaNode({
@@ -369,4 +380,4 @@ function buildPostgresPlanDiff(input) {
369
380
  //#endregion
370
381
  export { diffPostgresSchema as n, contractToPostgresDatabaseSchemaNode as r, buildPostgresPlanDiff as t };
371
382
 
372
- //# sourceMappingURL=diff-database-schema-CK0FM2Z-.mjs.map
383
+ //# sourceMappingURL=diff-database-schema-C9H09OD3.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diff-database-schema-C9H09OD3.mjs","names":[],"sources":["../src/core/migrations/contract-to-postgres-database-schema-node.ts","../src/core/migrations/diff-database-schema.ts"],"sourcesContent":["import type { ContractToSchemaIROptions } from '@prisma-next/family-sql/control';\nimport { contractNamespaceToSchemaIR } from '@prisma-next/family-sql/control';\nimport type { SchemaNodeRef } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport {\n PrimaryKey,\n RelationalSchemaNodeKind,\n SqlForeignKeyIR,\n SqlIndexIR,\n SqlUniqueIR,\n} from '@prisma-next/sql-schema-ir/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresError } from '../errors';\nimport type { PostgresRlsPolicy } from '../postgres-rls-policy';\nimport type { PostgresContract } from '../postgres-schema';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport { PostgresNativeEnumSchemaNode } from '../schema-ir/postgres-native-enum-schema-node';\nimport { PostgresPolicySchemaNode } from '../schema-ir/postgres-policy-schema-node';\nimport { PostgresRoleSchemaNode } from '../schema-ir/postgres-role-schema-node';\nimport { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';\nimport { PostgresSchemaNodeKind } from '../schema-ir/schema-node-kinds';\nimport { resolveDdlSchemaForNamespaceStorage } from './resolve-ddl-schema';\n\n/** The database root's fixed sentinel id (`PostgresDatabaseSchemaNode#id`). */\nfunction databaseStep(): { readonly nodeKind: string; readonly id: string } {\n return { nodeKind: PostgresSchemaNodeKind.database, id: 'database' };\n}\n\nfunction tableDependsOn(namespaceId: string, tableName: string): SchemaNodeRef {\n return [\n databaseStep(),\n { nodeKind: PostgresSchemaNodeKind.namespace, id: namespaceId },\n { nodeKind: PostgresSchemaNodeKind.table, id: tableName },\n ];\n}\n\nfunction roleDependsOn(role: string): SchemaNodeRef {\n return [databaseStep(), { nodeKind: PostgresSchemaNodeKind.role, id: role }];\n}\n\n/**\n * The chains from a table-child object (foreign key, index, unique, primary\n * key) to each of the own columns it is built on, in the Postgres tree.\n * Dropping a covered column auto-drops the object, so the object's drop must\n * precede the column's; the graph derives that direction from these edges.\n */\nfunction columnDependsOn(\n namespaceId: string,\n tableName: string,\n columns: readonly string[],\n): readonly SchemaNodeRef[] {\n return columns.map((column) => [\n ...tableDependsOn(namespaceId, tableName),\n { nodeKind: RelationalSchemaNodeKind.column, id: `column:${column}` },\n ]);\n}\n\nfunction toPolicyNode(policy: PostgresRlsPolicy, namespaceId: string): PostgresPolicySchemaNode {\n return new PostgresPolicySchemaNode({\n name: policy.name,\n prefix: policy.prefix,\n tableName: policy.tableName,\n namespaceId,\n operation: policy.operation,\n roles: [...policy.roles],\n ...ifDefined('using', policy.using),\n ...ifDefined('withCheck', policy.withCheck),\n permissive: policy.permissive,\n dependsOn: [tableDependsOn(namespaceId, policy.tableName), ...policy.roles.map(roleDependsOn)],\n });\n}\n\n/**\n * Projects a Postgres contract into the expected schema-diff tree: a\n * `PostgresDatabaseSchemaNode` root holding one `PostgresNamespaceSchemaNode`\n * per Postgres namespace, each holding its `PostgresTableSchemaNode`s with\n * their `PostgresPolicySchemaNode`s, plus the database roles on the root.\n *\n * Not a duplicate of the family's `contractToSchemaIR`: that builds a flat,\n * single `{ tables }` map (and throws on cross-namespace name collisions, with\n * no RLS/role concept) for SQLite's single-schema world. This is the\n * Postgres-specific *tree* shape — multi-schema, RLS-policy-aware, role-aware.\n * It reuses the family's per-namespace table conversion (`contractNamespaceToSchemaIR`)\n * for column/FK/index building and only adds the Postgres tree/policy/role shape.\n *\n * Tables are grouped by their owning namespace (resolved DDL schema name) so\n * the tree mirrors Postgres's object hierarchy. The DDL schema name is\n * resolved once per namespace.\n *\n * A policy that references a table absent from its namespace is a malformed\n * contract — the loop throws rather than fabricating a stub table.\n */\nexport function contractToPostgresDatabaseSchemaNode(\n contract: PostgresContract | null,\n options: ContractToSchemaIROptions,\n): PostgresDatabaseSchemaNode {\n if (contract === null) {\n return new PostgresDatabaseSchemaNode({\n namespaces: {},\n roles: [],\n existingSchemas: [],\n pgVersion: '',\n });\n }\n\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = {};\n const roles: PostgresRoleSchemaNode[] = [];\n const ownedSchemas: string[] = [];\n\n for (const ns of Object.values(contract.storage.namespaces)) {\n if (!isPostgresSchema(ns)) continue;\n\n // Role entries are root-level diff subjects: they hoist to the database\n // root from every slot and never count toward whether a namespace\n // materializes a schema node.\n for (const role of Object.values(ns.role)) {\n roles.push(new PostgresRoleSchemaNode({ name: role.name, namespaceId: role.namespaceId }));\n }\n\n // The unbound slot resolves its DDL schema to 'public', so it\n // materializes a schema node exactly when it has non-role content — a\n // late-binding contract keeps today's behavior (the slot carries the\n // tables), while a roles-only unbound slot alongside named namespaces\n // contributes only root roles and no node (which would otherwise be a\n // spurious empty 'public' node, clobbering a real bound 'public'\n // namespace's node keyed by the same resolved schema name).\n if (ns.id === UNBOUND_NAMESPACE_ID) {\n const hasNonRoleContent = Object.entries(ns.entries).some(\n ([entriesKey, slot]) => entriesKey !== 'role' && Object.keys(slot).length > 0,\n );\n if (!hasNonRoleContent) continue;\n }\n\n const ddlSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id);\n ownedSchemas.push(ddlSchema);\n\n // Convert only THIS namespace's tables (passing the full storage for\n // type/value-set/enum resolution that spans namespaces), so the same table\n // name can exist in two schemas without colliding in a bare-keyed record.\n const sqlTables = contractNamespaceToSchemaIR(contract.storage, ns.id, options).tables;\n\n const policiesByTable = new Map<string, PostgresPolicySchemaNode[]>();\n for (const policy of Object.values(ns.policy)) {\n const list = policiesByTable.get(policy.tableName) ?? [];\n list.push(toPolicyNode(policy, ddlSchema));\n policiesByTable.set(policy.tableName, list);\n }\n\n const tables: Record<string, PostgresTableSchemaNode> = {};\n for (const tableName of Object.keys(ns.table)) {\n const sqlTable = sqlTables[tableName];\n if (sqlTable === undefined) continue;\n // The family conversion stamps `referencedSchema` only for bound FK\n // targets; an absent value means the FK targets the unbound namespace.\n // Postgres restores its own coordinate for that slot (the unbound\n // singleton's id) so the raw coordinate keeps qualifying REFERENCES\n // clauses, and resolves the real live DDL schema — introspected FKs\n // already carry the live schema, so this is what lets an expected FK\n // pair (by diff-node id) with its introspected counterpart.\n const foreignKeys = sqlTable.foreignKeys.map((fk) => {\n const resolvedReferencedNamespace = resolveDdlSchemaForNamespaceStorage(\n contract.storage,\n fk.referencedSchema ?? UNBOUND_NAMESPACE_ID,\n );\n return new SqlForeignKeyIR({\n columns: fk.columns,\n referencedTable: fk.referencedTable,\n referencedColumns: fk.referencedColumns,\n referencedSchema: fk.referencedSchema ?? UNBOUND_NAMESPACE_ID,\n ...ifDefined('name', fk.name),\n ...ifDefined('onDelete', fk.onDelete),\n ...ifDefined('onUpdate', fk.onUpdate),\n ...ifDefined('annotations', fk.annotations),\n resolvedReferencedNamespace,\n dependsOn: [\n tableDependsOn(resolvedReferencedNamespace, fk.referencedTable),\n ...columnDependsOn(ddlSchema, tableName, fk.columns),\n ],\n });\n });\n // The family stamped these children's own-column `dependsOn` with the\n // flat (single-schema) chain; the Postgres tree nests them under a\n // namespace, so re-stamp with the multi-schema chain that matches this\n // tree's paths. Every other field is carried through unchanged.\n const uniques = sqlTable.uniques.map(\n (u) =>\n new SqlUniqueIR({\n columns: u.columns,\n ...ifDefined('name', u.name),\n ...ifDefined('annotations', u.annotations),\n dependsOn: columnDependsOn(ddlSchema, tableName, u.columns),\n }),\n );\n const indexes = sqlTable.indexes.map(\n (i) =>\n new SqlIndexIR({\n columns: i.columns,\n unique: i.unique,\n partial: i.partial,\n name: i.name,\n type: i.type,\n options: i.options,\n annotations: i.annotations,\n dependsOn: columnDependsOn(ddlSchema, tableName, i.columns),\n }),\n );\n const primaryKey =\n sqlTable.primaryKey !== undefined\n ? new PrimaryKey({\n columns: sqlTable.primaryKey.columns,\n ...ifDefined('name', sqlTable.primaryKey.name),\n dependsOn: columnDependsOn(ddlSchema, tableName, sqlTable.primaryKey.columns),\n })\n : undefined;\n tables[tableName] = new PostgresTableSchemaNode({\n name: sqlTable.name,\n columns: sqlTable.columns,\n foreignKeys,\n uniques,\n indexes,\n ...ifDefined('primaryKey', primaryKey),\n ...ifDefined('annotations', sqlTable.annotations),\n ...ifDefined('checks', sqlTable.checks),\n policies: policiesByTable.get(tableName) ?? [],\n // Marker-driven, never derived from the policy set: the `rls` entry\n // is the single authored source of enablement.\n rlsEnabled: Object.hasOwn(ns.rls, tableName),\n });\n }\n\n for (const [tableName, tablePolicies] of policiesByTable) {\n if (!(tableName in tables)) {\n const policyName = tablePolicies[0]?.name ?? '(unknown)';\n throw postgresError(\n 'CONTRACT.POLICY_INVALID',\n `contract-to-postgres-database-schema-node: policy \"${policyName}\" references table \"${tableName}\" not present in namespace \"${ddlSchema}\"`,\n { meta: { policyName, tableName, namespaceId: ddlSchema, reason: 'table-missing' } },\n );\n }\n if (!Object.hasOwn(ns.rls, tableName)) {\n const policyPrefix = tablePolicies[0]?.prefix ?? '(unknown)';\n throw postgresError(\n 'CONTRACT.POLICY_INVALID',\n `contract-to-postgres-database-schema-node: policy \"${policyPrefix}\" targets table \"${tableName}\" in namespace \"${ddlSchema}\", which is not RLS-controlled. Mark the model with @@rls (entries.rls[\"${tableName}\"]) or remove the policy.`,\n {\n meta: {\n policyName: policyPrefix,\n tableName,\n namespaceId: ddlSchema,\n reason: 'table-not-rls-controlled',\n },\n },\n );\n }\n }\n\n const nativeEnums = Object.values(ns.entries.native_enum ?? {}).map(\n (entity) =>\n new PostgresNativeEnumSchemaNode({\n typeName: entity.typeName,\n namespaceId: ddlSchema,\n members: entity.members,\n ...ifDefined('control', entity.control),\n }),\n );\n\n namespaces[ddlSchema] = new PostgresNamespaceSchemaNode({\n schemaName: ddlSchema,\n tables,\n nativeEnums,\n });\n }\n\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles,\n existingSchemas: ownedSchemas,\n pgVersion: '',\n });\n}\n","import type { Contract, ControlPolicy } from '@prisma-next/contract/types';\nimport type { SqlSchemaDiffResult } from '@prisma-next/family-sql/control';\nimport { buildNativeTypeExpander } from '@prisma-next/family-sql/control';\nimport { classifyDiffSubjectGranularity } from '@prisma-next/family-sql/diff';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type { DiffableNode, SchemaDiffIssue } from '@prisma-next/framework-components/control';\nimport { diffSchemas, issueOutcome } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresResolveDefault } from '../default-normalizer';\nimport type { PostgresContract } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport {\n postgresDiffSubjectGranularity,\n type SqlSchemaDiffNode,\n} from '../schema-ir/schema-node-kinds';\nimport { contractToPostgresDatabaseSchemaNode } from './contract-to-postgres-database-schema-node';\nimport { resolvePostgresNodeIssueControlPolicySubject } from './control-policy';\n\n/**\n * Whether a diff issue's subject node is cluster-scoped — it carries its own\n * `namespaceId` field (only role and policy diff nodes do) and that\n * coordinate is the unbound sentinel, meaning the node is not owned by any\n * schema/namespace. A role node is always cluster-scoped (roles are\n * cluster-level objects); a policy node's `namespaceId` is always its\n * table's resolved DDL schema, never the sentinel. Namespace-ownership\n * scoping (which compares `issue.path[1]` against the set of DDL schemas\n * the contract owns) makes no sense for a cluster-scoped subject — its path\n * segment at that index is the object's own name, not a schema name — so\n * such an issue bypasses that scoping entirely.\n */\nfunction isClusterScopedIssue(issue: SchemaDiffIssue): boolean {\n const node = issue.expected ?? issue.actual;\n return node !== undefined && nodeNamespaceId(node) === UNBOUND_NAMESPACE_ID;\n}\n\nfunction nodeNamespaceId(node: DiffableNode): string | undefined {\n if (!Object.hasOwn(node, 'namespaceId')) return undefined;\n return blindCast<\n { namespaceId: string },\n 'presence of an own namespaceId field was just checked via Object.hasOwn'\n >(node).namespaceId;\n}\n\nfunction ownedSchemaNames(expected: PostgresDatabaseSchemaNode): ReadonlySet<string> {\n const policyNamespaces = Object.values(expected.namespaces).flatMap((ns) =>\n Object.values(ns.tables).flatMap((t) => t.policies.map((p) => p.namespaceId)),\n );\n return new Set([...policyNamespaces, ...expected.existingSchemas]);\n}\n\n/**\n * Drops contract namespaces that declare no tables from the verdict-diff\n * expected tree and the relational owned-schema set. The legacy relational\n * walk skipped a table-less namespace (e.g. an enums-only schema) before\n * pairing, so neither its DDL schema's absence nor that schema's live\n * relational contents ever reached the verdict — the pruned tree\n * reproduces that. The prune loses no expected policies: policies attach\n * to tables, so a table-less namespace carries none (the projection\n * throws on a policy referencing an absent table). Live policies in a\n * pruned schema remain governed via the full owned set (see\n * {@link diffPostgresSchema}).\n */\nfunction pruneTableLessNamespaces(\n expected: PostgresDatabaseSchemaNode,\n): PostgresDatabaseSchemaNode {\n const namespaces = Object.fromEntries(\n Object.entries(expected.namespaces).filter(([, ns]) => Object.keys(ns.tables).length > 0),\n );\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles: [...expected.roles],\n existingSchemas: expected.existingSchemas.filter((s) => namespaces[s] !== undefined),\n pgVersion: expected.pgVersion,\n });\n}\n\n/**\n * Resolves a verdict-diff issue's subject's declared control policy directly\n * from the contract, by delegating to the same node-typed resolver\n * ({@link resolvePostgresNodeIssueControlPolicySubject}) the planner uses to\n * gate DDL calls. `undefined` when the issue resolves to no contract subject.\n *\n * A role issue resolves through that same resolver to `external`\n * unconditionally (see its role branch), regardless of the contract's own\n * default policy: a role is referenced by the contract but not owned, and\n * `external`'s existing semantics — a missing declared subject still fails,\n * every extra is suppressed — are exactly the wanted asymmetric grading for\n * a cluster object the framework does not own.\n */\nfunction resolveControlPolicy(\n issue: SchemaDiffIssue,\n contract: Contract<SqlStorage>,\n): ControlPolicy | undefined {\n const nodeIssue = blindCast<\n SchemaDiffIssue<SqlSchemaDiffNode>,\n 'every node in a Postgres schema diff tree is a SqlSchemaDiffNode'\n >(issue);\n return resolvePostgresNodeIssueControlPolicySubject(nodeIssue, contract)\n ?.explicitNodeControlPolicy;\n}\n\n/**\n * The Postgres full-tree node diff for the family verify verdict: derive\n * the expected tree (resolved leaf values, expander threaded, FK schemas\n * resolved, table-less namespaces pruned), run the generic\n * differ over the trees as derived, and scope out `not-expected` findings under namespaces the\n * contract does not own. Ownership scoping bypasses cluster-scoped subjects\n * (roles today), mirroring the legacy decomposition: relational extras check\n * the PRUNED owned set (the legacy\n * per-namespace walk never visited a table-less namespace, so its live\n * relational contents are invisible), while `structural` extras (RLS\n * policies) check the FULL owned set (the legacy policy diff governed\n * every contract schema regardless of tables — RLS governance does not\n * shrink because a namespace declares no tables). The codec `verifyType`\n * hooks run once per contract namespace with tables against that\n * namespace's paired actual node (the hooks read namespace-scoped state\n * such as `nativeEnums`).\n */\nexport function diffPostgresSchema(input: {\n readonly contract: Contract<SqlStorage>;\n readonly schema: SqlSchemaIRNode;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}): SqlSchemaDiffResult {\n const postgresContract = blindCast<\n PostgresContract,\n 'diffPostgresSchema is only called with a postgres contract'\n >(input.contract);\n PostgresDatabaseSchemaNode.assert(input.schema);\n const actual = input.schema;\n const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);\n const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expandNativeType),\n resolveDefault: postgresResolveDefault,\n });\n const expected = pruneTableLessNamespaces(fullExpected);\n const relationalOwned = ownedSchemaNames(expected);\n const structuralOwned = ownedSchemaNames(fullExpected);\n const issues = diffSchemas(expected, actual).filter((issue) => {\n if (issueOutcome(issue) !== 'not-expected') return true;\n if (isClusterScopedIssue(issue)) return true;\n const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);\n const namespaceSegment = issue.path[1];\n if (namespaceSegment === undefined) return true;\n const owned = granularity === 'structural' ? structuralOwned : relationalOwned;\n return owned.has(namespaceSegment);\n });\n const namespacePairs = Object.values(expected.namespaces).map((ns) => ({\n actual: actual.namespaces[ns.schemaName],\n }));\n return {\n issues,\n resolveControlPolicy: (issue) => resolveControlPolicy(issue, postgresContract),\n namespacePairs,\n };\n}\n\n/**\n * Adds an empty namespace node to the actual tree for every expected namespace\n * absent from it. The relational plan diff pairs on namespace: a contract\n * namespace whose live schema does not exist yet must surface each of its\n * tables as `not-found` (→ `CREATE TABLE`), NOT as a single namespace\n * `not-found` that subtree-coalescing would collapse (leaving `CREATE SCHEMA`\n * with no tables). Padding makes the namespaces pair, so only table/column/\n * policy drift surfaces; `CREATE SCHEMA` comes separately from the synthesized\n * namespace-presence stitch (`verifyPostgresNamespacePresence`), never from the\n * tree diff — matching the retired per-namespace-paired relational walk, which\n * paired a missing schema against an empty namespace node.\n */\nfunction padActualNamespaces(\n expected: PostgresDatabaseSchemaNode,\n actual: PostgresDatabaseSchemaNode,\n): PostgresDatabaseSchemaNode {\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = { ...actual.namespaces };\n let padded = false;\n for (const schemaName of Object.keys(expected.namespaces)) {\n if (namespaces[schemaName] === undefined) {\n namespaces[schemaName] = new PostgresNamespaceSchemaNode({\n schemaName,\n tables: {},\n });\n padded = true;\n }\n }\n if (!padded) return actual;\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles: [...actual.roles],\n existingSchemas: [...actual.existingSchemas],\n pgVersion: actual.pgVersion,\n });\n}\n\nexport interface PostgresPlanDiff {\n /** The desired (\"end\") tree — resolved leaf values (incl. `codecRef`) on every column, table-less namespaces pruned. */\n readonly expected: PostgresDatabaseSchemaNode;\n /** The live (\"start\") tree, padded with empty namespaces so a missing schema's tables pair. */\n readonly actual: PostgresDatabaseSchemaNode;\n /** The one node diff over the two trees: relational + policy drift, cluster-scope-aware ownership filtered. */\n readonly issues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[];\n}\n\n/**\n * The Postgres planner's diff input: the SAME tree-building\n * `diffPostgresSchema` uses (expander threaded, FK schemas resolved,\n * table-less namespaces pruned, cluster-scope-aware ownership filter) plus\n * actual namespace padding (so a missing\n * schema's tables surface as `not-found` instead of a swallowed namespace\n * `not-found`). One differ drives both verify and plan; this is the\n * plan-side derivation. The single issue list covers tables / columns /\n * constraints / indexes / defaults AND policies — the caller splits it\n * (relational → `mapNodeIssueToCall`; policy → RLS ops) and stitches in\n * `CREATE SCHEMA` separately.\n */\nexport function buildPostgresPlanDiff(input: {\n readonly contract: Contract<SqlStorage>;\n readonly actualSchema: SqlSchemaIRNode;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}): PostgresPlanDiff {\n const postgresContract = blindCast<\n PostgresContract,\n 'buildPostgresPlanDiff is only called with a postgres contract'\n >(input.contract);\n PostgresDatabaseSchemaNode.assert(input.actualSchema);\n const actual = input.actualSchema;\n const expandNativeType = buildNativeTypeExpander(input.frameworkComponents);\n const projectionOptions = {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expandNativeType),\n resolveDefault: postgresResolveDefault,\n };\n const fullExpected = contractToPostgresDatabaseSchemaNode(postgresContract, projectionOptions);\n const expected = pruneTableLessNamespaces(fullExpected);\n const paddedActual = padActualNamespaces(expected, actual);\n const relationalOwned = ownedSchemaNames(expected);\n const structuralOwned = ownedSchemaNames(fullExpected);\n const issues = blindCast<\n readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n 'both trees are PostgresDatabaseSchemaNodes, so every diff-issue node is a SqlSchemaDiffNode'\n >(diffSchemas(expected, paddedActual)).filter((issue) => {\n if (issueOutcome(issue) !== 'not-expected') return true;\n if (isClusterScopedIssue(issue)) return true;\n const granularity = classifyDiffSubjectGranularity(issue, postgresDiffSubjectGranularity);\n const namespaceSegment = issue.path[1];\n if (namespaceSegment === undefined) return true;\n const owned = granularity === 'structural' ? structuralOwned : relationalOwned;\n return owned.has(nam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F,MAAM,mBAAmB,MAAM,KAAK;GACpC,IAAI,qBAAqB,KAAA,GAAW,OAAO;GAE3C,QADc,gBAAgB,eAAe,kBAAkB,gBAAA,CAClD,IAAI,gBAAgB;EACnC,CAC8C;CAAE;AAClD"}
@@ -1,2 +1,2 @@
1
- import { t as buildPostgresPlanDiff } from "./diff-database-schema-CK0FM2Z-.mjs";
1
+ import { t as buildPostgresPlanDiff } from "./diff-database-schema-C9H09OD3.mjs";
2
2
  export { buildPostgresPlanDiff };
@@ -1,5 +1,9 @@
1
1
  import { CliStructuredError } from "@prisma-next/errors/control";
2
+ import { structuredError } from "@prisma-next/utils/structured-error";
2
3
  //#region src/core/errors.ts
4
+ function postgresError(code, message, options) {
5
+ return structuredError(code, message, options);
6
+ }
3
7
  /**
4
8
  * A `PostgresMigration` operation that needs the materialized control adapter
5
9
  * — named by `operation` (e.g. `createTable`, `dropColumn`, `dataTransform`) —
@@ -30,6 +34,6 @@ function errorPostgresMigrationStackMissing(operation) {
30
34
  });
31
35
  }
32
36
  //#endregion
33
- export { errorPostgresMigrationStackMissing as t };
37
+ export { postgresError as n, errorPostgresMigrationStackMissing as t };
34
38
 
35
- //# sourceMappingURL=errors-ByDS0xJL.mjs.map
39
+ //# sourceMappingURL=errors-DBSNx7EJ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-DBSNx7EJ.mjs","names":[],"sources":["../src/core/errors.ts"],"sourcesContent":["import { CliStructuredError } from '@prisma-next/errors/control';\nimport type { StructuredError, StructuredErrorOptions } from '@prisma-next/utils/structured-error';\nimport { structuredError } from '@prisma-next/utils/structured-error';\n\nexport type PostgresTargetErrorCode =\n | 'CONTRACT.CODEC_DESCRIPTOR_MISSING'\n | 'CONTRACT.DEFAULT_INVALID'\n | 'CONTRACT.ENTITY_KIND_INVALID'\n | 'CONTRACT.IDENTIFIER_INVALID'\n | 'CONTRACT.INDEX_INVALID'\n | 'CONTRACT.INFER_UNSUPPORTED'\n | 'CONTRACT.MODEL_UNKNOWN'\n | 'CONTRACT.NAME_DUPLICATE'\n | 'CONTRACT.NATIVE_TYPE_INVALID'\n | 'CONTRACT.PACK_CONTRIBUTION_INVALID'\n | 'CONTRACT.POLICY_INVALID'\n | 'CONTRACT.ROLE_INVALID'\n | 'MIGRATION.CONTRACT_SPACE_VIOLATION'\n | 'MIGRATION.POSTGRES_CONTROL_STACK_MISSING'\n | 'MIGRATION.TARGET_MISMATCH'\n | 'RUNTIME.DECODE_FAILED'\n | 'RUNTIME.ENCODE_FAILED'\n | 'RUNTIME.TYPE_PARAMS_INVALID';\n\nexport function postgresError(\n code: PostgresTargetErrorCode,\n message: string,\n options?: StructuredErrorOptions,\n): StructuredError {\n return structuredError(code, message, options);\n}\n\n/**\n * A `PostgresMigration` operation that needs the materialized control adapter\n * — named by `operation` (e.g. `createTable`, `dropColumn`, `dataTransform`) —\n * was invoked, but the migration was constructed without a `ControlStack`.\n * Concrete authoring usage always goes through the migration CLI entrypoint,\n * which assembles a stack from the loaded `prisma-next.config.ts`; reaching this\n * error means a test fixture or ad-hoc consumer instantiated `PostgresMigration`\n * with the no-arg form (legal for `operations` / `describe` introspection only).\n *\n * The `operation` argument is required so every throw site names the operation\n * that actually failed; a new operation cannot inherit a misattributed message.\n *\n * Distinct from `MIGRATION.UNFILLED_PLACEHOLDER` (placeholder not filled)\n * and `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH` (data-transform query\n * plan against wrong contract) because the missing input is the stack\n * itself, not the per-operation contract.\n *\n * Lives in `@prisma-next/target-postgres/errors` rather than the shared\n * framework migration errors module because the failure is target-specific:\n * the contract it talks about (`PostgresMigration`, the Postgres control\n * adapter, the Postgres-target stack) only exists in this package.\n */\nexport function errorPostgresMigrationStackMissing(operation: string): CliStructuredError {\n return new CliStructuredError(\n 'MIGRATION.POSTGRES_CONTROL_STACK_MISSING',\n `PostgresMigration.${operation} requires a control adapter`,\n {\n why: `PostgresMigration.${operation} was invoked on an instance constructed without a ControlStack, so the stored controlAdapter is undefined and the operation cannot lower its plan.`,\n fix: 'Construct the migration via the migration CLI entrypoint (which assembles a ControlStack from the loaded prisma-next.config.ts), or pass a ControlStack containing a Postgres adapter to the migration constructor in test fixtures.',\n meta: { operation },\n },\n );\n}\n"],"mappings":";;;AAwBA,SAAgB,cACd,MACA,SACA,SACiB;CACjB,OAAO,gBAAgB,MAAM,SAAS,OAAO;AAC/C;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,mCAAmC,WAAuC;CACxF,OAAO,IAAI,mBACT,4CACA,qBAAqB,UAAU,8BAC/B;EACE,KAAK,qBAAqB,UAAU;EACpC,KAAK;EACL,MAAM,EAAE,UAAU;CACpB,CACF;AACF"}
package/dist/errors.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { CliStructuredError } from "@prisma-next/errors/control";
2
+ import "@prisma-next/utils/structured-error";
2
3
  //#region src/core/errors.d.ts
3
4
  /**
4
5
  * A `PostgresMigration` operation that needs the materialized control adapter
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.mts","names":[],"sources":["../src/core/errors.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;iBAwBgB,mCAAmC,oBAAoB"}
1
+ {"version":3,"file":"errors.d.mts","names":[],"sources":["../src/core/errors.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;iBAsDgB,mCAAmC,oBAAoB"}
package/dist/errors.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { t as errorPostgresMigrationStackMissing } from "./errors-ByDS0xJL.mjs";
1
+ import { t as errorPostgresMigrationStackMissing } from "./errors-DBSNx7EJ.mjs";
2
2
  export { errorPostgresMigrationStackMissing };
@@ -1,2 +1,2 @@
1
- import { l as planIssues, o as coalesceSubtreeIssues } from "./control-policy-BrcqeM82.mjs";
1
+ import { l as planIssues, o as coalesceSubtreeIssues } from "./control-policy-B-_34g05.mjs";
2
2
  export { coalesceSubtreeIssues, planIssues };
@@ -1,6 +1,6 @@
1
- import { P as createExtension } from "./op-factory-call-PBYfcv8h.mjs";
1
+ import { P as createExtension } from "./op-factory-call-BVYLIojV.mjs";
2
2
  import { t as dataTransform } from "./data-transform-BOWpliq8.mjs";
3
- import { t as PostgresMigration } from "./postgres-migration-BkIplcRz.mjs";
3
+ import { t as PostgresMigration } from "./postgres-migration-GIOABsAa.mjs";
4
4
  import { checkExpression, col, fn, foreignKey, lit, primaryKey, unique } from "@prisma-next/sql-relational-core/contract-free";
5
5
  import { placeholder } from "@prisma-next/errors/migration";
6
6
  import { MigrationCLI } from "@prisma-next/cli/migration-cli";