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

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 +1 @@
1
- {"version":3,"file":"postgres-migration-BkIplcRz.mjs","names":["SqlMigration","#endView","#startView"],"sources":["../src/core/migrations/postgres-migration.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport { Migration as SqlMigration } from '@prisma-next/family-sql/migration';\nimport type { ControlStack } from '@prisma-next/framework-components/control';\nimport { MigrationContractViews } from '@prisma-next/migration-tools/migration';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport { errorPostgresMigrationStackMissing } from '../errors';\nimport { PostgresContractView } from '../postgres-contract-view';\nimport { PostgresRlsPolicy, type PostgresRlsPolicyInput } from '../postgres-rls-policy';\nimport {\n AddCheckConstraintCall,\n AddColumnCall,\n AddForeignKeyCall,\n AddNativeEnumValueCall,\n AddPrimaryKeyCall,\n AddUniqueCall,\n AlterColumnTypeCall,\n type AlterColumnTypeOptions,\n CreateIndexCall,\n CreateNativeEnumTypeCall,\n CreatePostgresRlsPolicyCall,\n CreateSchemaCall,\n CreateTableCall,\n DisableRowLevelSecurityCall,\n DropCheckConstraintCall,\n DropColumnCall,\n DropConstraintCall,\n DropDefaultCall,\n DropIndexCall,\n DropNativeEnumTypeCall,\n DropNotNullCall,\n DropPostgresRlsPolicyCall,\n DropTableCall,\n EnableRowLevelSecurityCall,\n RenamePostgresRlsPolicyCall,\n SetDefaultCall,\n SetNotNullCall,\n} from './op-factory-call';\nimport { type DataTransformOptions, dataTransform } from './operations/data-transform';\nimport { installExtension } from './operations/dependencies';\nimport type { CreateIndexExtras } from './operations/indexes';\nimport type { ForeignKeySpec } from './operations/shared';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\n/**\n * Target-owned base class for Postgres migrations.\n *\n * Fixes the `SqlMigration` generic to `PostgresPlanTargetDetails` and the\n * abstract `targetId` to the Postgres target-id string literal, so both\n * user-authored migrations and renderer-generated scaffolds (the output of\n * `renderCallsToTypeScript`) can extend `PostgresMigration` directly without\n * redeclaring target-local identity.\n *\n * Mirrors `MongoMigration` in `@prisma-next/family-mongo`: the renderer\n * emits `extends Migration` against a facade re-export of this class\n * from `@prisma-next/postgres/migration`, keeping the authoring surface\n * target-scoped rather than family-scoped.\n *\n * The constructor materializes a single Postgres `SqlControlAdapter` from\n * `stack.adapter.create(stack)` and stores it; the protected `dataTransform`\n * instance method forwards to the free `dataTransform` factory with that\n * stored adapter, so user migrations can write `this.dataTransform(...)`\n * without threading the adapter through every call.\n *\n * Every method requires an explicit `schema`. Postgres migrations name their\n * schema deliberately — there is no default and no `search_path`-relative\n * option. A migration that left the schema unspecified would resolve against\n * whatever `search_path` the connection happened to carry, and that ambiguity\n * is an antipattern in a migration. (The unbound/unspecified namespace concept\n * remains for SQLite, which has no schemas, and for Mongo's connection `db`.)\n */\nexport abstract class PostgresMigration<\n Start extends Contract<SqlStorage> = Contract<SqlStorage>,\n End extends Contract<SqlStorage> = Contract<SqlStorage>,\n> extends SqlMigration<PostgresPlanTargetDetails, 'postgres', Start, End> {\n readonly targetId = 'postgres' as const;\n\n /**\n * Materialized Postgres control adapter, created once per migration\n * instance from the injected stack. `undefined` only when the migration\n * was instantiated without a stack (test fixtures); `controlAdapterFor`\n * throws a MIGRATION.POSTGRES_CONTROL_STACK_MISSING in that case to surface the misuse.\n */\n protected readonly controlAdapter: SqlControlAdapter<'postgres'> | undefined;\n\n #endView = new MigrationContractViews<PostgresContractView<End>>(\n this,\n 'PostgresMigration',\n (json) => PostgresContractView.fromJson<End>(json),\n );\n #startView = new MigrationContractViews<PostgresContractView<Start>>(\n this,\n 'PostgresMigration',\n (json) => PostgresContractView.fromJson<Start>(json),\n );\n\n constructor(stack?: ControlStack<'sql', 'postgres'>) {\n super(stack);\n // The descriptor `create()` is typed as the wider `ControlAdapterInstance`;\n // the Postgres descriptor concretely returns a `SqlControlAdapter<'postgres'>`,\n // so the cast holds for any Postgres-target stack assembled at runtime.\n this.controlAdapter = stack?.adapter\n ? (stack.adapter.create(stack) as SqlControlAdapter<'postgres'>)\n : undefined;\n }\n\n /**\n * Returns the materialized control adapter, or throws a MIGRATION.POSTGRES_CONTROL_STACK_MISSING naming\n * `operation` when the migration was constructed without a `ControlStack`.\n * Single home for the null-check that every DDL/DML method shares.\n */\n private controlAdapterFor(operation: string): SqlControlAdapter<'postgres'> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing(operation);\n }\n return this.controlAdapter;\n }\n\n /**\n * The typed, schema-qualified Postgres view over this migration's end-state\n * contract — `this.endContract.namespace.<schema>.table.<name>`, etc. Throws\n * if no `endContractJson` was provided.\n */\n get endContract(): PostgresContractView<End> {\n return this.#endView.endContract;\n }\n\n /**\n * The typed Postgres view over this migration's start-state contract, or\n * `null` for a baseline migration (no `startContractJson`).\n */\n get startContract(): PostgresContractView<Start> | null {\n return this.#startView.startContract;\n }\n\n /**\n * Instance-method wrapper around the free `dataTransform` factory that\n * supplies the stored control adapter. Authors call this from inside\n * `get operations()`; the adapter argument is hidden from the call site.\n */\n protected dataTransform<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n name: string,\n options: DataTransformOptions,\n ): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return dataTransform(contract, name, options, this.controlAdapterFor('dataTransform'));\n }\n\n /**\n * Emit a `CREATE TABLE` migration operation. Builds a typed DDL node from\n * the supplied options and lowers it through the stored control adapter.\n * Throws if no adapter is present (i.e. migration instantiated without a stack).\n */\n protected createTable(options: {\n readonly schema: string;\n readonly table: string;\n readonly ifNotExists?: boolean;\n readonly columns: readonly DdlColumn[];\n readonly constraints?: readonly DdlTableConstraint[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new CreateTableCall(\n options.schema,\n options.table,\n options.columns,\n options.constraints,\n ).toOp(this.controlAdapterFor('createTable'));\n }\n\n /**\n * Emit a `CREATE SCHEMA` migration operation. Builds a typed DDL node from\n * the supplied options and lowers it through the stored control adapter.\n * Throws if no adapter is present (i.e. migration instantiated without a stack).\n */\n protected createSchema(options: {\n readonly schema: string;\n readonly ifNotExists?: boolean;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new CreateSchemaCall(options.schema).toOp(this.controlAdapterFor('createSchema'));\n }\n\n /**\n * Emit a `CREATE TYPE ... AS ENUM (...)` migration operation for a managed\n * native enum. Builds a typed DDL node and lowers it through the stored\n * control adapter (members render in declaration order). Throws if no adapter\n * is present.\n */\n protected createNativeEnumType(options: {\n readonly schema: string;\n readonly typeName: string;\n readonly members: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new CreateNativeEnumTypeCall(options.schema, options.typeName, options.members).toOp(\n this.controlAdapterFor('createNativeEnumType'),\n );\n }\n\n /**\n * Emit a `DROP TYPE` migration operation for a managed native enum, lowered\n * through the stored control adapter. Throws if no adapter is present.\n */\n protected dropNativeEnumType(options: {\n readonly schema: string;\n readonly typeName: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropNativeEnumTypeCall(options.schema, options.typeName).toOp(\n this.controlAdapterFor('dropNativeEnumType'),\n );\n }\n\n /**\n * Emit an `ALTER TYPE ... ADD VALUE` migration operation appending one\n * member to a managed native enum, lowered through the stored control\n * adapter. Throws if no adapter is present. Every appended value is its\n * own operation — call this once per value to append more than one.\n */\n protected addNativeEnumValue(options: {\n readonly schema: string;\n readonly typeName: string;\n readonly value: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AddNativeEnumValueCall(options.schema, options.typeName, options.value).toOp(\n this.controlAdapterFor('addNativeEnumValue'),\n );\n }\n\n protected addColumn(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: DdlColumn;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AddColumnCall(options.schema, options.table, options.column).toOp(\n this.controlAdapterFor('addColumn'),\n );\n }\n\n protected addPrimaryKey(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly columns: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AddPrimaryKeyCall(\n options.schema,\n options.table,\n options.constraint,\n options.columns,\n ).toOp(this.controlAdapterFor('addPrimaryKey'));\n }\n\n protected addUnique(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly columns: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AddUniqueCall(\n options.schema,\n options.table,\n options.constraint,\n options.columns,\n ).toOp(this.controlAdapterFor('addUnique'));\n }\n\n protected addForeignKey(options: {\n readonly schema: string;\n readonly table: string;\n readonly foreignKey: ForeignKeySpec;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AddForeignKeyCall(options.schema, options.table, options.foreignKey).toOp(\n this.controlAdapterFor('addForeignKey'),\n );\n }\n\n protected addCheckConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly column: string;\n readonly values: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AddCheckConstraintCall(\n options.schema,\n options.table,\n options.constraint,\n options.column,\n options.values,\n ).toOp(this.controlAdapterFor('addCheckConstraint'));\n }\n\n protected dropCheckConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropCheckConstraintCall(options.schema, options.table, options.constraint).toOp(\n this.controlAdapterFor('dropCheckConstraint'),\n );\n }\n\n protected dropConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly kind?: 'foreignKey' | 'unique' | 'primaryKey';\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropConstraintCall(\n options.schema,\n options.table,\n options.constraint,\n options.kind ?? 'unique',\n ).toOp(this.controlAdapterFor('dropConstraint'));\n }\n\n protected dropTable(options: {\n readonly schema: string;\n readonly table: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropTableCall(options.schema, options.table).toOp(\n this.controlAdapterFor('dropTable'),\n );\n }\n\n protected dropColumn(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropColumnCall(options.schema, options.table, options.column).toOp(\n this.controlAdapterFor('dropColumn'),\n );\n }\n\n protected alterColumnType(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly options: AlterColumnTypeOptions;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AlterColumnTypeCall(\n options.schema,\n options.table,\n options.column,\n options.options,\n ).toOp(this.controlAdapterFor('alterColumnType'));\n }\n\n protected setNotNull(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new SetNotNullCall(options.schema, options.table, options.column).toOp(\n this.controlAdapterFor('setNotNull'),\n );\n }\n\n protected dropNotNull(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropNotNullCall(options.schema, options.table, options.column).toOp(\n this.controlAdapterFor('dropNotNull'),\n );\n }\n\n protected setDefault(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly defaultSql: string;\n readonly operationClass?: 'additive' | 'widening';\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new SetDefaultCall(\n options.schema,\n options.table,\n options.column,\n options.defaultSql,\n options.operationClass,\n ).toOp(this.controlAdapterFor('setDefault'));\n }\n\n protected dropDefault(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropDefaultCall(options.schema, options.table, options.column).toOp(\n this.controlAdapterFor('dropDefault'),\n );\n }\n\n protected createIndex(options: {\n readonly schema: string;\n readonly table: string;\n readonly index: string;\n readonly columns: readonly string[];\n readonly extras?: CreateIndexExtras;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new CreateIndexCall(\n options.schema,\n options.table,\n options.index,\n options.columns,\n options.extras,\n ).toOp(this.controlAdapterFor('createIndex'));\n }\n\n protected dropIndex(options: {\n readonly schema: string;\n readonly table: string;\n readonly index: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropIndexCall(options.schema, options.table, options.index).toOp(\n this.controlAdapterFor('dropIndex'),\n );\n }\n\n protected installExtension(options: {\n readonly extensionName: string;\n readonly invariantId: string;\n readonly id: string;\n readonly label?: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return installExtension(options, this.controlAdapterFor('installExtension'));\n }\n\n protected enableRowLevelSecurity(options: {\n readonly schema: string;\n readonly table: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new EnableRowLevelSecurityCall(options.schema, options.table).toOp(\n this.controlAdapterFor('enableRowLevelSecurity'),\n );\n }\n\n protected disableRowLevelSecurity(options: {\n readonly schema: string;\n readonly table: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DisableRowLevelSecurityCall(options.schema, options.table).toOp(\n this.controlAdapterFor('disableRowLevelSecurity'),\n );\n }\n\n protected createRlsPolicy(options: {\n readonly schema: string;\n readonly table: string;\n readonly policy: PostgresRlsPolicyInput;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new CreatePostgresRlsPolicyCall(\n options.schema,\n options.table,\n new PostgresRlsPolicy(options.policy),\n ).toOp(this.controlAdapterFor('createRlsPolicy'));\n }\n\n protected dropRlsPolicy(options: {\n readonly schema: string;\n readonly table: string;\n readonly policy: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropPostgresRlsPolicyCall(options.schema, options.table, options.policy).toOp(\n this.controlAdapterFor('dropRlsPolicy'),\n );\n }\n\n protected renameRlsPolicy(options: {\n readonly schema: string;\n readonly table: string;\n readonly from: string;\n readonly to: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new RenamePostgresRlsPolicyCall(\n options.schema,\n options.table,\n options.from,\n options.to,\n ).toOp(this.controlAdapterFor('renameRlsPolicy'));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,IAAsB,oBAAtB,cAGUA,UAAgE;CACxE,WAAoB;;;;;;;CAQpB;CAEA,WAAW,IAAI,uBACb,MACA,sBACC,SAAS,qBAAqB,SAAc,IAAI,CACnD;CACA,aAAa,IAAI,uBACf,MACA,sBACC,SAAS,qBAAqB,SAAgB,IAAI,CACrD;CAEA,YAAY,OAAyC;EACnD,MAAM,KAAK;EAIX,KAAK,iBAAiB,OAAO,UACxB,MAAM,QAAQ,OAAO,KAAK,IAC3B,KAAA;CACN;;;;;;CAOA,kBAA0B,WAAkD;EAC1E,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC,SAAS;EAEpD,OAAO,KAAK;CACd;;;;;;CAOA,IAAI,cAAyC;E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,0BAA0B,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,MAAM,CAAC,CAAC,KAClF,KAAK,kBAAkB,eAAe,CACxC;CACF;CAEA,gBAA0B,SAKwC;EAChE,OAAO,IAAI,4BACT,QAAQ,QACR,QAAQ,OACR,QAAQ,MACR,QAAQ,EACV,CAAC,CAAC,KAAK,KAAK,kBAAkB,iBAAiB,CAAC;CAClD;AACF"}
1
+ {"version":3,"file":"postgres-migration-GIOABsAa.mjs","names":["SqlMigration","#endView","#startView"],"sources":["../src/core/migrations/postgres-migration.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';\nimport { Migration as SqlMigration } from '@prisma-next/family-sql/migration';\nimport type { ControlStack } from '@prisma-next/framework-components/control';\nimport { MigrationContractViews } from '@prisma-next/migration-tools/migration';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { DdlColumn, DdlTableConstraint } from '@prisma-next/sql-relational-core/ast';\nimport { errorPostgresMigrationStackMissing } from '../errors';\nimport { PostgresContractView } from '../postgres-contract-view';\nimport { PostgresRlsPolicy, type PostgresRlsPolicyInput } from '../postgres-rls-policy';\nimport {\n AddCheckConstraintCall,\n AddColumnCall,\n AddForeignKeyCall,\n AddNativeEnumValueCall,\n AddPrimaryKeyCall,\n AddUniqueCall,\n AlterColumnTypeCall,\n type AlterColumnTypeOptions,\n CreateIndexCall,\n CreateNativeEnumTypeCall,\n CreatePostgresRlsPolicyCall,\n CreateSchemaCall,\n CreateTableCall,\n DisableRowLevelSecurityCall,\n DropCheckConstraintCall,\n DropColumnCall,\n DropConstraintCall,\n DropDefaultCall,\n DropIndexCall,\n DropNativeEnumTypeCall,\n DropNotNullCall,\n DropPostgresRlsPolicyCall,\n DropTableCall,\n EnableRowLevelSecurityCall,\n RenamePostgresRlsPolicyCall,\n SetDefaultCall,\n SetNotNullCall,\n} from './op-factory-call';\nimport { type DataTransformOptions, dataTransform } from './operations/data-transform';\nimport { installExtension } from './operations/dependencies';\nimport type { CreateIndexExtras } from './operations/indexes';\nimport type { ForeignKeySpec } from './operations/shared';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\n/**\n * Target-owned base class for Postgres migrations.\n *\n * Fixes the `SqlMigration` generic to `PostgresPlanTargetDetails` and the\n * abstract `targetId` to the Postgres target-id string literal, so both\n * user-authored migrations and renderer-generated scaffolds (the output of\n * `renderCallsToTypeScript`) can extend `PostgresMigration` directly without\n * redeclaring target-local identity.\n *\n * Mirrors `MongoMigration` in `@prisma-next/family-mongo`: the renderer\n * emits `extends Migration` against a facade re-export of this class\n * from `@prisma-next/postgres/migration`, keeping the authoring surface\n * target-scoped rather than family-scoped.\n *\n * The constructor materializes a single Postgres `SqlControlAdapter` from\n * `stack.adapter.create(stack)` and stores it; the protected `dataTransform`\n * instance method forwards to the free `dataTransform` factory with that\n * stored adapter, so user migrations can write `this.dataTransform(...)`\n * without threading the adapter through every call.\n *\n * Every method requires an explicit `schema`. Postgres migrations name their\n * schema deliberately — there is no default and no `search_path`-relative\n * option. A migration that left the schema unspecified would resolve against\n * whatever `search_path` the connection happened to carry, and that ambiguity\n * is an antipattern in a migration. (The unbound/unspecified namespace concept\n * remains for SQLite, which has no schemas, and for Mongo's connection `db`.)\n */\nexport abstract class PostgresMigration<\n Start extends Contract<SqlStorage> = Contract<SqlStorage>,\n End extends Contract<SqlStorage> = Contract<SqlStorage>,\n> extends SqlMigration<PostgresPlanTargetDetails, 'postgres', Start, End> {\n readonly targetId = 'postgres' as const;\n\n /**\n * Materialized Postgres control adapter, created once per migration\n * instance from the injected stack. `undefined` only when the migration\n * was instantiated without a stack (test fixtures); `controlAdapterFor`\n * throws a MIGRATION.POSTGRES_CONTROL_STACK_MISSING in that case to surface the misuse.\n */\n protected readonly controlAdapter: SqlControlAdapter<'postgres'> | undefined;\n\n #endView = new MigrationContractViews<PostgresContractView<End>>(\n this,\n 'PostgresMigration',\n (json) => PostgresContractView.fromJson<End>(json),\n );\n #startView = new MigrationContractViews<PostgresContractView<Start>>(\n this,\n 'PostgresMigration',\n (json) => PostgresContractView.fromJson<Start>(json),\n );\n\n constructor(stack?: ControlStack<'sql', 'postgres'>) {\n super(stack);\n // The descriptor `create()` is typed as the wider `ControlAdapterInstance`;\n // the Postgres descriptor concretely returns a `SqlControlAdapter<'postgres'>`,\n // so the cast holds for any Postgres-target stack assembled at runtime.\n this.controlAdapter = stack?.adapter\n ? (stack.adapter.create(stack) as SqlControlAdapter<'postgres'>)\n : undefined;\n }\n\n /**\n * Returns the materialized control adapter, or throws a MIGRATION.POSTGRES_CONTROL_STACK_MISSING naming\n * `operation` when the migration was constructed without a `ControlStack`.\n * Single home for the null-check that every DDL/DML method shares.\n */\n private controlAdapterFor(operation: string): SqlControlAdapter<'postgres'> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing(operation);\n }\n return this.controlAdapter;\n }\n\n /**\n * The typed, schema-qualified Postgres view over this migration's end-state\n * contract — `this.endContract.namespace.<schema>.table.<name>`, etc. Throws\n * if no `endContractJson` was provided.\n */\n get endContract(): PostgresContractView<End> {\n return this.#endView.endContract;\n }\n\n /**\n * The typed Postgres view over this migration's start-state contract, or\n * `null` for a baseline migration (no `startContractJson`).\n */\n get startContract(): PostgresContractView<Start> | null {\n return this.#startView.startContract;\n }\n\n /**\n * Instance-method wrapper around the free `dataTransform` factory that\n * supplies the stored control adapter. Authors call this from inside\n * `get operations()`; the adapter argument is hidden from the call site.\n */\n protected dataTransform<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n name: string,\n options: DataTransformOptions,\n ): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return dataTransform(contract, name, options, this.controlAdapterFor('dataTransform'));\n }\n\n /**\n * Emit a `CREATE TABLE` migration operation. Builds a typed DDL node from\n * the supplied options and lowers it through the stored control adapter.\n * Throws if no adapter is present (i.e. migration instantiated without a stack).\n */\n protected createTable(options: {\n readonly schema: string;\n readonly table: string;\n readonly ifNotExists?: boolean;\n readonly columns: readonly DdlColumn[];\n readonly constraints?: readonly DdlTableConstraint[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new CreateTableCall(\n options.schema,\n options.table,\n options.columns,\n options.constraints,\n ).toOp(this.controlAdapterFor('createTable'));\n }\n\n /**\n * Emit a `CREATE SCHEMA` migration operation. Builds a typed DDL node from\n * the supplied options and lowers it through the stored control adapter.\n * Throws if no adapter is present (i.e. migration instantiated without a stack).\n */\n protected createSchema(options: {\n readonly schema: string;\n readonly ifNotExists?: boolean;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new CreateSchemaCall(options.schema).toOp(this.controlAdapterFor('createSchema'));\n }\n\n /**\n * Emit a `CREATE TYPE ... AS ENUM (...)` migration operation for a managed\n * native enum. Builds a typed DDL node and lowers it through the stored\n * control adapter (members render in declaration order). Throws if no adapter\n * is present.\n */\n protected createNativeEnumType(options: {\n readonly schema: string;\n readonly typeName: string;\n readonly members: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new CreateNativeEnumTypeCall(options.schema, options.typeName, options.members).toOp(\n this.controlAdapterFor('createNativeEnumType'),\n );\n }\n\n /**\n * Emit a `DROP TYPE` migration operation for a managed native enum, lowered\n * through the stored control adapter. Throws if no adapter is present.\n */\n protected dropNativeEnumType(options: {\n readonly schema: string;\n readonly typeName: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropNativeEnumTypeCall(options.schema, options.typeName).toOp(\n this.controlAdapterFor('dropNativeEnumType'),\n );\n }\n\n /**\n * Emit an `ALTER TYPE ... ADD VALUE` migration operation appending one\n * member to a managed native enum, lowered through the stored control\n * adapter. Throws if no adapter is present. Every appended value is its\n * own operation — call this once per value to append more than one.\n */\n protected addNativeEnumValue(options: {\n readonly schema: string;\n readonly typeName: string;\n readonly value: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AddNativeEnumValueCall(options.schema, options.typeName, options.value).toOp(\n this.controlAdapterFor('addNativeEnumValue'),\n );\n }\n\n protected addColumn(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: DdlColumn;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AddColumnCall(options.schema, options.table, options.column).toOp(\n this.controlAdapterFor('addColumn'),\n );\n }\n\n protected addPrimaryKey(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly columns: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AddPrimaryKeyCall(\n options.schema,\n options.table,\n options.constraint,\n options.columns,\n ).toOp(this.controlAdapterFor('addPrimaryKey'));\n }\n\n protected addUnique(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly columns: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AddUniqueCall(\n options.schema,\n options.table,\n options.constraint,\n options.columns,\n ).toOp(this.controlAdapterFor('addUnique'));\n }\n\n protected addForeignKey(options: {\n readonly schema: string;\n readonly table: string;\n readonly foreignKey: ForeignKeySpec;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AddForeignKeyCall(options.schema, options.table, options.foreignKey).toOp(\n this.controlAdapterFor('addForeignKey'),\n );\n }\n\n protected addCheckConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly column: string;\n readonly values: readonly string[];\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AddCheckConstraintCall(\n options.schema,\n options.table,\n options.constraint,\n options.column,\n options.values,\n ).toOp(this.controlAdapterFor('addCheckConstraint'));\n }\n\n protected dropCheckConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropCheckConstraintCall(options.schema, options.table, options.constraint).toOp(\n this.controlAdapterFor('dropCheckConstraint'),\n );\n }\n\n protected dropConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n readonly kind?: 'foreignKey' | 'unique' | 'primaryKey';\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropConstraintCall(\n options.schema,\n options.table,\n options.constraint,\n options.kind ?? 'unique',\n ).toOp(this.controlAdapterFor('dropConstraint'));\n }\n\n protected dropTable(options: {\n readonly schema: string;\n readonly table: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropTableCall(options.schema, options.table).toOp(\n this.controlAdapterFor('dropTable'),\n );\n }\n\n protected dropColumn(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropColumnCall(options.schema, options.table, options.column).toOp(\n this.controlAdapterFor('dropColumn'),\n );\n }\n\n protected alterColumnType(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly options: AlterColumnTypeOptions;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new AlterColumnTypeCall(\n options.schema,\n options.table,\n options.column,\n options.options,\n ).toOp(this.controlAdapterFor('alterColumnType'));\n }\n\n protected setNotNull(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new SetNotNullCall(options.schema, options.table, options.column).toOp(\n this.controlAdapterFor('setNotNull'),\n );\n }\n\n protected dropNotNull(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropNotNullCall(options.schema, options.table, options.column).toOp(\n this.controlAdapterFor('dropNotNull'),\n );\n }\n\n protected setDefault(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n readonly defaultSql: string;\n readonly operationClass?: 'additive' | 'widening';\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new SetDefaultCall(\n options.schema,\n options.table,\n options.column,\n options.defaultSql,\n options.operationClass,\n ).toOp(this.controlAdapterFor('setDefault'));\n }\n\n protected dropDefault(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropDefaultCall(options.schema, options.table, options.column).toOp(\n this.controlAdapterFor('dropDefault'),\n );\n }\n\n protected createIndex(options: {\n readonly schema: string;\n readonly table: string;\n readonly index: string;\n readonly columns: readonly string[];\n readonly extras?: CreateIndexExtras;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new CreateIndexCall(\n options.schema,\n options.table,\n options.index,\n options.columns,\n options.extras,\n ).toOp(this.controlAdapterFor('createIndex'));\n }\n\n protected dropIndex(options: {\n readonly schema: string;\n readonly table: string;\n readonly index: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropIndexCall(options.schema, options.table, options.index).toOp(\n this.controlAdapterFor('dropIndex'),\n );\n }\n\n protected installExtension(options: {\n readonly extensionName: string;\n readonly invariantId: string;\n readonly id: string;\n readonly label?: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return installExtension(options, this.controlAdapterFor('installExtension'));\n }\n\n protected enableRowLevelSecurity(options: {\n readonly schema: string;\n readonly table: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new EnableRowLevelSecurityCall(options.schema, options.table).toOp(\n this.controlAdapterFor('enableRowLevelSecurity'),\n );\n }\n\n protected disableRowLevelSecurity(options: {\n readonly schema: string;\n readonly table: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DisableRowLevelSecurityCall(options.schema, options.table).toOp(\n this.controlAdapterFor('disableRowLevelSecurity'),\n );\n }\n\n protected createRlsPolicy(options: {\n readonly schema: string;\n readonly table: string;\n readonly policy: PostgresRlsPolicyInput;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new CreatePostgresRlsPolicyCall(\n options.schema,\n options.table,\n new PostgresRlsPolicy(options.policy),\n ).toOp(this.controlAdapterFor('createRlsPolicy'));\n }\n\n protected dropRlsPolicy(options: {\n readonly schema: string;\n readonly table: string;\n readonly policy: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new DropPostgresRlsPolicyCall(options.schema, options.table, options.policy).toOp(\n this.controlAdapterFor('dropRlsPolicy'),\n );\n }\n\n protected renameRlsPolicy(options: {\n readonly schema: string;\n readonly table: string;\n readonly from: string;\n readonly to: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n return new RenamePostgresRlsPolicyCall(\n options.schema,\n options.table,\n options.from,\n options.to,\n ).toOp(this.controlAdapterFor('renameRlsPolicy'));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,IAAsB,oBAAtB,cAGUA,UAAgE;CACxE,WAAoB;;;;;;;CAQpB;CAEA,WAAW,IAAI,uBACb,MACA,sBACC,SAAS,qBAAqB,SAAc,IAAI,CACnD;CACA,aAAa,IAAI,uBACf,MACA,sBACC,SAAS,qBAAqB,SAAgB,IAAI,CACrD;CAEA,YAAY,OAAyC;EACnD,MAAM,KAAK;EAIX,KAAK,iBAAiB,OAAO,UACxB,MAAM,QAAQ,OAAO,KAAK,IAC3B,KAAA;CACN;;;;;;CAOA,kBAA0B,WAAkD;EAC1E,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC,SAAS;EAEpD,OAAO,KAAK;CACd;;;;;;CAOA,IAAI,cAAyC;EAC3C,OAAO,KAAKC,SAAS;CACvB;;;;;CAMA,IAAI,gBAAoD;EACtD,OAAO,KAAKC,WAAW;CACzB;;;;;;CAOA,cACE,UACA,MACA,SAC+D;EAC/D,OAAO,cAAc,UAAU,MAAM,S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ACR,QAAQ,OACR,QAAQ,MACR,QAAQ,EACV,CAAC,CAAC,KAAK,KAAK,kBAAkB,iBAAiB,CAAC;CAClD;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { b as PG_TEXT_CODEC_ID } from "./codec-ids-D3G8K0YM.mjs";
2
2
  import { t as PostgresNativeEnum } from "./postgres-native-enum-BwVNf0Ku.mjs";
3
- import { n as escapeLiteral } from "./sql-utils-SU4FDvIV.mjs";
3
+ import { t as escapeLiteral } from "./sql-utils-B2lzkKfP.mjs";
4
4
  import { TableSource } from "@prisma-next/sql-relational-core/ast";
5
5
  import { UNBOUND_NAMESPACE_ID, freezeNode, hydrateNamespaceEntities } from "@prisma-next/framework-components/ir";
6
6
  import { blindCast } from "@prisma-next/utils/casts";
@@ -421,4 +421,4 @@ function postgresCreateNamespace(input) {
421
421
  //#endregion
422
422
  export { PostgresRlsEnablement as _, nativeEnumEntityKind as a, roleEntityKind as c, PostgresRlsEnablementSchema as d, PostgresRlsPolicySchema as f, PostgresRlsPolicy as g, ROLE_DEFAULT_CONTROL_POLICY as h, postgresCreateNamespace as i, PostgresTableSource as l, PostgresRole as m, PostgresUnboundSchema as n, policyEntityKind as o, PostgresRoleSchema as p, isPostgresSchema as r, rlsEnablementEntityKind as s, PostgresSchema as t, PostgresNativeEnumSchema as u };
423
423
 
424
- //# sourceMappingURL=postgres-schema-CewLYHB7.mjs.map
424
+ //# sourceMappingURL=postgres-schema-CTplQZDK.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-schema-CewLYHB7.mjs","names":[],"sources":["../src/core/postgres-rls-enablement.ts","../src/core/postgres-rls-policy.ts","../src/core/postgres-role.ts","../src/core/postgres-validators.ts","../src/core/ast/table-source.ts","../src/core/entity-kinds.ts","../src/core/postgres-schema.ts"],"sourcesContent":["import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from '@prisma-next/sql-contract/types';\n\nexport interface PostgresRlsEnablementInput {\n /** Name of the table this marker declares RLS-controlled. */\n readonly tableName: string;\n /** Namespace coordinate (schema name). Markers are schema-scoped like policies. */\n readonly namespaceId: string;\n}\n\n/**\n * Postgres contract-IR marker for `@@rls` on a model: the table named here is\n * RLS-controlled (`ENABLE ROW LEVEL SECURITY` is driven by this marker, never\n * by the policy set).\n *\n * This is an authored, serialized Contract-IR entity — it is registered as an\n * entity kind, extends `SqlNode`, and is stored in `contract.json` under\n * `entries.rls[tableName]`. Target-only concept — no SQL-family abstract.\n * Frozen at construction via `freezeNode(this)`. The `kind: 'rls'`\n * discriminant is enumerable so it survives JSON serialization; the literal\n * matches the entries key (one-string rule).\n */\nexport class PostgresRlsEnablement extends SqlNode {\n override readonly kind = 'rls' as const;\n readonly tableName: string;\n readonly namespaceId: string;\n\n constructor(input: PostgresRlsEnablementInput) {\n super();\n this.tableName = input.tableName;\n this.namespaceId = input.namespaceId;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from '@prisma-next/sql-contract/types';\n\nexport type RlsPolicyOperation = 'select' | 'insert' | 'update' | 'delete' | 'all';\n\nexport interface PostgresRlsPolicyInput {\n /** Full wire name: `<prefix>_<8hex>`. Stored as-is; hashing is not this class's job. */\n readonly name: string;\n /** User-supplied prefix (the part before the `_<8hex>` suffix). */\n readonly prefix: string;\n /** Name of the table this policy attaches to, by name within the same schema. */\n readonly tableName: string;\n /** Namespace coordinate (schema name). Policies are schema-scoped. */\n readonly namespaceId: string;\n readonly operation: RlsPolicyOperation;\n /** Sorted role names rendered in `TO <roles>`. Plain strings in this slice. */\n readonly roles: readonly string[];\n /** USING predicate SQL string, if present. */\n readonly using?: string;\n /** WITH CHECK predicate SQL string, if present. */\n readonly withCheck?: string;\n /** `true` = `AS PERMISSIVE`, `false` = `AS RESTRICTIVE`. */\n readonly permissive: boolean;\n}\n\n/**\n * Postgres contract-IR class for a row-level security policy (`CREATE POLICY … ON …`).\n *\n * This is an authored, serialized Contract-IR entity — it is registered as an entity\n * kind, extends `SqlNode`, and is stored in `contract.json`. It is NOT a DiffableNode;\n * the schema-diff tree uses `PostgresPolicySchemaNode` for that role.\n *\n * Target-only concept — no SQL-family abstract. Extends `SqlNode` directly.\n * Frozen at construction via `freezeNode(this)`. The `kind: 'policy'`\n * discriminant is enumerable (overrides SqlNode's non-enumerable `'sql'`) so it\n * survives JSON serialization and enables dispatch. The literal matches the\n * entries key (one-string rule: node.kind === entries key === entity kind).\n */\nexport class PostgresRlsPolicy extends SqlNode {\n override readonly kind = 'policy' as const;\n readonly name: string;\n readonly prefix: string;\n readonly tableName: string;\n readonly namespaceId: string;\n readonly operation: RlsPolicyOperation;\n readonly roles: readonly string[];\n declare readonly using?: string;\n declare readonly withCheck?: string;\n readonly permissive: boolean;\n\n constructor(input: PostgresRlsPolicyInput) {\n super();\n this.name = input.name;\n this.prefix = input.prefix;\n this.tableName = input.tableName;\n this.namespaceId = input.namespaceId;\n this.operation = input.operation;\n this.roles = Object.freeze([...input.roles]);\n if (input.using !== undefined) this.using = input.using;\n if (input.withCheck !== undefined) this.withCheck = input.withCheck;\n this.permissive = input.permissive;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from '@prisma-next/sql-contract/types';\n\n/**\n * Roles are referenced by the contract but never owned — the framework\n * issues no `CREATE`/`DROP ROLE`, so a role's effective governance is always\n * `external`: a missing declared role fails verify, an extra live role is\n * tolerated, and the planner emits zero role DDL. `external` is the only\n * value a role's control can ever carry.\n */\nexport const ROLE_DEFAULT_CONTROL_POLICY = 'external';\n\nexport interface PostgresRoleInput {\n readonly name: string;\n /**\n * Namespace coordinate. Roles are cluster-scoped; pass `UNBOUND_NAMESPACE_ID`\n * from `@prisma-next/framework-components/ir`.\n */\n readonly namespaceId: string;\n /**\n * Defaults to {@link ROLE_DEFAULT_CONTROL_POLICY} when omitted. Roles are\n * referenced but never owned, so `'external'` is the only allowed value.\n */\n readonly control?: 'external';\n}\n\n/**\n * Postgres contract-IR class for a database role (`CREATE ROLE …`).\n *\n * This is an authored, serialized Contract-IR entity — it is registered as an entity\n * kind, extends `SqlNode`, and is stored in `contract.json`. It is NOT a DiffableNode;\n * the schema-diff tree uses `PostgresRoleSchemaNode` for that role.\n *\n * Roles are cluster-scoped, so their namespace coordinate is always\n * `UNBOUND_NAMESPACE_ID`. Target-only concept — no SQL-family abstract.\n * Extends `SqlNode` directly, frozen at construction via `freezeNode(this)`.\n * The `kind: 'role'` discriminant is enumerable so it survives JSON.\n * Matches the entries key (one-string rule).\n *\n * `control` always carries a value (never omitted): it defaults to\n * {@link ROLE_DEFAULT_CONTROL_POLICY} in the constructor, so both a\n * freshly-authored role and one hydrated from an older `contract.json`\n * lacking the field resolve the same way — the control-policy resolver\n * reads it directly off the entity instead of special-casing role issues.\n */\nexport class PostgresRole extends SqlNode {\n override readonly kind = 'role' as const;\n readonly name: string;\n readonly namespaceId: string;\n readonly control: 'external';\n\n constructor(input: PostgresRoleInput) {\n super();\n this.name = input.name;\n this.namespaceId = input.namespaceId;\n this.control = input.control ?? ROLE_DEFAULT_CONTROL_POLICY;\n freezeNode(this);\n }\n}\n","import { type } from 'arktype';\n\nexport const PostgresRoleSchema = type({\n kind: \"'role'\",\n name: 'string',\n namespaceId: 'string',\n 'control?': \"'external'\",\n});\n\nexport const PostgresRlsPolicySchema = type({\n kind: \"'policy'\",\n name: 'string',\n prefix: 'string',\n tableName: 'string',\n namespaceId: 'string',\n operation: \"'select' | 'insert' | 'update' | 'delete' | 'all'\",\n roles: type.string.array().readonly(),\n 'using?': 'string',\n 'withCheck?': 'string',\n permissive: 'boolean',\n});\n\nexport const PostgresRlsEnablementSchema = type({\n kind: \"'rls'\",\n tableName: 'string',\n namespaceId: 'string',\n});\n\nexport const PostgresNativeEnumSchema = type({\n kind: \"'postgres-enum'\",\n typeName: 'string',\n members: type.string.array().readonly(),\n 'control?': \"'managed' | 'tolerated' | 'external' | 'observed'\",\n});\n","import {\n type AnyFromSource,\n type AstRewriter,\n TableSource,\n} from '@prisma-next/sql-relational-core/ast';\n\nexport class PostgresTableSource extends TableSource {\n readonly schema: string | undefined;\n\n constructor(options: {\n readonly name: string;\n readonly schema?: string;\n readonly alias?: string;\n }) {\n super(options.name, options.alias);\n this.schema = options.schema;\n this.freeze();\n }\n\n override rewrite(rewriter: AstRewriter): AnyFromSource {\n return rewriter.tableSource ? rewriter.tableSource(this) : this;\n }\n}\n","import type { EntityKindDescriptor } from '@prisma-next/framework-components/ir';\nimport { PostgresNativeEnum, type PostgresNativeEnumInput } from './postgres-native-enum';\nimport { PostgresRlsEnablement, type PostgresRlsEnablementInput } from './postgres-rls-enablement';\nimport { PostgresRlsPolicy, type PostgresRlsPolicyInput } from './postgres-rls-policy';\nimport { PostgresRole, type PostgresRoleInput } from './postgres-role';\nimport {\n PostgresNativeEnumSchema,\n PostgresRlsEnablementSchema,\n PostgresRlsPolicySchema,\n PostgresRoleSchema,\n} from './postgres-validators';\n\nexport const policyEntityKind: EntityKindDescriptor<PostgresRlsPolicyInput, PostgresRlsPolicy> = {\n kind: 'policy',\n schema: PostgresRlsPolicySchema,\n construct: (input) => new PostgresRlsPolicy(input),\n};\n\nexport const roleEntityKind: EntityKindDescriptor<PostgresRoleInput, PostgresRole> = {\n kind: 'role',\n schema: PostgresRoleSchema,\n construct: (input) => new PostgresRole(input),\n};\n\nexport const rlsEnablementEntityKind: EntityKindDescriptor<\n PostgresRlsEnablementInput,\n PostgresRlsEnablement\n> = {\n kind: 'rls',\n schema: PostgresRlsEnablementSchema,\n construct: (input) => new PostgresRlsEnablement(input),\n};\n\nexport const nativeEnumEntityKind: EntityKindDescriptor<\n PostgresNativeEnumInput,\n PostgresNativeEnum\n> = {\n kind: 'native_enum',\n schema: PostgresNativeEnumSchema,\n construct: (input) => new PostgresNativeEnum(input),\n};\n","import type { Contract } from '@prisma-next/contract/types';\nimport {\n freezeNode,\n hydrateNamespaceEntities,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport { composeSqlEntityKinds } from '@prisma-next/sql-contract/entity-kinds';\nimport {\n SqlNamespaceBase,\n type SqlNamespaceEntries,\n type SqlNamespaceInput,\n type SqlStorage,\n type StorageTable,\n type StorageValueSet,\n} from '@prisma-next/sql-contract/types';\n\nimport { type CfExpr, cfExpr } from '@prisma-next/sql-relational-core/contract-free';\nimport { invariant } from '@prisma-next/utils/assertions';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { PostgresTableSource } from './ast/table-source';\nimport { PG_TEXT_CODEC_ID } from './codec-ids';\nimport {\n nativeEnumEntityKind,\n policyEntityKind,\n rlsEnablementEntityKind,\n roleEntityKind,\n} from './entity-kinds';\nimport { PostgresNativeEnum } from './postgres-native-enum';\nimport type { PostgresRlsEnablement } from './postgres-rls-enablement';\nimport type { PostgresRlsPolicy } from './postgres-rls-policy';\nimport type { PostgresRole } from './postgres-role';\nimport { escapeLiteral } from './sql-utils';\n\nexport type PostgresContract = Contract<SqlStorage> & { readonly target: 'postgres' };\n\nexport type PostgresNamespaceEntries = SqlNamespaceEntries & {\n readonly policy?: Readonly<Record<string, PostgresRlsPolicy>>;\n readonly role?: Readonly<Record<string, PostgresRole>>;\n readonly rls?: Readonly<Record<string, PostgresRlsEnablement>>;\n readonly native_enum?: Readonly<Record<string, PostgresNativeEnum>>;\n};\n\nexport interface PostgresSchemaInput {\n readonly id: string;\n readonly entries: Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n}\n\n/**\n * Postgres target `Namespace` concretion — a Postgres schema (`CREATE\n * SCHEMA …`). Each Postgres `SqlStorage` carries a\n * `namespaces: Record<NamespaceId, PostgresSchema>` map populated by\n * the Postgres PSL interpreter from `namespace { … }` AST buckets.\n *\n * `entries` holds entity-kind maps (`table`, `valueSet`). Qualifier\n * emission is the rendering seam: DDL / SQL emission asks the namespace\n * for its qualifier (`\"<schema>\"`) or for a qualified table name\n * (`\"<schema>\".\"<table>\"`) and consumes the result polymorphically.\n * The unbound singleton below overrides these methods to elide the\n * prefix entirely — call sites stay polymorphic and never branch on\n * `id === UNBOUND_NAMESPACE_ID`.\n */\nexport class PostgresSchema extends SqlNamespaceBase {\n /**\n * Stable singleton reference for the late-bound slot. Materialised\n * lazily below the singleton subclass declaration so the static\n * initialiser sees the subclass before assigning. Consumers always\n * reach for `PostgresSchema.unbound` (or `PostgresUnboundSchema.instance`\n * — same identity).\n */\n static unbound: PostgresUnboundSchema;\n\n declare readonly kind: 'schema';\n readonly id: string;\n readonly entries: PostgresNamespaceEntries;\n\n constructor(input: PostgresSchemaInput) {\n super();\n this.id = input.id;\n\n const dispatched = hydrateNamespaceEntities(\n input.entries,\n composeSqlEntityKinds([\n policyEntityKind,\n roleEntityKind,\n rlsEnablementEntityKind,\n nativeEnumEntityKind,\n ]),\n 'carry',\n );\n\n // A native enum keys under its PHYSICAL type name in storage `entries`\n // (ADR 221 coordinate `entityName`). The family/authoring layer keys every\n // block by its author handle, so re-key the `native_enum` slot by each\n // entity's `typeName` here — target-local Postgres code that already knows\n // this entity kind. This runs at both authoring and hydration; a serialized\n // contract's key already equals the `typeName`, so the re-key is idempotent.\n const nativeEnumSlot = dispatched['native_enum'];\n if (nativeEnumSlot !== undefined) {\n const rekeyed: Record<string, unknown> = {};\n for (const [handle, entity] of Object.entries(nativeEnumSlot)) {\n const physicalName = PostgresNativeEnum.is(entity) ? entity.typeName : handle;\n invariant(\n !Object.hasOwn(rekeyed, physicalName),\n `PostgresSchema \"${input.id}\": two native_enum entities resolve to the same physical type name \"${physicalName}\". Give them distinct @@map type names.`,\n );\n rekeyed[physicalName] = entity;\n }\n dispatched['native_enum'] = Object.freeze(rekeyed);\n }\n\n // Drop an empty valueSet so presence signals non-emptiness.\n const valueSetRaw = dispatched['valueSet'];\n const withPresence =\n valueSetRaw !== undefined && Object.keys(valueSetRaw).length === 0\n ? { ...dispatched, valueSet: undefined }\n : dispatched;\n\n const entriesInput: Record<string, Readonly<Record<string, unknown>> | undefined> = {\n ...withPresence,\n };\n\n this.entries = Object.freeze(\n blindCast<\n PostgresNamespaceEntries,\n 'composeSqlEntityKinds([policyEntityKind, roleEntityKind, rlsEnablementEntityKind, nativeEnumEntityKind]) supplies table→StorageTable, valueSet→StorageValueSet, policy→PostgresRlsPolicy, role→PostgresRole, rls→PostgresRlsEnablement, native_enum→PostgresNativeEnum descriptors'\n >(entriesInput),\n );\n Object.defineProperty(this, 'kind', {\n value: 'schema',\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n\n get table(): Readonly<Record<string, StorageTable>> {\n return this.entries.table ?? Object.freeze({});\n }\n\n get valueSet(): Readonly<Record<string, StorageValueSet>> | undefined {\n return this.entries.valueSet;\n }\n\n get policy(): Readonly<Record<string, PostgresRlsPolicy>> {\n return this.entries.policy ?? Object.freeze({});\n }\n\n get role(): Readonly<Record<string, PostgresRole>> {\n return this.entries.role ?? Object.freeze({});\n }\n\n get rls(): Readonly<Record<string, PostgresRlsEnablement>> {\n return this.entries.rls ?? Object.freeze({});\n }\n\n /**\n * The bare schema qualifier as it would appear in a rendered SQL\n * fragment (already quoted). The unbound-schema singleton overrides\n * this to return `''`.\n */\n qualifier(): string {\n return `\"${this.id}\"`;\n }\n\n /**\n * Qualify a table name with the schema prefix\n * (`\"<schema>\".\"<table>\"`). The unbound-schema singleton overrides\n * this to emit just `\"<table>\"` so the resolved DDL is unqualified\n * and `search_path` decides where the object lands at runtime.\n */\n qualifyTable(tableName: string): string {\n return `\"${this.id}\".\"${tableName}\"`;\n }\n\n /**\n * Render a SQL string-literal containing the qualified-name form\n * suitable for `to_regclass(...)` arguments (e.g. `'\"public\".\"user\"'`).\n * The unbound singleton overrides this to elide the schema prefix\n * (`'\"user\"'`) so `search_path` resolves the object at runtime.\n */\n regclassLiteral(name: string): string {\n return `'${escapeLiteral(this.qualifyTable(name))}'`;\n }\n\n /**\n * Render a SQL expression that evaluates to this namespace's schema\n * name at runtime, ready to drop into a `WHERE table_schema = …` /\n * `WHERE n.nspname = …` clause. Named schemas emit a quoted SQL\n * literal (`'public'`); the unbound singleton overrides this to emit\n * `current_schema()` so catalog queries match whichever schema the\n * connection's `search_path` resolved at runtime.\n */\n schemaSqlExpression(): string {\n return `'${escapeLiteral(this.id)}'`;\n }\n\n /**\n * Typed-AST counterpart of {@link schemaSqlExpression}: the expression a\n * builder-built catalog check compares `n.nspname` / `table_schema`\n * against. Named schemas bind the schema name as a text parameter; the\n * unbound singleton overrides this to the opaque `current_schema()`\n * expression so the live connection's `search_path` decides at runtime.\n */\n schemaFilterExpression(): CfExpr {\n return cfExpr.param(this.id, PG_TEXT_CODEC_ID);\n }\n\n /**\n * Typed-AST counterpart of {@link qualifyTable}: the FROM source a\n * builder-built check uses to address a user table in this namespace.\n * Named schemas qualify (`\"schema\".\"table\"`); the unbound singleton\n * overrides this to leave the table unqualified so `search_path`\n * resolves it at runtime.\n */\n tableSource(tableName: string, alias?: string): PostgresTableSource {\n return new PostgresTableSource({\n name: tableName,\n schema: this.id,\n ...ifDefined('alias', alias),\n });\n }\n\n /**\n * The bare schema name a DDL planner should target when emitting\n * statements that need to identify this namespace in the live\n * database (e.g. `CREATE TABLE \"<ddlSchemaName>\".\"<table>\" …`,\n * catalog filters, planner conflict lookups). Named schemas resolve\n * to their own id. The `PostgresUnboundSchema` singleton inherits\n * this and returns `UNBOUND_NAMESPACE_ID` — callers that dispatch\n * through `qualifyTableName` route through the polymorphic\n * `PostgresUnboundSchema` overrides and produce unqualified\n * (search-path-resolved) output automatically.\n */\n ddlSchemaName(_storage: SqlStorage): string {\n return this.id;\n }\n}\n\n/**\n * Singleton subclass for the reserved sentinel namespace id\n * (`UNBOUND_NAMESPACE_ID`) — the late-bound Postgres slot whose binding\n * the connection's `search_path` resolves at runtime. Overrides\n * qualifier emission to elide the schema prefix; call sites that consume\n * `qualifier()` / `qualifyTable()` get unqualified output without\n * branching on the namespace id.\n *\n * This is the target-side materialization of \"the framework provides\n * affordances; targets implement specifics\": the framework names the\n * sentinel; Postgres decides what late-bound means here (the table\n * name, naked — the schema is supplied by the live connection's\n * `search_path`).\n *\n * `ddlSchemaName` is inherited from `PostgresSchema` and returns\n * `UNBOUND_NAMESPACE_ID`. Downstream helpers such as `qualifyTableName`\n * route through the polymorphic factory and produce unqualified output\n * automatically.\n */\nexport class PostgresUnboundSchema extends PostgresSchema {\n static readonly instance: PostgresUnboundSchema = new PostgresUnboundSchema();\n\n constructor(input?: PostgresSchemaInput) {\n super(input ?? { id: UNBOUND_NAMESPACE_ID, entries: { table: {} } });\n }\n\n override qualifier(): string {\n return '';\n }\n\n override qualifyTable(tableName: string): string {\n return `\"${tableName}\"`;\n }\n\n override schemaSqlExpression(): string {\n return 'current_schema()';\n }\n\n override schemaFilterExpression(): CfExpr {\n return cfExpr.raw('current_schema()', { codecId: PG_TEXT_CODEC_ID, nullable: false });\n }\n\n override tableSource(tableName: string, alias?: string): PostgresTableSource {\n return new PostgresTableSource({\n name: tableName,\n ...ifDefined('alias', alias),\n });\n }\n}\n\nPostgresSchema.unbound = PostgresUnboundSchema.instance;\n\n/**\n * Narrow an arbitrary namespace (or `undefined`) to `PostgresSchema`\n * so callers can dispatch to the polymorphic emission methods without\n * branching at the call site. Uses the structural `kind` discriminator\n * (`'schema'`) rather than `instanceof` so the check survives realm /\n * bundle / hot-reload boundaries — matching the rest of the IR's\n * narrowing convention. `PostgresUnboundSchema` passes through because\n * it inherits the same `kind: 'schema'` from `PostgresSchema`.\n */\nexport function isPostgresSchema(ns: unknown): ns is PostgresSchema {\n return (ns as { kind?: unknown } | null | undefined)?.kind === 'schema';\n}\n\n/**\n * Target-supplied `Namespace` factory the Postgres target plumbs\n * through `defineContract({ createNamespace })` and the SQL PSL\n * interpreter. Returns the unbound singleton for the framework\n * sentinel and a fresh `PostgresSchema` for any other coordinate.\n *\n * The factory has no per-call state — every named id deterministically\n * maps to a distinct schema instance — so callers can pass it through\n * by reference and trust the resulting `SqlStorage.namespaces` map to\n * be value-stable for a given input set. Native-enum column type names are\n * schema-qualified earlier, at column construction, via the target's\n * `authoring.qualifyColumnType` hook (`postgresQualifyColumnType`), so this\n * factory just materialises the namespace from already-qualified entries.\n */\nexport function postgresCreateNamespace(input: SqlNamespaceInput): PostgresSchema {\n const schemaInput: PostgresSchemaInput = {\n id: input.id,\n entries: {\n ...input.entries,\n table: input.entries['table'] ?? {},\n },\n };\n if (input.id === UNBOUND_NAMESPACE_ID) {\n return new PostgresUnboundSchema(schemaInput);\n }\n return new PostgresSchema(schemaInput);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,wBAAb,cAA2C,QAAQ;CACjD,OAAyB;CACzB;CACA;CAEA,YAAY,OAAmC;EAC7C,MAAM;EACN,KAAK,YAAY,MAAM;EACvB,KAAK,cAAc,MAAM;EACzB,WAAW,IAAI;CACjB;AACF;;;;;;;;;;;;;;;;ACKA,IAAa,oBAAb,cAAuC,QAAQ;CAC7C,OAAyB;CACzB;CACA;CACA;CACA;CACA;CACA;CAGA;CAEA,YAAY,OAA+B;EACzC,MAAM;EACN,KAAK,OAAO,MAAM;EAClB,KAAK,SAAS,MAAM;EACpB,KAAK,YAAY,MAAM;EACvB,KAAK,cAAc,MAAM;EACzB,KAAK,YAAY,MAAM;EACvB,KAAK,QAAQ,OAAO,OAAO,CAAC,GAAG,MAAM,KAAK,CAAC;EAC3C,IAAI,MAAM,UAAU,KAAA,GAAW,KAAK,QAAQ,MAAM;EAClD,IAAI,MAAM,cAAc,KAAA,GAAW,KAAK,YAAY,MAAM;EAC1D,KAAK,aAAa,MAAM;EACxB,WAAW,IAAI;CACjB;AACF;;;;;;;;;;ACrDA,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;;;AAmC3C,IAAa,eAAb,cAAkC,QAAQ;CACxC,OAAyB;CACzB;CACA;CACA;CAEA,YAAY,OAA0B;EACpC,MAAM;EACN,KAAK,OAAO,MAAM;EAClB,KAAK,cAAc,MAAM;EACzB,KAAK,UAAU,MAAM,WAAA;EACrB,WAAW,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ACpC;CACF;CACA,IAAI,MAAM,OAAO,sBACf,OAAO,IAAI,sBAAsB,WAAW;CAE9C,OAAO,IAAI,eAAe,WAAW;AACvC"}
1
+ {"version":3,"file":"postgres-schema-CTplQZDK.mjs","names":[],"sources":["../src/core/postgres-rls-enablement.ts","../src/core/postgres-rls-policy.ts","../src/core/postgres-role.ts","../src/core/postgres-validators.ts","../src/core/ast/table-source.ts","../src/core/entity-kinds.ts","../src/core/postgres-schema.ts"],"sourcesContent":["import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from '@prisma-next/sql-contract/types';\n\nexport interface PostgresRlsEnablementInput {\n /** Name of the table this marker declares RLS-controlled. */\n readonly tableName: string;\n /** Namespace coordinate (schema name). Markers are schema-scoped like policies. */\n readonly namespaceId: string;\n}\n\n/**\n * Postgres contract-IR marker for `@@rls` on a model: the table named here is\n * RLS-controlled (`ENABLE ROW LEVEL SECURITY` is driven by this marker, never\n * by the policy set).\n *\n * This is an authored, serialized Contract-IR entity — it is registered as an\n * entity kind, extends `SqlNode`, and is stored in `contract.json` under\n * `entries.rls[tableName]`. Target-only concept — no SQL-family abstract.\n * Frozen at construction via `freezeNode(this)`. The `kind: 'rls'`\n * discriminant is enumerable so it survives JSON serialization; the literal\n * matches the entries key (one-string rule).\n */\nexport class PostgresRlsEnablement extends SqlNode {\n override readonly kind = 'rls' as const;\n readonly tableName: string;\n readonly namespaceId: string;\n\n constructor(input: PostgresRlsEnablementInput) {\n super();\n this.tableName = input.tableName;\n this.namespaceId = input.namespaceId;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from '@prisma-next/sql-contract/types';\n\nexport type RlsPolicyOperation = 'select' | 'insert' | 'update' | 'delete' | 'all';\n\nexport interface PostgresRlsPolicyInput {\n /** Full wire name: `<prefix>_<8hex>`. Stored as-is; hashing is not this class's job. */\n readonly name: string;\n /** User-supplied prefix (the part before the `_<8hex>` suffix). */\n readonly prefix: string;\n /** Name of the table this policy attaches to, by name within the same schema. */\n readonly tableName: string;\n /** Namespace coordinate (schema name). Policies are schema-scoped. */\n readonly namespaceId: string;\n readonly operation: RlsPolicyOperation;\n /** Sorted role names rendered in `TO <roles>`. Plain strings in this slice. */\n readonly roles: readonly string[];\n /** USING predicate SQL string, if present. */\n readonly using?: string;\n /** WITH CHECK predicate SQL string, if present. */\n readonly withCheck?: string;\n /** `true` = `AS PERMISSIVE`, `false` = `AS RESTRICTIVE`. */\n readonly permissive: boolean;\n}\n\n/**\n * Postgres contract-IR class for a row-level security policy (`CREATE POLICY … ON …`).\n *\n * This is an authored, serialized Contract-IR entity — it is registered as an entity\n * kind, extends `SqlNode`, and is stored in `contract.json`. It is NOT a DiffableNode;\n * the schema-diff tree uses `PostgresPolicySchemaNode` for that role.\n *\n * Target-only concept — no SQL-family abstract. Extends `SqlNode` directly.\n * Frozen at construction via `freezeNode(this)`. The `kind: 'policy'`\n * discriminant is enumerable (overrides SqlNode's non-enumerable `'sql'`) so it\n * survives JSON serialization and enables dispatch. The literal matches the\n * entries key (one-string rule: node.kind === entries key === entity kind).\n */\nexport class PostgresRlsPolicy extends SqlNode {\n override readonly kind = 'policy' as const;\n readonly name: string;\n readonly prefix: string;\n readonly tableName: string;\n readonly namespaceId: string;\n readonly operation: RlsPolicyOperation;\n readonly roles: readonly string[];\n declare readonly using?: string;\n declare readonly withCheck?: string;\n readonly permissive: boolean;\n\n constructor(input: PostgresRlsPolicyInput) {\n super();\n this.name = input.name;\n this.prefix = input.prefix;\n this.tableName = input.tableName;\n this.namespaceId = input.namespaceId;\n this.operation = input.operation;\n this.roles = Object.freeze([...input.roles]);\n if (input.using !== undefined) this.using = input.using;\n if (input.withCheck !== undefined) this.withCheck = input.withCheck;\n this.permissive = input.permissive;\n freezeNode(this);\n }\n}\n","import { freezeNode } from '@prisma-next/framework-components/ir';\nimport { SqlNode } from '@prisma-next/sql-contract/types';\n\n/**\n * Roles are referenced by the contract but never owned — the framework\n * issues no `CREATE`/`DROP ROLE`, so a role's effective governance is always\n * `external`: a missing declared role fails verify, an extra live role is\n * tolerated, and the planner emits zero role DDL. `external` is the only\n * value a role's control can ever carry.\n */\nexport const ROLE_DEFAULT_CONTROL_POLICY = 'external';\n\nexport interface PostgresRoleInput {\n readonly name: string;\n /**\n * Namespace coordinate. Roles are cluster-scoped; pass `UNBOUND_NAMESPACE_ID`\n * from `@prisma-next/framework-components/ir`.\n */\n readonly namespaceId: string;\n /**\n * Defaults to {@link ROLE_DEFAULT_CONTROL_POLICY} when omitted. Roles are\n * referenced but never owned, so `'external'` is the only allowed value.\n */\n readonly control?: 'external';\n}\n\n/**\n * Postgres contract-IR class for a database role (`CREATE ROLE …`).\n *\n * This is an authored, serialized Contract-IR entity — it is registered as an entity\n * kind, extends `SqlNode`, and is stored in `contract.json`. It is NOT a DiffableNode;\n * the schema-diff tree uses `PostgresRoleSchemaNode` for that role.\n *\n * Roles are cluster-scoped, so their namespace coordinate is always\n * `UNBOUND_NAMESPACE_ID`. Target-only concept — no SQL-family abstract.\n * Extends `SqlNode` directly, frozen at construction via `freezeNode(this)`.\n * The `kind: 'role'` discriminant is enumerable so it survives JSON.\n * Matches the entries key (one-string rule).\n *\n * `control` always carries a value (never omitted): it defaults to\n * {@link ROLE_DEFAULT_CONTROL_POLICY} in the constructor, so both a\n * freshly-authored role and one hydrated from an older `contract.json`\n * lacking the field resolve the same way — the control-policy resolver\n * reads it directly off the entity instead of special-casing role issues.\n */\nexport class PostgresRole extends SqlNode {\n override readonly kind = 'role' as const;\n readonly name: string;\n readonly namespaceId: string;\n readonly control: 'external';\n\n constructor(input: PostgresRoleInput) {\n super();\n this.name = input.name;\n this.namespaceId = input.namespaceId;\n this.control = input.control ?? ROLE_DEFAULT_CONTROL_POLICY;\n freezeNode(this);\n }\n}\n","import { type } from 'arktype';\n\nexport const PostgresRoleSchema = type({\n kind: \"'role'\",\n name: 'string',\n namespaceId: 'string',\n 'control?': \"'external'\",\n});\n\nexport const PostgresRlsPolicySchema = type({\n kind: \"'policy'\",\n name: 'string',\n prefix: 'string',\n tableName: 'string',\n namespaceId: 'string',\n operation: \"'select' | 'insert' | 'update' | 'delete' | 'all'\",\n roles: type.string.array().readonly(),\n 'using?': 'string',\n 'withCheck?': 'string',\n permissive: 'boolean',\n});\n\nexport const PostgresRlsEnablementSchema = type({\n kind: \"'rls'\",\n tableName: 'string',\n namespaceId: 'string',\n});\n\nexport const PostgresNativeEnumSchema = type({\n kind: \"'postgres-enum'\",\n typeName: 'string',\n members: type.string.array().readonly(),\n 'control?': \"'managed' | 'tolerated' | 'external' | 'observed'\",\n});\n","import {\n type AnyFromSource,\n type AstRewriter,\n TableSource,\n} from '@prisma-next/sql-relational-core/ast';\n\nexport class PostgresTableSource extends TableSource {\n readonly schema: string | undefined;\n\n constructor(options: {\n readonly name: string;\n readonly schema?: string;\n readonly alias?: string;\n }) {\n super(options.name, options.alias);\n this.schema = options.schema;\n this.freeze();\n }\n\n override rewrite(rewriter: AstRewriter): AnyFromSource {\n return rewriter.tableSource ? rewriter.tableSource(this) : this;\n }\n}\n","import type { EntityKindDescriptor } from '@prisma-next/framework-components/ir';\nimport { PostgresNativeEnum, type PostgresNativeEnumInput } from './postgres-native-enum';\nimport { PostgresRlsEnablement, type PostgresRlsEnablementInput } from './postgres-rls-enablement';\nimport { PostgresRlsPolicy, type PostgresRlsPolicyInput } from './postgres-rls-policy';\nimport { PostgresRole, type PostgresRoleInput } from './postgres-role';\nimport {\n PostgresNativeEnumSchema,\n PostgresRlsEnablementSchema,\n PostgresRlsPolicySchema,\n PostgresRoleSchema,\n} from './postgres-validators';\n\nexport const policyEntityKind: EntityKindDescriptor<PostgresRlsPolicyInput, PostgresRlsPolicy> = {\n kind: 'policy',\n schema: PostgresRlsPolicySchema,\n construct: (input) => new PostgresRlsPolicy(input),\n};\n\nexport const roleEntityKind: EntityKindDescriptor<PostgresRoleInput, PostgresRole> = {\n kind: 'role',\n schema: PostgresRoleSchema,\n construct: (input) => new PostgresRole(input),\n};\n\nexport const rlsEnablementEntityKind: EntityKindDescriptor<\n PostgresRlsEnablementInput,\n PostgresRlsEnablement\n> = {\n kind: 'rls',\n schema: PostgresRlsEnablementSchema,\n construct: (input) => new PostgresRlsEnablement(input),\n};\n\nexport const nativeEnumEntityKind: EntityKindDescriptor<\n PostgresNativeEnumInput,\n PostgresNativeEnum\n> = {\n kind: 'native_enum',\n schema: PostgresNativeEnumSchema,\n construct: (input) => new PostgresNativeEnum(input),\n};\n","import type { Contract } from '@prisma-next/contract/types';\nimport {\n freezeNode,\n hydrateNamespaceEntities,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport { composeSqlEntityKinds } from '@prisma-next/sql-contract/entity-kinds';\nimport {\n SqlNamespaceBase,\n type SqlNamespaceEntries,\n type SqlNamespaceInput,\n type SqlStorage,\n type StorageTable,\n type StorageValueSet,\n} from '@prisma-next/sql-contract/types';\n\nimport { type CfExpr, cfExpr } from '@prisma-next/sql-relational-core/contract-free';\nimport { invariant } from '@prisma-next/utils/assertions';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { PostgresTableSource } from './ast/table-source';\nimport { PG_TEXT_CODEC_ID } from './codec-ids';\nimport {\n nativeEnumEntityKind,\n policyEntityKind,\n rlsEnablementEntityKind,\n roleEntityKind,\n} from './entity-kinds';\nimport { PostgresNativeEnum } from './postgres-native-enum';\nimport type { PostgresRlsEnablement } from './postgres-rls-enablement';\nimport type { PostgresRlsPolicy } from './postgres-rls-policy';\nimport type { PostgresRole } from './postgres-role';\nimport { escapeLiteral } from './sql-utils';\n\nexport type PostgresContract = Contract<SqlStorage> & { readonly target: 'postgres' };\n\nexport type PostgresNamespaceEntries = SqlNamespaceEntries & {\n readonly policy?: Readonly<Record<string, PostgresRlsPolicy>>;\n readonly role?: Readonly<Record<string, PostgresRole>>;\n readonly rls?: Readonly<Record<string, PostgresRlsEnablement>>;\n readonly native_enum?: Readonly<Record<string, PostgresNativeEnum>>;\n};\n\nexport interface PostgresSchemaInput {\n readonly id: string;\n readonly entries: Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n}\n\n/**\n * Postgres target `Namespace` concretion — a Postgres schema (`CREATE\n * SCHEMA …`). Each Postgres `SqlStorage` carries a\n * `namespaces: Record<NamespaceId, PostgresSchema>` map populated by\n * the Postgres PSL interpreter from `namespace { … }` AST buckets.\n *\n * `entries` holds entity-kind maps (`table`, `valueSet`). Qualifier\n * emission is the rendering seam: DDL / SQL emission asks the namespace\n * for its qualifier (`\"<schema>\"`) or for a qualified table name\n * (`\"<schema>\".\"<table>\"`) and consumes the result polymorphically.\n * The unbound singleton below overrides these methods to elide the\n * prefix entirely — call sites stay polymorphic and never branch on\n * `id === UNBOUND_NAMESPACE_ID`.\n */\nexport class PostgresSchema extends SqlNamespaceBase {\n /**\n * Stable singleton reference for the late-bound slot. Materialised\n * lazily below the singleton subclass declaration so the static\n * initialiser sees the subclass before assigning. Consumers always\n * reach for `PostgresSchema.unbound` (or `PostgresUnboundSchema.instance`\n * — same identity).\n */\n static unbound: PostgresUnboundSchema;\n\n declare readonly kind: 'schema';\n readonly id: string;\n readonly entries: PostgresNamespaceEntries;\n\n constructor(input: PostgresSchemaInput) {\n super();\n this.id = input.id;\n\n const dispatched = hydrateNamespaceEntities(\n input.entries,\n composeSqlEntityKinds([\n policyEntityKind,\n roleEntityKind,\n rlsEnablementEntityKind,\n nativeEnumEntityKind,\n ]),\n 'carry',\n );\n\n // A native enum keys under its PHYSICAL type name in storage `entries`\n // (ADR 221 coordinate `entityName`). The family/authoring layer keys every\n // block by its author handle, so re-key the `native_enum` slot by each\n // entity's `typeName` here — target-local Postgres code that already knows\n // this entity kind. This runs at both authoring and hydration; a serialized\n // contract's key already equals the `typeName`, so the re-key is idempotent.\n const nativeEnumSlot = dispatched['native_enum'];\n if (nativeEnumSlot !== undefined) {\n const rekeyed: Record<string, unknown> = {};\n for (const [handle, entity] of Object.entries(nativeEnumSlot)) {\n const physicalName = PostgresNativeEnum.is(entity) ? entity.typeName : handle;\n invariant(\n !Object.hasOwn(rekeyed, physicalName),\n `PostgresSchema \"${input.id}\": two native_enum entities resolve to the same physical type name \"${physicalName}\". Give them distinct @@map type names.`,\n );\n rekeyed[physicalName] = entity;\n }\n dispatched['native_enum'] = Object.freeze(rekeyed);\n }\n\n // Drop an empty valueSet so presence signals non-emptiness.\n const valueSetRaw = dispatched['valueSet'];\n const withPresence =\n valueSetRaw !== undefined && Object.keys(valueSetRaw).length === 0\n ? { ...dispatched, valueSet: undefined }\n : dispatched;\n\n const entriesInput: Record<string, Readonly<Record<string, unknown>> | undefined> = {\n ...withPresence,\n };\n\n this.entries = Object.freeze(\n blindCast<\n PostgresNamespaceEntries,\n 'composeSqlEntityKinds([policyEntityKind, roleEntityKind, rlsEnablementEntityKind, nativeEnumEntityKind]) supplies table→StorageTable, valueSet→StorageValueSet, policy→PostgresRlsPolicy, role→PostgresRole, rls→PostgresRlsEnablement, native_enum→PostgresNativeEnum descriptors'\n >(entriesInput),\n );\n Object.defineProperty(this, 'kind', {\n value: 'schema',\n writable: false,\n enumerable: false,\n configurable: true,\n });\n freezeNode(this);\n }\n\n get table(): Readonly<Record<string, StorageTable>> {\n return this.entries.table ?? Object.freeze({});\n }\n\n get valueSet(): Readonly<Record<string, StorageValueSet>> | undefined {\n return this.entries.valueSet;\n }\n\n get policy(): Readonly<Record<string, PostgresRlsPolicy>> {\n return this.entries.policy ?? Object.freeze({});\n }\n\n get role(): Readonly<Record<string, PostgresRole>> {\n return this.entries.role ?? Object.freeze({});\n }\n\n get rls(): Readonly<Record<string, PostgresRlsEnablement>> {\n return this.entries.rls ?? Object.freeze({});\n }\n\n /**\n * The bare schema qualifier as it would appear in a rendered SQL\n * fragment (already quoted). The unbound-schema singleton overrides\n * this to return `''`.\n */\n qualifier(): string {\n return `\"${this.id}\"`;\n }\n\n /**\n * Qualify a table name with the schema prefix\n * (`\"<schema>\".\"<table>\"`). The unbound-schema singleton overrides\n * this to emit just `\"<table>\"` so the resolved DDL is unqualified\n * and `search_path` decides where the object lands at runtime.\n */\n qualifyTable(tableName: string): string {\n return `\"${this.id}\".\"${tableName}\"`;\n }\n\n /**\n * Render a SQL string-literal containing the qualified-name form\n * suitable for `to_regclass(...)` arguments (e.g. `'\"public\".\"user\"'`).\n * The unbound singleton overrides this to elide the schema prefix\n * (`'\"user\"'`) so `search_path` resolves the object at runtime.\n */\n regclassLiteral(name: string): string {\n return `'${escapeLiteral(this.qualifyTable(name))}'`;\n }\n\n /**\n * Render a SQL expression that evaluates to this namespace's schema\n * name at runtime, ready to drop into a `WHERE table_schema = …` /\n * `WHERE n.nspname = …` clause. Named schemas emit a quoted SQL\n * literal (`'public'`); the unbound singleton overrides this to emit\n * `current_schema()` so catalog queries match whichever schema the\n * connection's `search_path` resolved at runtime.\n */\n schemaSqlExpression(): string {\n return `'${escapeLiteral(this.id)}'`;\n }\n\n /**\n * Typed-AST counterpart of {@link schemaSqlExpression}: the expression a\n * builder-built catalog check compares `n.nspname` / `table_schema`\n * against. Named schemas bind the schema name as a text parameter; the\n * unbound singleton overrides this to the opaque `current_schema()`\n * expression so the live connection's `search_path` decides at runtime.\n */\n schemaFilterExpression(): CfExpr {\n return cfExpr.param(this.id, PG_TEXT_CODEC_ID);\n }\n\n /**\n * Typed-AST counterpart of {@link qualifyTable}: the FROM source a\n * builder-built check uses to address a user table in this namespace.\n * Named schemas qualify (`\"schema\".\"table\"`); the unbound singleton\n * overrides this to leave the table unqualified so `search_path`\n * resolves it at runtime.\n */\n tableSource(tableName: string, alias?: string): PostgresTableSource {\n return new PostgresTableSource({\n name: tableName,\n schema: this.id,\n ...ifDefined('alias', alias),\n });\n }\n\n /**\n * The bare schema name a DDL planner should target when emitting\n * statements that need to identify this namespace in the live\n * database (e.g. `CREATE TABLE \"<ddlSchemaName>\".\"<table>\" …`,\n * catalog filters, planner conflict lookups). Named schemas resolve\n * to their own id. The `PostgresUnboundSchema` singleton inherits\n * this and returns `UNBOUND_NAMESPACE_ID` — callers that dispatch\n * through `qualifyTableName` route through the polymorphic\n * `PostgresUnboundSchema` overrides and produce unqualified\n * (search-path-resolved) output automatically.\n */\n ddlSchemaName(_storage: SqlStorage): string {\n return this.id;\n }\n}\n\n/**\n * Singleton subclass for the reserved sentinel namespace id\n * (`UNBOUND_NAMESPACE_ID`) — the late-bound Postgres slot whose binding\n * the connection's `search_path` resolves at runtime. Overrides\n * qualifier emission to elide the schema prefix; call sites that consume\n * `qualifier()` / `qualifyTable()` get unqualified output without\n * branching on the namespace id.\n *\n * This is the target-side materialization of \"the framework provides\n * affordances; targets implement specifics\": the framework names the\n * sentinel; Postgres decides what late-bound means here (the table\n * name, naked — the schema is supplied by the live connection's\n * `search_path`).\n *\n * `ddlSchemaName` is inherited from `PostgresSchema` and returns\n * `UNBOUND_NAMESPACE_ID`. Downstream helpers such as `qualifyTableName`\n * route through the polymorphic factory and produce unqualified output\n * automatically.\n */\nexport class PostgresUnboundSchema extends PostgresSchema {\n static readonly instance: PostgresUnboundSchema = new PostgresUnboundSchema();\n\n constructor(input?: PostgresSchemaInput) {\n super(input ?? { id: UNBOUND_NAMESPACE_ID, entries: { table: {} } });\n }\n\n override qualifier(): string {\n return '';\n }\n\n override qualifyTable(tableName: string): string {\n return `\"${tableName}\"`;\n }\n\n override schemaSqlExpression(): string {\n return 'current_schema()';\n }\n\n override schemaFilterExpression(): CfExpr {\n return cfExpr.raw('current_schema()', { codecId: PG_TEXT_CODEC_ID, nullable: false });\n }\n\n override tableSource(tableName: string, alias?: string): PostgresTableSource {\n return new PostgresTableSource({\n name: tableName,\n ...ifDefined('alias', alias),\n });\n }\n}\n\nPostgresSchema.unbound = PostgresUnboundSchema.instance;\n\n/**\n * Narrow an arbitrary namespace (or `undefined`) to `PostgresSchema`\n * so callers can dispatch to the polymorphic emission methods without\n * branching at the call site. Uses the structural `kind` discriminator\n * (`'schema'`) rather than `instanceof` so the check survives realm /\n * bundle / hot-reload boundaries — matching the rest of the IR's\n * narrowing convention. `PostgresUnboundSchema` passes through because\n * it inherits the same `kind: 'schema'` from `PostgresSchema`.\n */\nexport function isPostgresSchema(ns: unknown): ns is PostgresSchema {\n return (ns as { kind?: unknown } | null | undefined)?.kind === 'schema';\n}\n\n/**\n * Target-supplied `Namespace` factory the Postgres target plumbs\n * through `defineContract({ createNamespace })` and the SQL PSL\n * interpreter. Returns the unbound singleton for the framework\n * sentinel and a fresh `PostgresSchema` for any other coordinate.\n *\n * The factory has no per-call state — every named id deterministically\n * maps to a distinct schema instance — so callers can pass it through\n * by reference and trust the resulting `SqlStorage.namespaces` map to\n * be value-stable for a given input set. Native-enum column type names are\n * schema-qualified earlier, at column construction, via the target's\n * `authoring.qualifyColumnType` hook (`postgresQualifyColumnType`), so this\n * factory just materialises the namespace from already-qualified entries.\n */\nexport function postgresCreateNamespace(input: SqlNamespaceInput): PostgresSchema {\n const schemaInput: PostgresSchemaInput = {\n id: input.id,\n entries: {\n ...input.entries,\n table: input.entries['table'] ?? {},\n },\n };\n if (input.id === UNBOUND_NAMESPACE_ID) {\n return new PostgresUnboundSchema(schemaInput);\n }\n return new PostgresSchema(schemaInput);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,wBAAb,cAA2C,QAAQ;CACjD,OAAyB;CACzB;CACA;CAEA,YAAY,OAAmC;EAC7C,MAAM;EACN,KAAK,YAAY,MAAM;EACvB,KAAK,cAAc,MAAM;EACzB,WAAW,IAAI;CACjB;AACF;;;;;;;;;;;;;;;;ACKA,IAAa,oBAAb,cAAuC,QAAQ;CAC7C,OAAyB;CACzB;CACA;CACA;CACA;CACA;CACA;CAGA;CAEA,YAAY,OAA+B;EACzC,MAAM;EACN,KAAK,OAAO,MAAM;EAClB,KAAK,SAAS,MAAM;EACpB,KAAK,YAAY,MAAM;EACvB,KAAK,cAAc,MAAM;EACzB,KAAK,YAAY,MAAM;EACvB,KAAK,QAAQ,OAAO,OAAO,CAAC,GAAG,MAAM,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oB;GAAE,SAAS;GAAkB,UAAU;EAAM,CAAC;CACtF;CAEA,YAAqB,WAAmB,OAAqC;EAC3E,OAAO,IAAI,oBAAoB;GAC7B,MAAM;GACN,GAAG,UAAU,SAAS,KAAK;EAC7B,CAAC;CACH;AACF;AAEA,eAAe,UAAU,sBAAsB;;;;;;;;;;AAW/C,SAAgB,iBAAiB,IAAmC;CAClE,OAAQ,IAA8C,SAAS;AACjE;;;;;;;;;;;;;;;AAgBA,SAAgB,wBAAwB,OAA0C;CAChF,MAAM,cAAmC;EACvC,IAAI,MAAM;EACV,SAAS;GACP,GAAG,MAAM;GACT,OAAO,MAAM,QAAQ,YAAY,CAAC;EACpC;CACF;CACA,IAAI,MAAM,OAAO,sBACf,OAAO,IAAI,sBAAsB,WAAW;CAE9C,OAAO,IAAI,eAAe,WAAW;AACvC"}
@@ -1,3 +1,4 @@
1
+ import { n as postgresError } from "./errors-DBSNx7EJ.mjs";
1
2
  import { blindCast } from "@prisma-next/utils/casts";
2
3
  import { isThenable } from "@prisma-next/utils/promise";
3
4
  //#region src/core/migrations/render-ops.ts
@@ -10,7 +11,11 @@ import { isThenable } from "@prisma-next/utils/promise";
10
11
  */
11
12
  function assertPostgresOp(op, callFactoryName) {
12
13
  const targetId = blindCast(op).target?.id;
13
- if (targetId !== "postgres") throw new Error(`renderOps: expected postgres op but got target.id="${String(targetId)}" for op.id="${op.id}" (factoryName="${callFactoryName}"). An OpFactoryCall produced an op for a different target on the postgres planner path; check the call's target binding.`);
14
+ if (targetId !== "postgres") throw postgresError("MIGRATION.TARGET_MISMATCH", `renderOps: expected postgres op but got target.id="${String(targetId)}" for op.id="${op.id}" (factoryName="${callFactoryName}"). An OpFactoryCall produced an op for a different target on the postgres planner path; check the call's target binding.`, { meta: {
15
+ opId: op.id,
16
+ targetId: String(targetId),
17
+ factoryName: callFactoryName
18
+ } });
14
19
  }
15
20
  function renderOps(calls, lowerer) {
16
21
  return calls.map((c) => {
@@ -26,4 +31,4 @@ function renderOps(calls, lowerer) {
26
31
  //#endregion
27
32
  export { renderOps as t };
28
33
 
29
- //# sourceMappingURL=render-ops-BREh1kHe.mjs.map
34
+ //# sourceMappingURL=render-ops-TcY9XEkz.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-ops-TcY9XEkz.mjs","names":[],"sources":["../src/core/migrations/render-ops.ts"],"sourcesContent":["import type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport type {\n MigrationPlanOperation,\n OpFactoryCall,\n} from '@prisma-next/framework-components/control';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { isThenable } from '@prisma-next/utils/promise';\nimport { postgresError } from '../errors';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\n\ntype Op = SqlMigrationPlanOperation<PostgresPlanTargetDetails>;\n\n/**\n * Asserts an op materialised by an `OpFactoryCall` targets postgres. The\n * extension surface lets any contributor emit calls, so this is the\n * integration boundary where a stray non-postgres op would otherwise\n * silently flow through to postgres-shaped renderers — exactly the\n * place to fail loudly with op metadata (`id` + `target.id`).\n */\nfunction assertPostgresOp(op: MigrationPlanOperation, callFactoryName: string): asserts op is Op {\n const targetId = blindCast<\n { target?: { id?: string } },\n 'op.target is present on concrete SqlMigrationPlanOperation but absent on the framework MigrationPlanOperation base'\n >(op).target?.id;\n if (targetId !== 'postgres') {\n throw postgresError(\n 'MIGRATION.TARGET_MISMATCH',\n `renderOps: expected postgres op but got target.id=\"${String(targetId)}\" for op.id=\"${op.id}\" (factoryName=\"${callFactoryName}\"). An OpFactoryCall produced an op for a different target on the postgres planner path; check the call's target binding.`,\n { meta: { opId: op.id, targetId: String(targetId), factoryName: callFactoryName } },\n );\n }\n}\n\nexport function renderOps(\n calls: readonly OpFactoryCall[],\n lowerer?: ExecuteRequestLowerer,\n): (Op | Promise<Op>)[] {\n return calls.map((c) => {\n const opOrPromise = blindCast<\n { toOp(lowerer?: ExecuteRequestLowerer): Op | Promise<Op> },\n 'PG OpFactoryCall.toOp accepts an optional ExecuteRequestLowerer; the framework interface omits it because not all targets need a lowerer — the PG target overrides with this extended signature'\n >(c).toOp(lowerer);\n if (isThenable(opOrPromise)) {\n return opOrPromise.then((op) => {\n assertPostgresOp(op, c.factoryName);\n return op;\n });\n }\n assertPostgresOp(opOrPromise, c.factoryName);\n return opOrPromise;\n });\n}\n"],"mappings":";;;;;;;;;;;AAoBA,SAAS,iBAAiB,IAA4B,iBAA2C;CAC/F,MAAM,WAAW,UAGf,EAAE,CAAC,CAAC,QAAQ;CACd,IAAI,aAAa,YACf,MAAM,cACJ,6BACA,sDAAsD,OAAO,QAAQ,EAAE,eAAe,GAAG,GAAG,kBAAkB,gBAAgB,4HAC9H,EAAE,MAAM;EAAE,MAAM,GAAG;EAAI,UAAU,OAAO,QAAQ;EAAG,aAAa;CAAgB,EAAE,CACpF;AAEJ;AAEA,SAAgB,UACd,OACA,SACsB;CACtB,OAAO,MAAM,KAAK,MAAM;EACtB,MAAM,cAAc,UAGlB,CAAC,CAAC,CAAC,KAAK,OAAO;EACjB,IAAI,WAAW,WAAW,GACxB,OAAO,YAAY,MAAM,OAAO;GAC9B,iBAAiB,IAAI,EAAE,WAAW;GAClC,OAAO;EACT,CAAC;EAEH,iBAAiB,aAAa,EAAE,WAAW;EAC3C,OAAO;CACT,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"render-ops.d.mts","names":[],"sources":["../src/core/migrations/render-ops.ts"],"mappings":";;;;;KAUK,KAAK,0BAA0B;iBAqBpB,UACd,gBAAgB,iBAChB,UAAU,yBACR,KAAK,QAAQ"}
1
+ {"version":3,"file":"render-ops.d.mts","names":[],"sources":["../src/core/migrations/render-ops.ts"],"mappings":";;;;;KAWK,KAAK,0BAA0B;iBAuBpB,UACd,gBAAgB,iBAChB,UAAU,yBACR,KAAK,QAAQ"}
@@ -1,2 +1,2 @@
1
- import { t as renderOps } from "./render-ops-BREh1kHe.mjs";
1
+ import { t as renderOps } from "./render-ops-TcY9XEkz.mjs";
2
2
  export { renderOps };
@@ -1,5 +1,5 @@
1
1
  import { t as DEFAULT_NAMESPACE_ID } from "./namespace-ids-xtp_ZY86.mjs";
2
- import { r as isPostgresSchema } from "./postgres-schema-CewLYHB7.mjs";
2
+ import { r as isPostgresSchema } from "./postgres-schema-CTplQZDK.mjs";
3
3
  import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
4
4
  //#region src/core/migrations/resolve-ddl-schema.ts
5
5
  /**
@@ -19,4 +19,4 @@ function resolveDdlSchemaForNamespaceStorage(storage, namespaceId) {
19
19
  //#endregion
20
20
  export { resolveDdlSchemaForNamespaceStorage as t };
21
21
 
22
- //# sourceMappingURL=resolve-ddl-schema-D0wi_P9Q.mjs.map
22
+ //# sourceMappingURL=resolve-ddl-schema-BAsJEKW8.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-ddl-schema-D0wi_P9Q.mjs","names":[],"sources":["../src/core/migrations/resolve-ddl-schema.ts"],"sourcesContent":["import { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport { DEFAULT_NAMESPACE_ID } from '../namespace-ids';\nimport { isPostgresSchema } from '../postgres-schema';\n\n/**\n * Given the contract's storage and a namespace id, returns the live Postgres\n * DDL schema name that namespace maps to. A named Postgres namespace dispatches\n * to its `ddlSchemaName(storage)`; the unbound sentinel resolves to\n * `DEFAULT_NAMESPACE_ID` (the search-path default for offline planning); a\n * bare object payload (used by some tests) falls back to the namespace id\n * itself.\n */\nexport function resolveDdlSchemaForNamespaceStorage(\n storage: SqlStorage,\n namespaceId: string,\n): string {\n if (namespaceId === UNBOUND_NAMESPACE_ID) {\n return DEFAULT_NAMESPACE_ID;\n }\n const namespace = storage.namespaces[namespaceId];\n if (namespace && isPostgresSchema(namespace)) {\n return namespace.ddlSchemaName(storage);\n }\n return namespaceId;\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,oCACd,SACA,aACQ;CACR,IAAI,gBAAgB,sBAClB,OAAO;CAET,MAAM,YAAY,QAAQ,WAAW;CACrC,IAAI,aAAa,iBAAiB,SAAS,GACzC,OAAO,UAAU,cAAc,OAAO;CAExC,OAAO;AACT"}
1
+ {"version":3,"file":"resolve-ddl-schema-BAsJEKW8.mjs","names":[],"sources":["../src/core/migrations/resolve-ddl-schema.ts"],"sourcesContent":["import { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport { DEFAULT_NAMESPACE_ID } from '../namespace-ids';\nimport { isPostgresSchema } from '../postgres-schema';\n\n/**\n * Given the contract's storage and a namespace id, returns the live Postgres\n * DDL schema name that namespace maps to. A named Postgres namespace dispatches\n * to its `ddlSchemaName(storage)`; the unbound sentinel resolves to\n * `DEFAULT_NAMESPACE_ID` (the search-path default for offline planning); a\n * bare object payload (used by some tests) falls back to the namespace id\n * itself.\n */\nexport function resolveDdlSchemaForNamespaceStorage(\n storage: SqlStorage,\n namespaceId: string,\n): string {\n if (namespaceId === UNBOUND_NAMESPACE_ID) {\n return DEFAULT_NAMESPACE_ID;\n }\n const namespace = storage.namespaces[namespaceId];\n if (namespace && isPostgresSchema(namespace)) {\n return namespace.ddlSchemaName(storage);\n }\n return namespaceId;\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,oCACd,SACA,aACQ;CACR,IAAI,gBAAgB,sBAClB,OAAO;CAET,MAAM,YAAY,QAAQ,WAAW;CACrC,IAAI,aAAa,iBAAiB,SAAS,GACzC,OAAO,UAAU,cAAc,OAAO;CAExC,OAAO;AACT"}
package/dist/runtime.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as postgresTargetDescriptorMetaRuntime } from "./descriptor-meta-runtime-UwYdV8fD.mjs";
2
- import { n as PostgresContractSerializer, t as PostgresContractView } from "./postgres-contract-view-DebHMqGR.mjs";
2
+ import { n as PostgresContractSerializer, t as PostgresContractView } from "./postgres-contract-view-B8yXVWYe.mjs";
3
3
  //#region src/exports/runtime.ts
4
4
  /**
5
5
  * Target-postgres deliberately does NOT import `SqlRuntimeTargetDescriptor` from `@prisma-next/sql-runtime`. The target package is a control-plane residence and must not pull the SQL execution-plane package into its dependency closure. The runtime descriptor here is shaped to satisfy the framework's `RuntimeTargetDescriptor` plus the structural `SqlStaticContributions` (`codecs:` returning a descriptor list) that
@@ -1,2 +1,2 @@
1
- import { t as resolveDdlSchemaForNamespaceStorage } from "./resolve-ddl-schema-D0wi_P9Q.mjs";
1
+ import { t as resolveDdlSchemaForNamespaceStorage } from "./resolve-ddl-schema-BAsJEKW8.mjs";
2
2
  export { resolveDdlSchemaForNamespaceStorage };
@@ -1,3 +1,4 @@
1
+ import { n as postgresError } from "./errors-DBSNx7EJ.mjs";
1
2
  //#region src/core/sql-utils.ts
2
3
  /**
3
4
  * Shared SQL utility functions for the Postgres target.
@@ -10,16 +11,6 @@
10
11
  * escaping/validation behavior, and the target package is the natural shared
11
12
  * home that both adapters can depend on without crossing planes.
12
13
  */
13
- var SqlEscapeError = class extends Error {
14
- value;
15
- kind;
16
- constructor(message, value, kind) {
17
- super(message);
18
- this.value = value;
19
- this.kind = kind;
20
- this.name = "SqlEscapeError";
21
- }
22
- };
23
14
  const MAX_IDENTIFIER_LENGTH = 63;
24
15
  /**
25
16
  * Validates and quotes a PostgreSQL identifier (table, column, type, schema names).
@@ -29,11 +20,17 @@ const MAX_IDENTIFIER_LENGTH = 63;
29
20
  * - Rejects empty identifiers
30
21
  * - Warns on identifiers exceeding PostgreSQL's 63-character limit
31
22
  *
32
- * @throws {SqlEscapeError} If the identifier contains null bytes or is empty
23
+ * @throws `CONTRACT.IDENTIFIER_INVALID` structured error If the identifier contains null bytes or is empty
33
24
  */
34
25
  function quoteIdentifier(identifier) {
35
- if (identifier.length === 0) throw new SqlEscapeError("Identifier cannot be empty", identifier, "identifier");
36
- if (identifier.includes("\0")) throw new SqlEscapeError("Identifier cannot contain null bytes", identifier.replace(/\0/g, "\\0"), "identifier");
26
+ if (identifier.length === 0) throw postgresError("CONTRACT.IDENTIFIER_INVALID", "Identifier cannot be empty", { meta: {
27
+ value: identifier,
28
+ context: "identifier"
29
+ } });
30
+ if (identifier.includes("\0")) throw postgresError("CONTRACT.IDENTIFIER_INVALID", "Identifier cannot contain null bytes", { meta: {
31
+ value: identifier.replace(/\0/g, "\\0"),
32
+ context: "identifier"
33
+ } });
37
34
  if (identifier.length > MAX_IDENTIFIER_LENGTH) console.warn(`Identifier "${identifier.slice(0, 20)}..." exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character limit and will be truncated`);
38
35
  return `"${identifier.replace(/"/g, "\"\"")}"`;
39
36
  }
@@ -46,10 +43,13 @@ function quoteIdentifier(identifier) {
46
43
  * Note: This assumes PostgreSQL's `standard_conforming_strings` is ON (default since PG 9.1).
47
44
  * Backslashes are treated as literal characters, not escape sequences.
48
45
  *
49
- * @throws {SqlEscapeError} If the value contains null bytes
46
+ * @throws `CONTRACT.IDENTIFIER_INVALID` structured error If the value contains null bytes
50
47
  */
51
48
  function escapeLiteral(value) {
52
- if (value.includes("\0")) throw new SqlEscapeError("Literal value cannot contain null bytes", value.replace(/\0/g, "\\0"), "literal");
49
+ if (value.includes("\0")) throw postgresError("CONTRACT.IDENTIFIER_INVALID", "Literal value cannot contain null bytes", { meta: {
50
+ value: value.replace(/\0/g, "\\0"),
51
+ context: "literal"
52
+ } });
53
53
  return value.replace(/'/g, "''");
54
54
  }
55
55
  /**
@@ -76,12 +76,15 @@ function quoteQualifiedName(name) {
76
76
  *
77
77
  * @param value - The enum value to validate
78
78
  * @param enumTypeName - Name of the enum type (for error messages)
79
- * @throws {SqlEscapeError} If the value exceeds the maximum length
79
+ * @throws `CONTRACT.IDENTIFIER_INVALID` structured error If the value exceeds the maximum length
80
80
  */
81
81
  function validateEnumValueLength(value, enumTypeName) {
82
- if (new TextEncoder().encode(value).length > MAX_IDENTIFIER_LENGTH) throw new SqlEscapeError(`Enum value "${value.slice(0, 20)}..." for type "${enumTypeName}" exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-byte label limit`, value, "literal");
82
+ if (new TextEncoder().encode(value).length > MAX_IDENTIFIER_LENGTH) throw postgresError("CONTRACT.IDENTIFIER_INVALID", `Enum value "${value.slice(0, 20)}..." for type "${enumTypeName}" exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-byte label limit`, { meta: {
83
+ value,
84
+ context: "enum-label"
85
+ } });
83
86
  }
84
87
  //#endregion
85
- export { quoteQualifiedName as a, quoteIdentifier as i, escapeLiteral as n, validateEnumValueLength as o, qualifyName as r, SqlEscapeError as t };
88
+ export { validateEnumValueLength as a, quoteQualifiedName as i, qualifyName as n, quoteIdentifier as r, escapeLiteral as t };
86
89
 
87
- //# sourceMappingURL=sql-utils-SU4FDvIV.mjs.map
90
+ //# sourceMappingURL=sql-utils-B2lzkKfP.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sql-utils-B2lzkKfP.mjs","names":[],"sources":["../src/core/sql-utils.ts"],"sourcesContent":["/**\n * Shared SQL utility functions for the Postgres target.\n *\n * These functions handle safe SQL identifier and literal escaping\n * with security validations to prevent injection and encoding issues.\n *\n * They live in `target-postgres` because both the control adapter (used at\n * emit time) and the runtime adapter (used at execute time) need the same\n * escaping/validation behavior, and the target package is the natural shared\n * home that both adapters can depend on without crossing planes.\n */\n\nimport { postgresError } from './errors';\n\nconst MAX_IDENTIFIER_LENGTH = 63;\n\n/**\n * Validates and quotes a PostgreSQL identifier (table, column, type, schema names).\n *\n * Security validations:\n * - Rejects null bytes which could cause truncation or unexpected behavior\n * - Rejects empty identifiers\n * - Warns on identifiers exceeding PostgreSQL's 63-character limit\n *\n * @throws `CONTRACT.IDENTIFIER_INVALID` structured error If the identifier contains null bytes or is empty\n */\nexport function quoteIdentifier(identifier: string): string {\n if (identifier.length === 0) {\n throw postgresError('CONTRACT.IDENTIFIER_INVALID', 'Identifier cannot be empty', {\n meta: { value: identifier, context: 'identifier' },\n });\n }\n if (identifier.includes('\\0')) {\n throw postgresError('CONTRACT.IDENTIFIER_INVALID', 'Identifier cannot contain null bytes', {\n meta: { value: identifier.replace(/\\0/g, '\\\\0'), context: 'identifier' },\n });\n }\n if (identifier.length > MAX_IDENTIFIER_LENGTH) {\n console.warn(\n `Identifier \"${identifier.slice(0, 20)}...\" exceeds PostgreSQL's ${MAX_IDENTIFIER_LENGTH}-character limit and will be truncated`,\n );\n }\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`;\n}\n\n/**\n * Escapes a string literal for safe use in SQL statements.\n *\n * Security validations:\n * - Rejects null bytes which could cause truncation or unexpected behavior\n *\n * Note: This assumes PostgreSQL's `standard_conforming_strings` is ON (default since PG 9.1).\n * Backslashes are treated as literal characters, not escape sequences.\n *\n * @throws `CONTRACT.IDENTIFIER_INVALID` structured error If the value contains null bytes\n */\nexport function escapeLiteral(value: string): string {\n if (value.includes('\\0')) {\n throw postgresError('CONTRACT.IDENTIFIER_INVALID', 'Literal value cannot contain null bytes', {\n meta: { value: value.replace(/\\0/g, '\\\\0'), context: 'literal' },\n });\n }\n return value.replace(/'/g, \"''\");\n}\n\n/**\n * Builds a qualified name (schema.object) with proper quoting.\n */\nexport function qualifyName(schemaName: string, objectName: string): string {\n return `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;\n}\n\n/**\n * Quotes a possibly dot-qualified name segment-by-segment:\n * `order_status` -> `\"order_status\"`, `auth.aal_level` -> `\"auth\".\"aal_level\"`.\n * A single-segment name round-trips to exactly {@link quoteIdentifier}; whole-\n * string quoting (`\"auth.aal_level\"`) would be one wrong identifier.\n */\nexport function quoteQualifiedName(name: string): string {\n return name\n .split('.')\n .map((segment) => quoteIdentifier(segment))\n .join('.');\n}\n\n/**\n * Validates that an enum value doesn't exceed PostgreSQL's label length limit.\n *\n * PostgreSQL enum labels have a maximum length of NAMEDATALEN-1 (63 bytes by default).\n * Unlike identifiers, enum labels that exceed this limit cause an error rather than\n * silent truncation.\n *\n * @param value - The enum value to validate\n * @param enumTypeName - Name of the enum type (for error messages)\n * @throws `CONTRACT.IDENTIFIER_INVALID` structured error If the value exceeds the maximum length\n */\nexport function validateEnumValueLength(value: string, enumTypeName: string): void {\n if (new TextEncoder().encode(value).length > MAX_IDENTIFIER_LENGTH) {\n throw postgresError(\n 'CONTRACT.IDENTIFIER_INVALID',\n `Enum value \"${value.slice(0, 20)}...\" for type \"${enumTypeName}\" exceeds PostgreSQL's ` +\n `${MAX_IDENTIFIER_LENGTH}-byte label limit`,\n { meta: { value, context: 'enum-label' } },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,MAAM,wBAAwB;;;;;;;;;;;AAY9B,SAAgB,gBAAgB,YAA4B;CAC1D,IAAI,WAAW,WAAW,GACxB,MAAM,cAAc,+BAA+B,8BAA8B,EAC/E,MAAM;EAAE,OAAO;EAAY,SAAS;CAAa,EACnD,CAAC;CAEH,IAAI,WAAW,SAAS,IAAI,GAC1B,MAAM,cAAc,+BAA+B,wCAAwC,EACzF,MAAM;EAAE,OAAO,WAAW,QAAQ,OAAO,KAAK;EAAG,SAAS;CAAa,EACzE,CAAC;CAEH,IAAI,WAAW,SAAS,uBACtB,QAAQ,KACN,eAAe,WAAW,MAAM,GAAG,EAAE,EAAE,4BAA4B,sBAAsB,uCAC3F;CAEF,OAAO,IAAI,WAAW,QAAQ,MAAM,MAAI,EAAE;AAC5C;;;;;;;;;;;;AAaA,SAAgB,cAAc,OAAuB;CACnD,IAAI,MAAM,SAAS,IAAI,GACrB,MAAM,cAAc,+BAA+B,2CAA2C,EAC5F,MAAM;EAAE,OAAO,MAAM,QAAQ,OAAO,KAAK;EAAG,SAAS;CAAU,EACjE,CAAC;CAEH,OAAO,MAAM,QAAQ,MAAM,IAAI;AACjC;;;;AAKA,SAAgB,YAAY,YAAoB,YAA4B;CAC1E,OAAO,GAAG,gBAAgB,UAAU,EAAE,GAAG,gBAAgB,UAAU;AACrE;;;;;;;AAQA,SAAgB,mBAAmB,MAAsB;CACvD,OAAO,KACJ,MAAM,GAAG,CAAC,CACV,KAAK,YAAY,gBAAgB,OAAO,CAAC,CAAC,CAC1C,KAAK,GAAG;AACb;;;;;;;;;;;;AAaA,SAAgB,wBAAwB,OAAe,cAA4B;CACjF,IAAI,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,SAAS,uBAC3C,MAAM,cACJ,+BACA,eAAe,MAAM,MAAM,GAAG,EAAE,EAAE,iBAAiB,aAAa,yBAC3D,sBAAsB,oBAC3B,EAAE,MAAM;EAAE;EAAO,SAAS;CAAa,EAAE,CAC3C;AAEJ"}
@@ -10,11 +10,6 @@
10
10
  * escaping/validation behavior, and the target package is the natural shared
11
11
  * home that both adapters can depend on without crossing planes.
12
12
  */
13
- declare class SqlEscapeError extends Error {
14
- readonly value: string;
15
- readonly kind: 'identifier' | 'literal';
16
- constructor(message: string, value: string, kind: 'identifier' | 'literal');
17
- }
18
13
  /**
19
14
  * Validates and quotes a PostgreSQL identifier (table, column, type, schema names).
20
15
  *
@@ -23,7 +18,7 @@ declare class SqlEscapeError extends Error {
23
18
  * - Rejects empty identifiers
24
19
  * - Warns on identifiers exceeding PostgreSQL's 63-character limit
25
20
  *
26
- * @throws {SqlEscapeError} If the identifier contains null bytes or is empty
21
+ * @throws `CONTRACT.IDENTIFIER_INVALID` structured error If the identifier contains null bytes or is empty
27
22
  */
28
23
  declare function quoteIdentifier(identifier: string): string;
29
24
  /**
@@ -35,7 +30,7 @@ declare function quoteIdentifier(identifier: string): string;
35
30
  * Note: This assumes PostgreSQL's `standard_conforming_strings` is ON (default since PG 9.1).
36
31
  * Backslashes are treated as literal characters, not escape sequences.
37
32
  *
38
- * @throws {SqlEscapeError} If the value contains null bytes
33
+ * @throws `CONTRACT.IDENTIFIER_INVALID` structured error If the value contains null bytes
39
34
  */
40
35
  declare function escapeLiteral(value: string): string;
41
36
  /**
@@ -58,9 +53,9 @@ declare function quoteQualifiedName(name: string): string;
58
53
  *
59
54
  * @param value - The enum value to validate
60
55
  * @param enumTypeName - Name of the enum type (for error messages)
61
- * @throws {SqlEscapeError} If the value exceeds the maximum length
56
+ * @throws `CONTRACT.IDENTIFIER_INVALID` structured error If the value exceeds the maximum length
62
57
  */
63
58
  declare function validateEnumValueLength(value: string, enumTypeName: string): void;
64
59
  //#endregion
65
- export { SqlEscapeError, escapeLiteral, qualifyName, quoteIdentifier, quoteQualifiedName, validateEnumValueLength };
60
+ export { escapeLiteral, qualifyName, quoteIdentifier, quoteQualifiedName, validateEnumValueLength };
66
61
  //# sourceMappingURL=sql-utils.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sql-utils.d.mts","names":[],"sources":["../src/core/sql-utils.ts"],"mappings":";;;;;;;;;;;;cAYa,uBAAuB;WAGhB;WACA;cAFhB,iBACgB,eACA;;;;;;;;;;;;iBAmBJ,gBAAgB;;;;;;;;;;;;iBA8BhB,cAAc;;;;iBAcd,YAAY,oBAAoB;;;;;;;iBAUhC,mBAAmB;;;;;;;;;;;;iBAkBnB,wBAAwB,eAAe"}
1
+ {"version":3,"file":"sql-utils.d.mts","names":[],"sources":["../src/core/sql-utils.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBA0BgB,gBAAgB;;;;;;;;;;;;iBA8BhB,cAAc;;;;iBAYd,YAAY,oBAAoB;;;;;;;iBAUhC,mBAAmB;;;;;;;;;;;;iBAkBnB,wBAAwB,eAAe"}
@@ -1,2 +1,2 @@
1
- import { a as quoteQualifiedName, i as quoteIdentifier, n as escapeLiteral, o as validateEnumValueLength, r as qualifyName, t as SqlEscapeError } from "./sql-utils-SU4FDvIV.mjs";
2
- export { SqlEscapeError, escapeLiteral, qualifyName, quoteIdentifier, quoteQualifiedName, validateEnumValueLength };
1
+ import { a as validateEnumValueLength, i as quoteQualifiedName, n as qualifyName, r as quoteIdentifier, t as escapeLiteral } from "./sql-utils-B2lzkKfP.mjs";
2
+ export { escapeLiteral, qualifyName, quoteIdentifier, quoteQualifiedName, validateEnumValueLength };
package/dist/types.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as PostgresNativeEnum } from "./postgres-native-enum-BwVNf0Ku.mjs";
2
- import { _ as PostgresRlsEnablement, g as PostgresRlsPolicy, i as postgresCreateNamespace, m as PostgresRole, n as PostgresUnboundSchema, r as isPostgresSchema, t as PostgresSchema } from "./postgres-schema-CewLYHB7.mjs";
2
+ import { _ as PostgresRlsEnablement, g as PostgresRlsPolicy, i as postgresCreateNamespace, m as PostgresRole, n as PostgresUnboundSchema, r as isPostgresSchema, t as PostgresSchema } from "./postgres-schema-CTplQZDK.mjs";
3
3
  import { n as PostgresNativeEnumSchemaNode, r as PostgresSchemaNodeKind, t as PostgresTableSchemaNode } from "./postgres-table-schema-node-D6LvInCe.mjs";
4
4
  import { i as PostgresDatabaseSchemaNode, n as PostgresPolicySchemaNode, r as PostgresNamespaceSchemaNode, t as PostgresRoleSchemaNode } from "./postgres-role-schema-node-bg32e7I-.mjs";
5
5
  export { PostgresDatabaseSchemaNode, PostgresNamespaceSchemaNode, PostgresNativeEnum, PostgresNativeEnumSchemaNode, PostgresPolicySchemaNode, PostgresRlsEnablement, PostgresRlsPolicy, PostgresRole, PostgresRoleSchemaNode, PostgresSchema, PostgresSchemaNodeKind, PostgresTableSchemaNode, PostgresUnboundSchema, isPostgresSchema, postgresCreateNamespace };
package/package.json CHANGED
@@ -1,35 +1,35 @@
1
1
  {
2
2
  "name": "@prisma-next/target-postgres",
3
- "version": "0.16.0-dev.22",
3
+ "version": "0.16.0-dev.24",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "Postgres target pack for Prisma Next",
8
8
  "dependencies": {
9
- "@prisma-next/cli": "0.16.0-dev.22",
10
- "@prisma-next/contract": "0.16.0-dev.22",
11
- "@prisma-next/errors": "0.16.0-dev.22",
12
- "@prisma-next/family-sql": "0.16.0-dev.22",
13
- "@prisma-next/framework-components": "0.16.0-dev.22",
14
- "@prisma-next/migration-tools": "0.16.0-dev.22",
15
- "@prisma-next/psl-parser": "0.16.0-dev.22",
16
- "@prisma-next/sql-contract": "0.16.0-dev.22",
17
- "@prisma-next/sql-errors": "0.16.0-dev.22",
18
- "@prisma-next/sql-operations": "0.16.0-dev.22",
19
- "@prisma-next/sql-relational-core": "0.16.0-dev.22",
20
- "@prisma-next/sql-schema-ir": "0.16.0-dev.22",
21
- "@prisma-next/ts-render": "0.16.0-dev.22",
22
- "@prisma-next/utils": "0.16.0-dev.22",
9
+ "@prisma-next/cli": "0.16.0-dev.24",
10
+ "@prisma-next/contract": "0.16.0-dev.24",
11
+ "@prisma-next/errors": "0.16.0-dev.24",
12
+ "@prisma-next/family-sql": "0.16.0-dev.24",
13
+ "@prisma-next/framework-components": "0.16.0-dev.24",
14
+ "@prisma-next/migration-tools": "0.16.0-dev.24",
15
+ "@prisma-next/psl-parser": "0.16.0-dev.24",
16
+ "@prisma-next/sql-contract": "0.16.0-dev.24",
17
+ "@prisma-next/sql-errors": "0.16.0-dev.24",
18
+ "@prisma-next/sql-operations": "0.16.0-dev.24",
19
+ "@prisma-next/sql-relational-core": "0.16.0-dev.24",
20
+ "@prisma-next/sql-schema-ir": "0.16.0-dev.24",
21
+ "@prisma-next/ts-render": "0.16.0-dev.24",
22
+ "@prisma-next/utils": "0.16.0-dev.24",
23
23
  "@standard-schema/spec": "^1.1.0",
24
24
  "arktype": "^2.2.2",
25
25
  "pathe": "^2.0.3"
26
26
  },
27
27
  "devDependencies": {
28
- "@prisma-next/psl-printer": "0.16.0-dev.22",
29
- "@prisma-next/sql-contract-psl": "0.16.0-dev.22",
30
- "@prisma-next/test-utils": "0.16.0-dev.22",
31
- "@prisma-next/tsconfig": "0.16.0-dev.22",
32
- "@prisma-next/tsdown": "0.16.0-dev.22",
28
+ "@prisma-next/psl-printer": "0.16.0-dev.24",
29
+ "@prisma-next/sql-contract-psl": "0.16.0-dev.24",
30
+ "@prisma-next/test-utils": "0.16.0-dev.24",
31
+ "@prisma-next/tsconfig": "0.16.0-dev.24",
32
+ "@prisma-next/tsdown": "0.16.0-dev.24",
33
33
  "tsdown": "0.22.8",
34
34
  "typescript": "5.9.3",
35
35
  "vitest": "4.1.10"