@prisma-next/target-postgres 0.14.0-dev.46 → 0.14.0-dev.47

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.
package/dist/control.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-CuGDsrG4.mjs";
2
2
  import { a as PostgresDatabaseSchemaNode } from "./postgres-table-schema-node-Clei_xel.mjs";
3
- import { i as contractToPostgresDatabaseSchemaNode, n as diffPostgresDatabaseSchema, r as verifyPostgresDatabaseSchema, t as createPostgresMigrationPlanner } from "./planner-CMXuFrQB.mjs";
3
+ import { i as contractToPostgresDatabaseSchemaNode, n as diffPostgresDatabaseSchema, r as verifyPostgresDatabaseSchema, t as createPostgresMigrationPlanner } from "./planner-Bq0Z2sVO.mjs";
4
4
  import { r as renderDefaultLiteral } from "./planner-ddl-builders-B8Nn6nHN.mjs";
5
- import { n as PostgresContractSerializer } from "./postgres-contract-view-V3rGJCoe.mjs";
5
+ import { n as PostgresContractSerializer } from "./postgres-contract-view-3xfUgjnC.mjs";
6
6
  import { UNBOUND_NAMESPACE_ID, coordinateKey, elementCoordinates } from "@prisma-next/framework-components/ir";
7
7
  import { blindCast } from "@prisma-next/utils/casts";
8
8
  import { extractCodecControlHooks, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
@@ -1,6 +1,6 @@
1
1
  import { k as createExtension } from "./op-factory-call-BuoGT5UI.mjs";
2
2
  import { t as dataTransform } from "./data-transform-BOWpliq8.mjs";
3
- import { t as PostgresMigration } from "./postgres-migration-CZApTUCK.mjs";
3
+ import { t as PostgresMigration } from "./postgres-migration-D0QIVE-p.mjs";
4
4
  import { checkExpression, col, fn, foreignKey, lit, primaryKey, unique } from "@prisma-next/sql-relational-core/contract-free";
5
5
  import { placeholder } from "@prisma-next/errors/migration";
6
6
  import { MigrationCLI } from "@prisma-next/cli/migration-cli";
@@ -6,7 +6,7 @@ import { t as parsePostgresDefault } from "./default-normalizer-Dug8Fez9.mjs";
6
6
  import { t as normalizeSchemaNativeType } from "./native-type-normalizer-Bc9XJzWC.mjs";
7
7
  import { C as EnableRowLevelSecurityCall, d as CreatePostgresRlsPolicyCall, x as DropPostgresRlsPolicyCall } from "./op-factory-call-BuoGT5UI.mjs";
8
8
  import { n as postgresPlannerStrategies, t as planIssues } from "./issue-planner-Cbh-xTEr.mjs";
9
- import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-CikV-edi.mjs";
9
+ import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-C2_H6Vvl.mjs";
10
10
  import { UNBOUND_NAMESPACE_ID, entityAt } from "@prisma-next/framework-components/ir";
11
11
  import { blindCast } from "@prisma-next/utils/casts";
12
12
  import { contractNamespaceToSchemaIR, extractCodecControlHooks, partitionCallsByControlPolicy, partitionIssuesByControlPolicy, planFieldEventOperations, plannerFailure } from "@prisma-next/family-sql/control";
@@ -638,4 +638,4 @@ function policyNodeToContractPolicy(node) {
638
638
  //#endregion
639
639
  export { contractToPostgresDatabaseSchemaNode as i, diffPostgresDatabaseSchema as n, verifyPostgresDatabaseSchema as r, createPostgresMigrationPlanner as t };
640
640
 
641
- //# sourceMappingURL=planner-CMXuFrQB.mjs.map
641
+ //# sourceMappingURL=planner-Bq0Z2sVO.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"planner-CMXuFrQB.mjs","names":["#lowerer"],"sources":["../src/core/migrations/contract-to-postgres-database-schema-node.ts","../src/core/migrations/diff-database-schema.ts","../src/core/migrations/control-policy.ts","../src/core/migrations/verify-postgres-namespaces.ts","../src/core/migrations/planner.ts"],"sourcesContent":["import type { ContractToSchemaIROptions } from '@prisma-next/family-sql/control';\nimport { contractNamespaceToSchemaIR } from '@prisma-next/family-sql/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresRlsPolicy } from '../postgres-rls-policy';\nimport type { PostgresContract } from '../postgres-schema';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport { PostgresPolicySchemaNode } from '../schema-ir/postgres-policy-schema-node';\nimport { PostgresRoleSchemaNode } from '../schema-ir/postgres-role-schema-node';\nimport { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';\nimport { resolveDdlSchemaForNamespaceStorage } from './resolve-ddl-schema';\n\nfunction toPolicyNode(policy: PostgresRlsPolicy, namespaceId: string): PostgresPolicySchemaNode {\n return new PostgresPolicySchemaNode({\n name: policy.name,\n prefix: policy.prefix,\n tableName: policy.tableName,\n namespaceId,\n operation: policy.operation,\n roles: [...policy.roles],\n ...ifDefined('using', policy.using),\n ...ifDefined('withCheck', policy.withCheck),\n permissive: policy.permissive,\n });\n}\n\n/**\n * Projects a Postgres contract into the expected schema-diff tree: a\n * `PostgresDatabaseSchemaNode` root holding one `PostgresNamespaceSchemaNode`\n * per Postgres namespace, each holding its `PostgresTableSchemaNode`s with\n * their `PostgresPolicySchemaNode`s, plus the database roles on the root.\n *\n * Not a duplicate of the family's `contractToSchemaIR`: that builds a flat,\n * single `{ tables }` map (and throws on cross-namespace name collisions, with\n * no RLS/role concept) for SQLite's single-schema world. This is the\n * Postgres-specific *tree* shape — multi-schema, RLS-policy-aware, role-aware.\n * It reuses the family's per-namespace table conversion (`contractNamespaceToSchemaIR`)\n * for column/FK/index building and only adds the Postgres tree/policy/role shape.\n *\n * Tables are grouped by their owning namespace (resolved DDL schema name) so\n * the tree mirrors Postgres's object hierarchy. The DDL schema name is\n * resolved once per namespace.\n *\n * A policy that references a table absent from its namespace is a malformed\n * contract — the loop throws rather than fabricating a stub table.\n */\nexport function contractToPostgresDatabaseSchemaNode(\n contract: PostgresContract | null,\n options: ContractToSchemaIROptions,\n): PostgresDatabaseSchemaNode {\n if (contract === null) {\n return new PostgresDatabaseSchemaNode({\n namespaces: {},\n roles: [],\n existingSchemas: [],\n pgVersion: '',\n });\n }\n\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = {};\n const roles: PostgresRoleSchemaNode[] = [];\n const ownedSchemas: string[] = [];\n\n for (const ns of Object.values(contract.storage.namespaces)) {\n if (!isPostgresSchema(ns)) continue;\n const ddlSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id);\n ownedSchemas.push(ddlSchema);\n\n // Convert only THIS namespace's tables (passing the full storage for\n // type/value-set/enum resolution that spans namespaces), so the same table\n // name can exist in two schemas without colliding in a bare-keyed record.\n const sqlTables = contractNamespaceToSchemaIR(contract.storage, ns.id, options).tables;\n\n const policiesByTable = new Map<string, PostgresPolicySchemaNode[]>();\n for (const policy of Object.values(ns.policy)) {\n const list = policiesByTable.get(policy.tableName) ?? [];\n list.push(toPolicyNode(policy, ddlSchema));\n policiesByTable.set(policy.tableName, list);\n }\n\n const tables: Record<string, PostgresTableSchemaNode> = {};\n for (const tableName of Object.keys(ns.table)) {\n const sqlTable = sqlTables[tableName];\n if (sqlTable === undefined) continue;\n tables[tableName] = new PostgresTableSchemaNode({\n name: sqlTable.name,\n columns: sqlTable.columns,\n foreignKeys: sqlTable.foreignKeys,\n uniques: sqlTable.uniques,\n indexes: sqlTable.indexes,\n ...ifDefined('primaryKey', sqlTable.primaryKey),\n ...ifDefined('annotations', sqlTable.annotations),\n ...ifDefined('checks', sqlTable.checks),\n policies: policiesByTable.get(tableName) ?? [],\n });\n }\n\n for (const [tableName, tablePolicies] of policiesByTable) {\n if (!(tableName in tables)) {\n const policyName = tablePolicies[0]?.name ?? '(unknown)';\n throw new Error(\n `contract-to-postgres-database-schema-node: policy \"${policyName}\" references table \"${tableName}\" not present in namespace \"${ddlSchema}\"`,\n );\n }\n }\n\n namespaces[ddlSchema] = new PostgresNamespaceSchemaNode({\n schemaName: ddlSchema,\n tables,\n nativeEnumTypeNames: [],\n });\n\n for (const role of Object.values(ns.role)) {\n roles.push(new PostgresRoleSchemaNode({ name: role.name, namespaceId: role.namespaceId }));\n }\n }\n\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles,\n existingSchemas: ownedSchemas,\n pgVersion: '',\n });\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { verifySqlSchemaTree } from '@prisma-next/family-sql/diff';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n SchemaDiffIssue,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport { diffSchemas, SchemaDiff } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport type { PostgresContract } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresPolicySchemaNode } from '../schema-ir/postgres-policy-schema-node';\nimport type { SqlSchemaDiffNode } from '../schema-ir/schema-node-kinds';\nimport { contractToPostgresDatabaseSchemaNode } from './contract-to-postgres-database-schema-node';\n\ninterface PostgresDiffDatabaseSchemaInput {\n readonly contract: Contract<SqlStorage>;\n readonly actualSchema: SqlSchemaIRNode;\n readonly strict: boolean;\n readonly typeMetadataRegistry: ReadonlyMap<string, { readonly nativeType?: string }>;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}\n\n/**\n * The single combined database-schema comparison — the one computation the\n * migration planner and the family schema verify both consume. Composes,\n * once each:\n *\n * - the per-namespace-paired relational diff (`verifySqlSchemaTree`) → table /\n * column / constraint findings as framework `SchemaIssue`s (with the\n * verification-tree `root` and pass/warn/fail counts);\n * - the policy diff (`diffPostgresSchema` over the two trees) → RLS policy\n * presence as `SchemaDiffIssue`s, ownership-filtered to the contract's owned\n * schemas.\n *\n * `diffPostgresDatabaseSchema` and `verifyPostgresDatabaseSchema` both read\n * this single result, so the relational walk runs once per caller — never\n * once for the diff and again for the verify tree.\n */\nfunction computePostgresSchemaComparison(input: PostgresDiffDatabaseSchemaInput): {\n readonly relational: VerifyDatabaseSchemaResult;\n readonly schemaDiffIssues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[];\n} {\n const postgresContract = blindCast<\n PostgresContract,\n 'diffPostgresDatabaseSchema is only called with a postgres contract'\n >(input.contract);\n\n // Relational diff: per-namespace-paired so a multi-schema database checks each\n // contract namespace against its own actual node.\n const relational = verifySqlSchemaTree({\n contract: input.contract,\n actualSchema: input.actualSchema,\n buildExpectedSchema: (scopedContract) =>\n contractToPostgresDatabaseSchemaNode(\n blindCast<\n PostgresContract | null,\n 'the relational pairing projects a scoped postgres contract'\n >(scopedContract),\n { annotationNamespace: 'pg' },\n ),\n strict: input.strict,\n typeMetadataRegistry: input.typeMetadataRegistry,\n frameworkComponents: input.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n\n // Policy diff: the generic node differ over the expected/actual policy trees,\n // ownership-filtered to the schemas the contract owns (so unowned-namespace\n // policies are not reported as extras). The actual schema is always the\n // Postgres database root in production — assert it, matching the prior\n // `collectSchemaDiffIssues` / `planPostgresSchemaDiff` behaviour.\n PostgresDatabaseSchemaNode.assert(input.actualSchema);\n const expected = contractToPostgresDatabaseSchemaNode(postgresContract, {\n annotationNamespace: 'pg',\n });\n const schemaDiffIssues = filterIssuesByOwnership(\n diffPostgresSchema(expected, input.actualSchema),\n ownedSchemaNames(expected),\n );\n\n return { relational, schemaDiffIssues };\n}\n\n/**\n * The `SchemaDiffer` for Postgres: the target's black-box comparison,\n * projected to the two issue lists. Namespace presence (`missing_schema` →\n * `CREATE SCHEMA`) is intentionally NOT composed here: it is a planner-only\n * op-generation concern (verify rejects on the relational `missing_table` a\n * missing schema already produces), so the planner stitches it in around this\n * diff. Control-policy suppression of the policy issues is likewise a\n * per-consumer post-step (verify filters the issues; the planner filters the\n * calls).\n */\nexport function diffPostgresDatabaseSchema(\n input: PostgresDiffDatabaseSchemaInput,\n): SchemaDiff<SqlSchemaDiffNode> {\n const { relational, schemaDiffIssues } = computePostgresSchemaComparison(input);\n return new SchemaDiff(relational.schema.issues, schemaDiffIssues);\n}\n\n/**\n * The same combined comparison as {@link diffPostgresDatabaseSchema}, wrapped\n * in the verify envelope (`ok`/`summary`/`code`/`target`/`timings`) plus the\n * pass/warn/fail tree the CLI renders — i.e. exactly the existing verify-result\n * schema shape, so nothing downstream changes.\n */\nexport function verifyPostgresDatabaseSchema(\n input: PostgresDiffDatabaseSchemaInput,\n): VerifyDatabaseSchemaResult {\n const { relational, schemaDiffIssues } = computePostgresSchemaComparison(input);\n return {\n ...relational,\n schema: { ...relational.schema, schemaDiffIssues },\n };\n}\n\nfunction ownedSchemaNames(expected: PostgresDatabaseSchemaNode): ReadonlySet<string> {\n const policyNamespaces = Object.values(expected.namespaces).flatMap((ns) =>\n Object.values(ns.tables).flatMap((t) => t.policies.map((p) => p.namespaceId)),\n );\n return new Set([...policyNamespaces, ...expected.existingSchemas]);\n}\n\n// Renders a display-only reference string for the diff message. If policy\n// rendering grows, route it through the adapter's SQL renderer so the message\n// can't diverge from the emitted policy SQL.\nfunction renderPostgresPolicyReference(policy: PostgresPolicySchemaNode): string {\n return `policy \"${policy.name}\" on \"${policy.namespaceId}\".\"${policy.tableName}\"`;\n}\n\n/**\n * The policy node-diff — the structural half of the combined comparison above.\n * Computes RLS-policy drift between two derived schema trees:\n *\n * 1. Runs the framework total diff over the two `PostgresDatabaseSchemaNode`\n * roots (database → namespace → table → policy).\n * 2. Filters to policy-subject issues only — this is transitional: the generic\n * differ walks the whole tree, but the legacy relational verifier still owns\n * table/column drift, so non-policy issues are dropped here.\n * 3. Remaps the message to a human-readable policy reference.\n *\n * Both trees are `PostgresDatabaseSchemaNode`s, so every issue node is a\n * `SqlSchemaDiffNode` — narrow the framework's `SchemaDiffIssue<DiffableNode>`\n * output once here (the single boundary cast), so every downstream consumer\n * (the ownership filter, the planner) reads the concrete node with no cast.\n *\n * Ownership filtering (dropping `extra` issues in namespaces a contract doesn't\n * own) is the caller's responsibility — use `filterIssuesByOwnership`.\n */\nexport function diffPostgresSchema(\n expected: PostgresDatabaseSchemaNode,\n actual: PostgresDatabaseSchemaNode,\n): readonly SchemaDiffIssue<SqlSchemaDiffNode>[] {\n const issues = blindCast<\n readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n 'both trees are PostgresDatabaseSchemaNodes, so every diff-issue node is a SqlSchemaDiffNode'\n >(diffSchemas(expected, actual));\n\n return issues\n .filter((i) => {\n const node = i.expected ?? i.actual;\n return node !== undefined && PostgresPolicySchemaNode.is(node);\n })\n .map((i) => {\n const node = i.expected ?? i.actual;\n if (node === undefined || !PostgresPolicySchemaNode.is(node)) return i;\n return { ...i, message: `${i.outcome}: ${renderPostgresPolicyReference(node)}` };\n });\n}\n\n/**\n * Filters `extra` policy issues to those in owned namespaces. Call after\n * `diffPostgresSchema` with the union of namespace ids from the expected tree's\n * policies and its `existingSchemas`.\n */\nexport function filterIssuesByOwnership(\n issues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n ownedSchemaNameSet: ReadonlySet<string>,\n): readonly SchemaDiffIssue<SqlSchemaDiffNode>[] {\n return issues.filter((i) => {\n if (i.outcome !== 'extra') return true;\n if (i.actual === undefined) return false;\n return PostgresPolicySchemaNode.is(i.actual) && ownedSchemaNameSet.has(i.actual.namespaceId);\n });\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { ControlPolicySubject } from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { entityAt, UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage, StorageTable } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { isPostgresSchema } from '../postgres-schema';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\n\n/**\n * Factory calls that create a whole, previously-absent top-level storage\n * object. Used to decide whether `tolerated` permits a call (it only allows\n * creating absent objects, never modifying existing ones).\n *\n * Deliberately an explicit, closed set rather than a `factoryName`\n * create/alter/drop classification: it answers exactly one yes/no question\n * and is fail-closed. Any call not listed here — including future or\n * extension-contributed factories — is treated as NOT object-creation, so it\n * is suppressed under `tolerated` rather than permissively emitted.\n */\nconst OBJECT_CREATION_FACTORIES: ReadonlySet<string> = new Set<string>([\n 'createTable',\n 'createSchema',\n 'createRlsPolicy',\n 'enableRowLevelSecurity',\n]);\n\nfunction createsNewTopLevelObject(call: PostgresOpFactoryCall): boolean {\n return OBJECT_CREATION_FACTORIES.has(call.factoryName);\n}\n\nfunction ddlSchemaNameForNamespace(contract: Contract<SqlStorage>, namespaceId: string): string {\n const namespace = contract.storage.namespaces[namespaceId];\n return isPostgresSchema(namespace) ? namespace.ddlSchemaName(contract.storage) : namespaceId;\n}\n\nfunction resolveNamespaceIdForTable(\n contract: Contract<SqlStorage>,\n tableName: string,\n ddlSchemaName: string | undefined,\n): string {\n for (const namespaceId of Object.keys(contract.storage.namespaces)) {\n const table = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: tableName,\n });\n if (!table) continue;\n if (\n ddlSchemaName === undefined ||\n ddlSchemaNameForNamespace(contract, namespaceId) === ddlSchemaName\n ) {\n return namespaceId;\n }\n }\n return UNBOUND_NAMESPACE_ID;\n}\n\nfunction resolveNamespaceIdForDdlSchema(\n contract: Contract<SqlStorage>,\n ddlSchemaName: string,\n): string {\n for (const namespaceId of Object.keys(contract.storage.namespaces)) {\n const ns = contract.storage.namespaces[namespaceId];\n if (isPostgresSchema(ns) && ns.ddlSchemaName(contract.storage) === ddlSchemaName) {\n return namespaceId;\n }\n if (namespaceId === ddlSchemaName) {\n return namespaceId;\n }\n }\n return UNBOUND_NAMESPACE_ID;\n}\n\ninterface PostgresCallFields {\n readonly schemaName?: string;\n readonly tableName?: string;\n readonly columnName?: string;\n}\n\nfunction postgresCallFields(call: PostgresOpFactoryCall): PostgresCallFields {\n return {\n ...ifDefined('schemaName', 'schemaName' in call ? call.schemaName : undefined),\n ...ifDefined('tableName', 'tableName' in call ? call.tableName : undefined),\n ...ifDefined('columnName', 'columnName' in call ? call.columnName : undefined),\n };\n}\n\nexport function formatPostgresControlPolicySubjectLabel(\n factoryName: string,\n subject: ControlPolicySubject | undefined,\n contract: Contract<SqlStorage>,\n): string {\n if (subject?.table) {\n const ddlSchema = ddlSchemaNameForNamespace(contract, subject.namespaceId);\n return `${factoryName}(${ddlSchema}.${subject.table})`;\n }\n return factoryName;\n}\n\nexport function resolvePostgresCallControlPolicySubject(\n call: PostgresOpFactoryCall,\n contract: Contract<SqlStorage>,\n): ControlPolicySubject | undefined {\n const callFields = postgresCallFields(call);\n const createsNewObject = createsNewTopLevelObject(call);\n\n if (call.factoryName === 'createSchema' && callFields.schemaName) {\n return {\n namespaceId: resolveNamespaceIdForDdlSchema(contract, callFields.schemaName),\n createsNewObject,\n };\n }\n\n if (callFields.tableName) {\n const namespaceId = resolveNamespaceIdForTable(\n contract,\n callFields.tableName,\n callFields.schemaName,\n );\n const tableControlPolicy = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: callFields.tableName,\n })?.control;\n return {\n namespaceId,\n ...ifDefined('explicitNodeControlPolicy', tableControlPolicy),\n table: callFields.tableName,\n ...ifDefined('column', callFields.columnName),\n createsNewObject,\n };\n }\n\n if (callFields.schemaName) {\n return {\n namespaceId: resolveNamespaceIdForDdlSchema(contract, callFields.schemaName),\n createsNewObject,\n };\n }\n\n return undefined;\n}\n\n/**\n * Issue kinds that describe the absence of a whole, top-level Postgres\n * object — the same kinds `createsNewTopLevelObject` recognises for calls.\n * Used by {@link resolvePostgresIssueCreationFactoryName} to decide whether\n * a `tolerated` subject permits the issue to flow into the planner\n * (create-if-absent) and to seed the suppressed-subject warning's\n * `factoryName` when the planner is skipped.\n */\nconst POSTGRES_ISSUE_CREATION_FACTORY: Readonly<Record<string, string>> = Object.freeze({\n missing_schema: 'createSchema',\n missing_table: 'createTable',\n missing_rls_policy: 'createRlsPolicy',\n});\n\nexport function resolvePostgresIssueCreationFactoryName(issue: SchemaIssue): string | undefined {\n return POSTGRES_ISSUE_CREATION_FACTORY[issue.kind];\n}\n\n/**\n * Resolve the control-policy subject coordinate for a single\n * {@link SchemaIssue}. Mirrors the resolution `resolvePostgresCallControlPolicySubject`\n * performs for a generated DDL call, but works *off the issue* — so the\n * planner can partition issues by effective policy before the diff engine\n * runs. `createsNewObject` is derived from the issue's kind: schema/table/\n * type-missing issues describe a brand-new top-level object; everything else\n * touches an existing object.\n *\n * An `extra_table` issue carries no contract namespace coordinate (the table\n * isn't in any contract namespace), so the subject's `namespaceId` falls\n * back to {@link UNBOUND_NAMESPACE_ID}; the call-side resolver does the same\n * for the `DropTableCall` it produces.\n */\nexport function resolvePostgresIssueControlPolicySubject(\n issue: SchemaIssue,\n contract: Contract<SqlStorage>,\n): ControlPolicySubject | undefined {\n const createsNewObject = POSTGRES_ISSUE_CREATION_FACTORY[issue.kind] !== undefined;\n\n if (issue.kind === 'missing_schema' && issue.namespaceId) {\n return { namespaceId: issue.namespaceId, createsNewObject };\n }\n\n if ('table' in issue && issue.table) {\n const namespaceId =\n 'namespaceId' in issue && issue.namespaceId\n ? issue.namespaceId\n : resolveNamespaceIdForTable(contract, issue.table, undefined);\n const table = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: issue.table,\n });\n return {\n namespaceId,\n ...ifDefined('explicitNodeControlPolicy', table?.control),\n table: issue.table,\n ...ifDefined('column', 'column' in issue ? issue.column : undefined),\n createsNewObject,\n };\n }\n\n return undefined;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport { DEFAULT_NAMESPACE_ID } from '../namespace-ids';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\n\n/**\n * Resolves the live-database schema name for a given namespace\n * coordinate. Mirrors `resolveDdlSchemaForNamespace` in\n * `planner-strategies.ts` so the verifier's projection and the\n * planner's projection always agree — Postgres-aware namespaces (the\n * production path) dispatch to `ddlSchemaName(storage)`, and bare\n * object payloads (used by some tests) fall back to the coordinate\n * itself.\n */\nfunction resolveDdlSchemaName(storage: SqlStorage, namespaceId: string): string {\n const namespace = storage.namespaces[namespaceId];\n if (isPostgresSchema(namespace)) {\n return namespace.ddlSchemaName(storage);\n }\n return namespaceId;\n}\n\n/**\n * Reads the introspected list of schema names from the database-root schema\n * node. `existingSchemas` is database-level, so it lives on the\n * `PostgresDatabaseSchemaNode` root — not on the per-schema namespace nodes.\n *\n * Defaults to the always-present `public` schema when the node is not the\n * database root — a fresh Postgres database always carries `public` (unless an\n * operator dropped it manually), so any verifier path that runs without an\n * enriched introspection still suppresses the redundant `CREATE SCHEMA\n * \"public\"`.\n *\n * Production introspection (`PostgresControlAdapter.introspect`) is the\n * authoritative source: it queries `pg_namespace` and sets `existingSchemas`\n * on the returned root. Tests that want to assert against a richer initial\n * state construct a `PostgresDatabaseSchemaNode` explicitly.\n */\nfunction existingSchemasFromSchema(schema: SqlSchemaIRNode): readonly string[] {\n if (PostgresDatabaseSchemaNode.is(schema)) {\n return schema.existingSchemas;\n }\n return [DEFAULT_NAMESPACE_ID];\n}\n\n/**\n * Emits a `missing_schema` issue for every contract-declared Postgres\n * namespace whose live container does not yet exist. The planner's\n * `collectSchemaIssues` prepends these to the relational findings so a\n * multi-schema plan emits `CREATE SCHEMA` before the tables that need it —\n * a planner-only concern (verify already rejects via the `missing_table` a\n * missing schema produces), so this is not part of the shared diff.\n *\n * A namespace's live container is the schema returned by its\n * polymorphic `ddlSchemaName(storage)` method — named schemas resolve\n * to their own id; the unbound singleton returns `UNBOUND_NAMESPACE_ID`\n * and is skipped explicitly (late-bound namespaces have no fixed DDL\n * schema). Issues are emitted only when the resolved name is a real,\n * creatable schema (not the unbound sentinel) and is missing from the\n * introspected list. `public` is suppressed implicitly because the\n * introspection (or its sensible default) always carries it.\n *\n * Each emitted issue stamps `namespaceId` with the contract namespace\n * coordinate so the downstream `mapIssueToCall` re-resolves the DDL\n * schema name through the same polymorphic path — keeping the\n * coordinate, not the resolved name, as the issue's stable identity.\n */\nexport function verifyPostgresNamespacePresence(input: {\n readonly contract: Contract<SqlStorage>;\n readonly schema: SqlSchemaIRNode;\n}): readonly SchemaIssue[] {\n const { contract, schema } = input;\n const existing = new Set(existingSchemasFromSchema(schema));\n const issues: SchemaIssue[] = [];\n const namespaceIds = Object.keys(contract.storage.namespaces).sort();\n for (const namespaceId of namespaceIds) {\n if (namespaceId === UNBOUND_NAMESPACE_ID) continue;\n const ddlName = resolveDdlSchemaName(contract.storage, namespaceId);\n if (ddlName === UNBOUND_NAMESPACE_ID) continue;\n if (existing.has(ddlName)) continue;\n issues.push({\n kind: 'missing_schema',\n reason: 'not-found',\n namespaceId,\n message: `Schema \"${ddlName}\" is missing from database`,\n });\n }\n return issues;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlMigrationPlannerPlanOptions,\n SqlPlannerConflict,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport {\n extractCodecControlHooks,\n partitionCallsByControlPolicy,\n partitionIssuesByControlPolicy,\n planFieldEventOperations,\n plannerFailure,\n} from '@prisma-next/family-sql/control';\nimport type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n SchemaDiffIssue,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { PostgresRlsPolicy } from '../postgres-rls-policy';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresPolicySchemaNode } from '../schema-ir/postgres-policy-schema-node';\nimport type { SqlSchemaDiffNode } from '../schema-ir/schema-node-kinds';\nimport {\n formatPostgresControlPolicySubjectLabel,\n resolvePostgresCallControlPolicySubject,\n resolvePostgresIssueControlPolicySubject,\n resolvePostgresIssueCreationFactoryName,\n} from './control-policy';\nimport { diffPostgresDatabaseSchema } from './diff-database-schema';\nimport { planIssues } from './issue-planner';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\nimport {\n CreatePostgresRlsPolicyCall,\n DropPostgresRlsPolicyCall,\n EnableRowLevelSecurityCall,\n} from './op-factory-call';\nimport { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';\nimport { postgresPlannerStrategies } from './planner-strategies';\nimport { resolveDdlSchemaForNamespaceStorage } from './resolve-ddl-schema';\nimport { verifyPostgresNamespacePresence } from './verify-postgres-namespaces';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\nexport function createPostgresMigrationPlanner(\n lowerer: ExecuteRequestLowerer,\n): PostgresMigrationPlanner {\n return new PostgresMigrationPlanner(lowerer);\n}\n\n/**\n * Result of `PostgresMigrationPlanner.plan()`. A discriminated union whose\n * success variant carries a `TypeScriptRenderablePostgresMigration` — a\n * migration object that both the CLI (via `renderTypeScript()`) and the\n * SQL-typed callers (via `operations`, `describe()`, etc.) consume\n * uniformly.\n */\nexport type PostgresPlanResult =\n | {\n readonly kind: 'success';\n readonly plan: TypeScriptRenderablePostgresMigration;\n readonly warnings?: readonly SqlPlannerConflict[];\n }\n | SqlPlannerFailureResult;\n\n/**\n * Postgres migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the unified\n * `postgresPlannerStrategies` list: enum-change, NOT-NULL backfill,\n * type-change, nullable-tightening, codec-hook storage types,\n * component-declared dependency installs, and shared-temp-default /\n * empty-table-guarded NOT-NULL add-column. The same strategy list runs for\n * `migration plan`, `db update`, and `db init`; behavior diverges purely on\n * `policy.allowedOperationClasses` (the data-safe strategies short-circuit\n * when `'data'` is excluded). The issue planner applies operation-class\n * policy gates and emits a single `PostgresOpFactoryCall[]` that drives both\n * the runtime-ops view (via `renderOps`) and the `renderTypeScript()`\n * authoring surface.\n */\nexport class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgres'> {\n readonly #lowerer: ExecuteRequestLowerer | undefined;\n\n constructor(lowerer?: ExecuteRequestLowerer) {\n this.#lowerer = lowerer;\n }\n\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts\n * at), or `null` for reconciliation flows. Only `migration plan` ever\n * supplies a non-null value; `db update` / `db init` reconcile against\n * the live schema and pass `null`. When present alongside the\n * `'data'` operation class, strategies that need from/to column-shape\n * comparisons (unsafe type change, nullability tightening) activate.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly schemaName?: string;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n /**\n * Contract space this plan applies to. Stamped onto the produced\n * {@link TypeScriptRenderablePostgresMigration.spaceId} so the runner keys\n * the marker row by the right space.\n */\n readonly spaceId: string;\n }): PostgresPlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(\n context: MigrationScaffoldContext,\n spaceId: string,\n ): MigrationPlanWithAuthoringSurface {\n return new TypeScriptRenderablePostgresMigration(\n [],\n {\n from: context.fromHash,\n to: context.toHash,\n },\n spaceId,\n this.#lowerer,\n );\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): PostgresPlanResult {\n const schemaName =\n options.schemaName ??\n Object.keys(options.contract.storage.namespaces).find((id) => id !== UNBOUND_NAMESPACE_ID) ??\n UNBOUND_NAMESPACE_ID;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n // One combined database-schema diff drives the whole plan: the relational\n // findings (+ namespace presence) become structural DDL via `planIssues`,\n // the policy findings become RLS ops via `planPostgresSchemaDiff`. Verify\n // runs the same underlying comparison (via `verifyDatabaseSchema`) and\n // rejects on non-empty. The caller-supplied `keepDiffIssue` predicate is\n // applied blindly — any scoping (e.g. multi-space ownership) is the\n // orchestration's, never worked out here.\n PostgresDatabaseSchemaNode.assert(options.schema);\n const rawDiff = diffPostgresDatabaseSchema({\n contract: options.contract,\n actualSchema: options.schema,\n strict:\n options.policy.allowedOperationClasses.includes('widening') ||\n options.policy.allowedOperationClasses.includes('destructive'),\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n });\n const databaseDiff = options.keepDiffIssue ? rawDiff.filter(options.keepDiffIssue) : rawDiff;\n const schemaIssues = this.collectSchemaIssues(options, databaseDiff.issues);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n // The strategy layer reads the live schema by bare table name for existence\n // checks (shared-temp-default safety, FK/unique probes), so it takes one\n // per-schema namespace node — never the whole tree root, and never a flat\n // merge of every namespace (which would collide same-named tables across\n // schemas). Probing more than one namespace at once is future work.\n const relationalSchema = relationalNamespaceNode(options.schema, schemaName);\n\n // Input-side control-policy partition. `external` / `observed` subjects\n // — and non-creation issues for `tolerated` subjects — are dropped from\n // the planner's input entirely; the planner never observes them, never\n // diffs them, never generates DDL for them. Suppression warnings are\n // built directly from the suppressed partition (one per subject), so the\n // user-visible message survives even when the planner would have failed\n // to model the subject's live shape.\n const issuePartition = partitionIssuesByControlPolicy({\n issues: schemaIssues,\n contract: options.contract,\n resolveControlPolicySubject: (issue) =>\n resolvePostgresIssueControlPolicySubject(issue, options.contract),\n resolveCreationFactoryName: resolvePostgresIssueCreationFactoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n\n const result = planIssues({\n issues: issuePartition.plannable,\n toContract: options.contract,\n // `fromContract` is only supplied by `migration plan`. It is `null` for\n // `db update` / `db init`, which means data-safety strategies needing\n // from/to comparisons (unsafe type change, nullable tightening) are\n // inapplicable there — reconciliation falls through to\n // `mapIssueToCall`'s direct destructive handlers.\n fromContract: options.fromContract,\n schemaName,\n codecHooks,\n storageTypes,\n ...ifDefined('schema', relationalSchema),\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: postgresPlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n const schemaDiffCalls = this.planPostgresSchemaDiff(options, databaseDiff.schemaDiffIssues);\n const schemaDiffPartition = partitionCallsByControlPolicy({\n calls: schemaDiffCalls,\n contract: options.contract,\n resolveControlPolicySubject: (call) =>\n resolvePostgresCallControlPolicySubject(call, options.contract),\n resolveFactoryName: (call) => call.factoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n\n // Inline `onFieldEvent`-emitted ops after structural DDL. The fixed\n // ordering is `structural → added → dropped → altered`, with\n // within-group sorting by `(tableName, fieldName)` so re-emits are\n // byte-stable. The hook fires only at the application emitter —\n // extension-space planning never reaches this helper.\n const fieldEventOps = planFieldEventOperations({\n priorContract: options.fromContract,\n newContract: options.contract,\n codecHooks,\n });\n // Codec hook ops are target-agnostic `OpFactoryCall`; Postgres planning\n // lifts them at this integration boundary (see field-event-planner JSDoc).\n const fieldEventPostgresCalls = blindCast<\n readonly PostgresOpFactoryCall[],\n 'Codec hook ops conform to PostgresOpFactoryCall at the app emitter boundary'\n >(fieldEventOps);\n const fieldEventPartition = partitionCallsByControlPolicy({\n calls: fieldEventPostgresCalls,\n contract: options.contract,\n resolveControlPolicySubject: (call) =>\n resolvePostgresCallControlPolicySubject(call, options.contract),\n resolveFactoryName: (call) => call.factoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n const calls = [...result.value.calls, ...schemaDiffPartition.kept, ...fieldEventPartition.kept];\n const warnings: SqlPlannerConflict[] = [\n ...issuePartition.warnings,\n ...schemaDiffPartition.warnings,\n ...fieldEventPartition.warnings,\n ];\n\n return Object.freeze({\n kind: 'success' as const,\n plan: new TypeScriptRenderablePostgresMigration(\n calls,\n {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n },\n options.spaceId,\n this.#lowerer,\n ),\n ...(warnings.length > 0 ? { warnings: Object.freeze(warnings) } : {}),\n });\n }\n\n /**\n * Maps the RLS policy presence findings of the shared\n * `diffPostgresDatabaseSchema` (already ownership-filtered) into\n * `ENABLE RLS` / `CREATE POLICY` / `DROP POLICY` ops. It no longer re-diffs —\n * it consumes the `schemaDiffIssues` of the one combined diff.\n */\n private planPostgresSchemaDiff(\n options: PlannerOptionsWithComponents,\n filteredDiffIssues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n ): readonly PostgresOpFactoryCall[] {\n const allowsDestructive = options.policy.allowedOperationClasses.includes('destructive');\n const calls: PostgresOpFactoryCall[] = [];\n const seenEnableTables = new Set<string>();\n\n for (const issue of filteredDiffIssues) {\n // 'mismatch' is unreachable for content-addressed policies: the wire name\n // encodes the body hash, so two policies sharing a local key (same name)\n // are always equal and isEqualTo never returns false.\n if (issue.outcome === 'missing') {\n const expected = issue.expected;\n PostgresPolicySchemaNode.assert(expected);\n // expected.namespaceId is the DDL schema name (resolved during projection);\n // this re-resolution is a no-op as long as PostgresSchema.ddlSchemaName() returns this.id.\n const schemaForTable = resolveDdlSchemaForNamespaceStorage(\n options.contract.storage,\n expected.namespaceId,\n );\n const tableKey = `${schemaForTable}.${expected.tableName}`;\n if (!seenEnableTables.has(tableKey)) {\n seenEnableTables.add(tableKey);\n calls.push(new EnableRowLevelSecurityCall(schemaForTable, expected.tableName));\n }\n calls.push(\n new CreatePostgresRlsPolicyCall(\n schemaForTable,\n expected.tableName,\n policyNodeToContractPolicy(expected),\n ),\n );\n } else if (issue.outcome === 'extra' && allowsDestructive) {\n const actual = issue.actual;\n PostgresPolicySchemaNode.assert(actual);\n const schemaForTable = resolveDdlSchemaForNamespaceStorage(\n options.contract.storage,\n actual.namespaceId,\n );\n calls.push(new DropPostgresRlsPolicyCall(schemaForTable, actual.tableName, actual.name));\n }\n }\n\n return calls;\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n /**\n * The structural issue list `planIssues` consumes: the relational findings\n * from the shared `diffPostgresDatabaseSchema` plus namespace presence.\n *\n * Schema presence (`missing_schema` → `CREATE SCHEMA`) is a planner-only\n * op-generation concern, so it is stitched in here rather than inside the\n * shared diff — verify never needs it (a missing schema already surfaces as\n * `missing_table` in the relational findings). It reads `existingSchemas` off\n * the database root, so it takes the whole tree. Policy drift is handled\n * separately via `planPostgresSchemaDiff` from the same shared diff's\n * `schemaDiffIssues`.\n */\n private collectSchemaIssues(\n options: PlannerOptionsWithComponents,\n relationalIssues: readonly SchemaIssue[],\n ): readonly SchemaIssue[] {\n const namespaceIssues = verifyPostgresNamespacePresence({\n contract: options.contract,\n schema: options.schema,\n });\n if (namespaceIssues.length === 0) {\n return relationalIssues;\n }\n return [...namespaceIssues, ...relationalIssues];\n }\n}\n\n/**\n * Returns the one namespace node whose tables the relational strategy layer\n * probes for live-table existence — the node matching the planner's resolved\n * schema name, or the first namespace when none matches. `undefined` when the\n * tree has no namespaces, so the strategy context uses its empty-schema default.\n *\n * The relational strategies key tables by bare name, so they can only probe one\n * namespace at a time; probing across every namespace at once is future work.\n */\nfunction relationalNamespaceNode(\n schema: PostgresDatabaseSchemaNode,\n schemaName: string,\n): SqlSchemaIR | undefined {\n const namespaceNodes = Object.values(schema.namespaces);\n const byName = namespaceNodes.find((node) => node.schemaName === schemaName);\n return byName ?? namespaceNodes[0];\n}\n\n/**\n * Rebuilds the `PostgresRlsPolicy` contract entity `CreatePostgresRlsPolicyCall`\n * carries (its `renderTypeScript`/`createRlsPolicy` paths serialize the whole\n * entity, `namespaceId` included). This reconstructs rather than looking the\n * original up in the contract on purpose: the diff node's `namespaceId` is the\n * *resolved DDL schema* (set when the expected tree was built), which is the\n * value the emitted op must carry; the contract-stored entity holds the raw,\n * pre-resolution coordinate, so a lookup would change the migration output.\n */\nfunction policyNodeToContractPolicy(node: PostgresPolicySchemaNode): PostgresRlsPolicy {\n return new PostgresRlsPolicy({\n name: node.name,\n prefix: node.prefix,\n tableName: node.tableName,\n namespaceId: node.namespaceId,\n operation: node.operation,\n roles: [...node.roles],\n ...ifDefined('using', node.using),\n ...ifDefined('withCheck', node.withCheck),\n permissive: node.permissive,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,SAAS,aAAa,QAA2B,aAA+C;CAC9F,OAAO,IAAI,yBAAyB;EAClC,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB;EACA,WAAW,OAAO;EAClB,OAAO,CAAC,GAAG,OAAO,KAAK;EACvB,GAAG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Bq0Z2sVO.mjs","names":["#lowerer"],"sources":["../src/core/migrations/contract-to-postgres-database-schema-node.ts","../src/core/migrations/diff-database-schema.ts","../src/core/migrations/control-policy.ts","../src/core/migrations/verify-postgres-namespaces.ts","../src/core/migrations/planner.ts"],"sourcesContent":["import type { ContractToSchemaIROptions } from '@prisma-next/family-sql/control';\nimport { contractNamespaceToSchemaIR } from '@prisma-next/family-sql/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { PostgresRlsPolicy } from '../postgres-rls-policy';\nimport type { PostgresContract } from '../postgres-schema';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresNamespaceSchemaNode } from '../schema-ir/postgres-namespace-schema-node';\nimport { PostgresPolicySchemaNode } from '../schema-ir/postgres-policy-schema-node';\nimport { PostgresRoleSchemaNode } from '../schema-ir/postgres-role-schema-node';\nimport { PostgresTableSchemaNode } from '../schema-ir/postgres-table-schema-node';\nimport { resolveDdlSchemaForNamespaceStorage } from './resolve-ddl-schema';\n\nfunction toPolicyNode(policy: PostgresRlsPolicy, namespaceId: string): PostgresPolicySchemaNode {\n return new PostgresPolicySchemaNode({\n name: policy.name,\n prefix: policy.prefix,\n tableName: policy.tableName,\n namespaceId,\n operation: policy.operation,\n roles: [...policy.roles],\n ...ifDefined('using', policy.using),\n ...ifDefined('withCheck', policy.withCheck),\n permissive: policy.permissive,\n });\n}\n\n/**\n * Projects a Postgres contract into the expected schema-diff tree: a\n * `PostgresDatabaseSchemaNode` root holding one `PostgresNamespaceSchemaNode`\n * per Postgres namespace, each holding its `PostgresTableSchemaNode`s with\n * their `PostgresPolicySchemaNode`s, plus the database roles on the root.\n *\n * Not a duplicate of the family's `contractToSchemaIR`: that builds a flat,\n * single `{ tables }` map (and throws on cross-namespace name collisions, with\n * no RLS/role concept) for SQLite's single-schema world. This is the\n * Postgres-specific *tree* shape — multi-schema, RLS-policy-aware, role-aware.\n * It reuses the family's per-namespace table conversion (`contractNamespaceToSchemaIR`)\n * for column/FK/index building and only adds the Postgres tree/policy/role shape.\n *\n * Tables are grouped by their owning namespace (resolved DDL schema name) so\n * the tree mirrors Postgres's object hierarchy. The DDL schema name is\n * resolved once per namespace.\n *\n * A policy that references a table absent from its namespace is a malformed\n * contract — the loop throws rather than fabricating a stub table.\n */\nexport function contractToPostgresDatabaseSchemaNode(\n contract: PostgresContract | null,\n options: ContractToSchemaIROptions,\n): PostgresDatabaseSchemaNode {\n if (contract === null) {\n return new PostgresDatabaseSchemaNode({\n namespaces: {},\n roles: [],\n existingSchemas: [],\n pgVersion: '',\n });\n }\n\n const namespaces: Record<string, PostgresNamespaceSchemaNode> = {};\n const roles: PostgresRoleSchemaNode[] = [];\n const ownedSchemas: string[] = [];\n\n for (const ns of Object.values(contract.storage.namespaces)) {\n if (!isPostgresSchema(ns)) continue;\n const ddlSchema = resolveDdlSchemaForNamespaceStorage(contract.storage, ns.id);\n ownedSchemas.push(ddlSchema);\n\n // Convert only THIS namespace's tables (passing the full storage for\n // type/value-set/enum resolution that spans namespaces), so the same table\n // name can exist in two schemas without colliding in a bare-keyed record.\n const sqlTables = contractNamespaceToSchemaIR(contract.storage, ns.id, options).tables;\n\n const policiesByTable = new Map<string, PostgresPolicySchemaNode[]>();\n for (const policy of Object.values(ns.policy)) {\n const list = policiesByTable.get(policy.tableName) ?? [];\n list.push(toPolicyNode(policy, ddlSchema));\n policiesByTable.set(policy.tableName, list);\n }\n\n const tables: Record<string, PostgresTableSchemaNode> = {};\n for (const tableName of Object.keys(ns.table)) {\n const sqlTable = sqlTables[tableName];\n if (sqlTable === undefined) continue;\n tables[tableName] = new PostgresTableSchemaNode({\n name: sqlTable.name,\n columns: sqlTable.columns,\n foreignKeys: sqlTable.foreignKeys,\n uniques: sqlTable.uniques,\n indexes: sqlTable.indexes,\n ...ifDefined('primaryKey', sqlTable.primaryKey),\n ...ifDefined('annotations', sqlTable.annotations),\n ...ifDefined('checks', sqlTable.checks),\n policies: policiesByTable.get(tableName) ?? [],\n });\n }\n\n for (const [tableName, tablePolicies] of policiesByTable) {\n if (!(tableName in tables)) {\n const policyName = tablePolicies[0]?.name ?? '(unknown)';\n throw new Error(\n `contract-to-postgres-database-schema-node: policy \"${policyName}\" references table \"${tableName}\" not present in namespace \"${ddlSchema}\"`,\n );\n }\n }\n\n namespaces[ddlSchema] = new PostgresNamespaceSchemaNode({\n schemaName: ddlSchema,\n tables,\n nativeEnumTypeNames: [],\n });\n\n for (const role of Object.values(ns.role)) {\n roles.push(new PostgresRoleSchemaNode({ name: role.name, namespaceId: role.namespaceId }));\n }\n }\n\n return new PostgresDatabaseSchemaNode({\n namespaces,\n roles,\n existingSchemas: ownedSchemas,\n pgVersion: '',\n });\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport { verifySqlSchemaTree } from '@prisma-next/family-sql/diff';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n SchemaDiffIssue,\n VerifyDatabaseSchemaResult,\n} from '@prisma-next/framework-components/control';\nimport { diffSchemas, SchemaDiff } from '@prisma-next/framework-components/control';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport type { PostgresContract } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresPolicySchemaNode } from '../schema-ir/postgres-policy-schema-node';\nimport type { SqlSchemaDiffNode } from '../schema-ir/schema-node-kinds';\nimport { contractToPostgresDatabaseSchemaNode } from './contract-to-postgres-database-schema-node';\n\ninterface PostgresDiffDatabaseSchemaInput {\n readonly contract: Contract<SqlStorage>;\n readonly actualSchema: SqlSchemaIRNode;\n readonly strict: boolean;\n readonly typeMetadataRegistry: ReadonlyMap<string, { readonly nativeType?: string }>;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n}\n\n/**\n * The single combined database-schema comparison — the one computation the\n * migration planner and the family schema verify both consume. Composes,\n * once each:\n *\n * - the per-namespace-paired relational diff (`verifySqlSchemaTree`) → table /\n * column / constraint findings as framework `SchemaIssue`s (with the\n * verification-tree `root` and pass/warn/fail counts);\n * - the policy diff (`diffPostgresSchema` over the two trees) → RLS policy\n * presence as `SchemaDiffIssue`s, ownership-filtered to the contract's owned\n * schemas.\n *\n * `diffPostgresDatabaseSchema` and `verifyPostgresDatabaseSchema` both read\n * this single result, so the relational walk runs once per caller — never\n * once for the diff and again for the verify tree.\n */\nfunction computePostgresSchemaComparison(input: PostgresDiffDatabaseSchemaInput): {\n readonly relational: VerifyDatabaseSchemaResult;\n readonly schemaDiffIssues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[];\n} {\n const postgresContract = blindCast<\n PostgresContract,\n 'diffPostgresDatabaseSchema is only called with a postgres contract'\n >(input.contract);\n\n // Relational diff: per-namespace-paired so a multi-schema database checks each\n // contract namespace against its own actual node.\n const relational = verifySqlSchemaTree({\n contract: input.contract,\n actualSchema: input.actualSchema,\n buildExpectedSchema: (scopedContract) =>\n contractToPostgresDatabaseSchemaNode(\n blindCast<\n PostgresContract | null,\n 'the relational pairing projects a scoped postgres contract'\n >(scopedContract),\n { annotationNamespace: 'pg' },\n ),\n strict: input.strict,\n typeMetadataRegistry: input.typeMetadataRegistry,\n frameworkComponents: input.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n\n // Policy diff: the generic node differ over the expected/actual policy trees,\n // ownership-filtered to the schemas the contract owns (so unowned-namespace\n // policies are not reported as extras). The actual schema is always the\n // Postgres database root in production — assert it, matching the prior\n // `collectSchemaDiffIssues` / `planPostgresSchemaDiff` behaviour.\n PostgresDatabaseSchemaNode.assert(input.actualSchema);\n const expected = contractToPostgresDatabaseSchemaNode(postgresContract, {\n annotationNamespace: 'pg',\n });\n const schemaDiffIssues = filterIssuesByOwnership(\n diffPostgresSchema(expected, input.actualSchema),\n ownedSchemaNames(expected),\n );\n\n return { relational, schemaDiffIssues };\n}\n\n/**\n * The `SchemaDiffer` for Postgres: the target's black-box comparison,\n * projected to the two issue lists. Namespace presence (`missing_schema` →\n * `CREATE SCHEMA`) is intentionally NOT composed here: it is a planner-only\n * op-generation concern (verify rejects on the relational `missing_table` a\n * missing schema already produces), so the planner stitches it in around this\n * diff. Control-policy suppression of the policy issues is likewise a\n * per-consumer post-step (verify filters the issues; the planner filters the\n * calls).\n */\nexport function diffPostgresDatabaseSchema(\n input: PostgresDiffDatabaseSchemaInput,\n): SchemaDiff<SqlSchemaDiffNode> {\n const { relational, schemaDiffIssues } = computePostgresSchemaComparison(input);\n return new SchemaDiff(relational.schema.issues, schemaDiffIssues);\n}\n\n/**\n * The same combined comparison as {@link diffPostgresDatabaseSchema}, wrapped\n * in the verify envelope (`ok`/`summary`/`code`/`target`/`timings`) plus the\n * pass/warn/fail tree the CLI renders — i.e. exactly the existing verify-result\n * schema shape, so nothing downstream changes.\n */\nexport function verifyPostgresDatabaseSchema(\n input: PostgresDiffDatabaseSchemaInput,\n): VerifyDatabaseSchemaResult {\n const { relational, schemaDiffIssues } = computePostgresSchemaComparison(input);\n return {\n ...relational,\n schema: { ...relational.schema, schemaDiffIssues },\n };\n}\n\nfunction ownedSchemaNames(expected: PostgresDatabaseSchemaNode): ReadonlySet<string> {\n const policyNamespaces = Object.values(expected.namespaces).flatMap((ns) =>\n Object.values(ns.tables).flatMap((t) => t.policies.map((p) => p.namespaceId)),\n );\n return new Set([...policyNamespaces, ...expected.existingSchemas]);\n}\n\n// Renders a display-only reference string for the diff message. If policy\n// rendering grows, route it through the adapter's SQL renderer so the message\n// can't diverge from the emitted policy SQL.\nfunction renderPostgresPolicyReference(policy: PostgresPolicySchemaNode): string {\n return `policy \"${policy.name}\" on \"${policy.namespaceId}\".\"${policy.tableName}\"`;\n}\n\n/**\n * The policy node-diff — the structural half of the combined comparison above.\n * Computes RLS-policy drift between two derived schema trees:\n *\n * 1. Runs the framework total diff over the two `PostgresDatabaseSchemaNode`\n * roots (database → namespace → table → policy).\n * 2. Filters to policy-subject issues only — this is transitional: the generic\n * differ walks the whole tree, but the legacy relational verifier still owns\n * table/column drift, so non-policy issues are dropped here.\n * 3. Remaps the message to a human-readable policy reference.\n *\n * Both trees are `PostgresDatabaseSchemaNode`s, so every issue node is a\n * `SqlSchemaDiffNode` — narrow the framework's `SchemaDiffIssue<DiffableNode>`\n * output once here (the single boundary cast), so every downstream consumer\n * (the ownership filter, the planner) reads the concrete node with no cast.\n *\n * Ownership filtering (dropping `extra` issues in namespaces a contract doesn't\n * own) is the caller's responsibility — use `filterIssuesByOwnership`.\n */\nexport function diffPostgresSchema(\n expected: PostgresDatabaseSchemaNode,\n actual: PostgresDatabaseSchemaNode,\n): readonly SchemaDiffIssue<SqlSchemaDiffNode>[] {\n const issues = blindCast<\n readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n 'both trees are PostgresDatabaseSchemaNodes, so every diff-issue node is a SqlSchemaDiffNode'\n >(diffSchemas(expected, actual));\n\n return issues\n .filter((i) => {\n const node = i.expected ?? i.actual;\n return node !== undefined && PostgresPolicySchemaNode.is(node);\n })\n .map((i) => {\n const node = i.expected ?? i.actual;\n if (node === undefined || !PostgresPolicySchemaNode.is(node)) return i;\n return { ...i, message: `${i.outcome}: ${renderPostgresPolicyReference(node)}` };\n });\n}\n\n/**\n * Filters `extra` policy issues to those in owned namespaces. Call after\n * `diffPostgresSchema` with the union of namespace ids from the expected tree's\n * policies and its `existingSchemas`.\n */\nexport function filterIssuesByOwnership(\n issues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n ownedSchemaNameSet: ReadonlySet<string>,\n): readonly SchemaDiffIssue<SqlSchemaDiffNode>[] {\n return issues.filter((i) => {\n if (i.outcome !== 'extra') return true;\n if (i.actual === undefined) return false;\n return PostgresPolicySchemaNode.is(i.actual) && ownedSchemaNameSet.has(i.actual.namespaceId);\n });\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { ControlPolicySubject } from '@prisma-next/family-sql/control';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { entityAt, UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage, StorageTable } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { isPostgresSchema } from '../postgres-schema';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\n\n/**\n * Factory calls that create a whole, previously-absent top-level storage\n * object. Used to decide whether `tolerated` permits a call (it only allows\n * creating absent objects, never modifying existing ones).\n *\n * Deliberately an explicit, closed set rather than a `factoryName`\n * create/alter/drop classification: it answers exactly one yes/no question\n * and is fail-closed. Any call not listed here — including future or\n * extension-contributed factories — is treated as NOT object-creation, so it\n * is suppressed under `tolerated` rather than permissively emitted.\n */\nconst OBJECT_CREATION_FACTORIES: ReadonlySet<string> = new Set<string>([\n 'createTable',\n 'createSchema',\n 'createRlsPolicy',\n 'enableRowLevelSecurity',\n]);\n\nfunction createsNewTopLevelObject(call: PostgresOpFactoryCall): boolean {\n return OBJECT_CREATION_FACTORIES.has(call.factoryName);\n}\n\nfunction ddlSchemaNameForNamespace(contract: Contract<SqlStorage>, namespaceId: string): string {\n const namespace = contract.storage.namespaces[namespaceId];\n return isPostgresSchema(namespace) ? namespace.ddlSchemaName(contract.storage) : namespaceId;\n}\n\nfunction resolveNamespaceIdForTable(\n contract: Contract<SqlStorage>,\n tableName: string,\n ddlSchemaName: string | undefined,\n): string {\n for (const namespaceId of Object.keys(contract.storage.namespaces)) {\n const table = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: tableName,\n });\n if (!table) continue;\n if (\n ddlSchemaName === undefined ||\n ddlSchemaNameForNamespace(contract, namespaceId) === ddlSchemaName\n ) {\n return namespaceId;\n }\n }\n return UNBOUND_NAMESPACE_ID;\n}\n\nfunction resolveNamespaceIdForDdlSchema(\n contract: Contract<SqlStorage>,\n ddlSchemaName: string,\n): string {\n for (const namespaceId of Object.keys(contract.storage.namespaces)) {\n const ns = contract.storage.namespaces[namespaceId];\n if (isPostgresSchema(ns) && ns.ddlSchemaName(contract.storage) === ddlSchemaName) {\n return namespaceId;\n }\n if (namespaceId === ddlSchemaName) {\n return namespaceId;\n }\n }\n return UNBOUND_NAMESPACE_ID;\n}\n\ninterface PostgresCallFields {\n readonly schemaName?: string;\n readonly tableName?: string;\n readonly columnName?: string;\n}\n\nfunction postgresCallFields(call: PostgresOpFactoryCall): PostgresCallFields {\n return {\n ...ifDefined('schemaName', 'schemaName' in call ? call.schemaName : undefined),\n ...ifDefined('tableName', 'tableName' in call ? call.tableName : undefined),\n ...ifDefined('columnName', 'columnName' in call ? call.columnName : undefined),\n };\n}\n\nexport function formatPostgresControlPolicySubjectLabel(\n factoryName: string,\n subject: ControlPolicySubject | undefined,\n contract: Contract<SqlStorage>,\n): string {\n if (subject?.table) {\n const ddlSchema = ddlSchemaNameForNamespace(contract, subject.namespaceId);\n return `${factoryName}(${ddlSchema}.${subject.table})`;\n }\n return factoryName;\n}\n\nexport function resolvePostgresCallControlPolicySubject(\n call: PostgresOpFactoryCall,\n contract: Contract<SqlStorage>,\n): ControlPolicySubject | undefined {\n const callFields = postgresCallFields(call);\n const createsNewObject = createsNewTopLevelObject(call);\n\n if (call.factoryName === 'createSchema' && callFields.schemaName) {\n return {\n namespaceId: resolveNamespaceIdForDdlSchema(contract, callFields.schemaName),\n createsNewObject,\n };\n }\n\n if (callFields.tableName) {\n const namespaceId = resolveNamespaceIdForTable(\n contract,\n callFields.tableName,\n callFields.schemaName,\n );\n const tableControlPolicy = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: callFields.tableName,\n })?.control;\n return {\n namespaceId,\n ...ifDefined('explicitNodeControlPolicy', tableControlPolicy),\n table: callFields.tableName,\n ...ifDefined('column', callFields.columnName),\n createsNewObject,\n };\n }\n\n if (callFields.schemaName) {\n return {\n namespaceId: resolveNamespaceIdForDdlSchema(contract, callFields.schemaName),\n createsNewObject,\n };\n }\n\n return undefined;\n}\n\n/**\n * Issue kinds that describe the absence of a whole, top-level Postgres\n * object — the same kinds `createsNewTopLevelObject` recognises for calls.\n * Used by {@link resolvePostgresIssueCreationFactoryName} to decide whether\n * a `tolerated` subject permits the issue to flow into the planner\n * (create-if-absent) and to seed the suppressed-subject warning's\n * `factoryName` when the planner is skipped.\n */\nconst POSTGRES_ISSUE_CREATION_FACTORY: Readonly<Record<string, string>> = Object.freeze({\n missing_schema: 'createSchema',\n missing_table: 'createTable',\n missing_rls_policy: 'createRlsPolicy',\n});\n\nexport function resolvePostgresIssueCreationFactoryName(issue: SchemaIssue): string | undefined {\n return POSTGRES_ISSUE_CREATION_FACTORY[issue.kind];\n}\n\n/**\n * Resolve the control-policy subject coordinate for a single\n * {@link SchemaIssue}. Mirrors the resolution `resolvePostgresCallControlPolicySubject`\n * performs for a generated DDL call, but works *off the issue* — so the\n * planner can partition issues by effective policy before the diff engine\n * runs. `createsNewObject` is derived from the issue's kind: schema/table/\n * type-missing issues describe a brand-new top-level object; everything else\n * touches an existing object.\n *\n * An `extra_table` issue carries no contract namespace coordinate (the table\n * isn't in any contract namespace), so the subject's `namespaceId` falls\n * back to {@link UNBOUND_NAMESPACE_ID}; the call-side resolver does the same\n * for the `DropTableCall` it produces.\n */\nexport function resolvePostgresIssueControlPolicySubject(\n issue: SchemaIssue,\n contract: Contract<SqlStorage>,\n): ControlPolicySubject | undefined {\n const createsNewObject = POSTGRES_ISSUE_CREATION_FACTORY[issue.kind] !== undefined;\n\n if (issue.kind === 'missing_schema' && issue.namespaceId) {\n return { namespaceId: issue.namespaceId, createsNewObject };\n }\n\n if ('table' in issue && issue.table) {\n const namespaceId =\n 'namespaceId' in issue && issue.namespaceId\n ? issue.namespaceId\n : resolveNamespaceIdForTable(contract, issue.table, undefined);\n const table = entityAt<StorageTable>(contract.storage, {\n namespaceId,\n entityKind: 'table',\n entityName: issue.table,\n });\n return {\n namespaceId,\n ...ifDefined('explicitNodeControlPolicy', table?.control),\n table: issue.table,\n ...ifDefined('column', 'column' in issue ? issue.column : undefined),\n createsNewObject,\n };\n }\n\n return undefined;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type { SchemaIssue } from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport type { SqlSchemaIRNode } from '@prisma-next/sql-schema-ir/types';\nimport { DEFAULT_NAMESPACE_ID } from '../namespace-ids';\nimport { isPostgresSchema } from '../postgres-schema';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\n\n/**\n * Resolves the live-database schema name for a given namespace\n * coordinate. Mirrors `resolveDdlSchemaForNamespace` in\n * `planner-strategies.ts` so the verifier's projection and the\n * planner's projection always agree — Postgres-aware namespaces (the\n * production path) dispatch to `ddlSchemaName(storage)`, and bare\n * object payloads (used by some tests) fall back to the coordinate\n * itself.\n */\nfunction resolveDdlSchemaName(storage: SqlStorage, namespaceId: string): string {\n const namespace = storage.namespaces[namespaceId];\n if (isPostgresSchema(namespace)) {\n return namespace.ddlSchemaName(storage);\n }\n return namespaceId;\n}\n\n/**\n * Reads the introspected list of schema names from the database-root schema\n * node. `existingSchemas` is database-level, so it lives on the\n * `PostgresDatabaseSchemaNode` root — not on the per-schema namespace nodes.\n *\n * Defaults to the always-present `public` schema when the node is not the\n * database root — a fresh Postgres database always carries `public` (unless an\n * operator dropped it manually), so any verifier path that runs without an\n * enriched introspection still suppresses the redundant `CREATE SCHEMA\n * \"public\"`.\n *\n * Production introspection (`PostgresControlAdapter.introspect`) is the\n * authoritative source: it queries `pg_namespace` and sets `existingSchemas`\n * on the returned root. Tests that want to assert against a richer initial\n * state construct a `PostgresDatabaseSchemaNode` explicitly.\n */\nfunction existingSchemasFromSchema(schema: SqlSchemaIRNode): readonly string[] {\n if (PostgresDatabaseSchemaNode.is(schema)) {\n return schema.existingSchemas;\n }\n return [DEFAULT_NAMESPACE_ID];\n}\n\n/**\n * Emits a `missing_schema` issue for every contract-declared Postgres\n * namespace whose live container does not yet exist. The planner's\n * `collectSchemaIssues` prepends these to the relational findings so a\n * multi-schema plan emits `CREATE SCHEMA` before the tables that need it —\n * a planner-only concern (verify already rejects via the `missing_table` a\n * missing schema produces), so this is not part of the shared diff.\n *\n * A namespace's live container is the schema returned by its\n * polymorphic `ddlSchemaName(storage)` method — named schemas resolve\n * to their own id; the unbound singleton returns `UNBOUND_NAMESPACE_ID`\n * and is skipped explicitly (late-bound namespaces have no fixed DDL\n * schema). Issues are emitted only when the resolved name is a real,\n * creatable schema (not the unbound sentinel) and is missing from the\n * introspected list. `public` is suppressed implicitly because the\n * introspection (or its sensible default) always carries it.\n *\n * Each emitted issue stamps `namespaceId` with the contract namespace\n * coordinate so the downstream `mapIssueToCall` re-resolves the DDL\n * schema name through the same polymorphic path — keeping the\n * coordinate, not the resolved name, as the issue's stable identity.\n */\nexport function verifyPostgresNamespacePresence(input: {\n readonly contract: Contract<SqlStorage>;\n readonly schema: SqlSchemaIRNode;\n}): readonly SchemaIssue[] {\n const { contract, schema } = input;\n const existing = new Set(existingSchemasFromSchema(schema));\n const issues: SchemaIssue[] = [];\n const namespaceIds = Object.keys(contract.storage.namespaces).sort();\n for (const namespaceId of namespaceIds) {\n if (namespaceId === UNBOUND_NAMESPACE_ID) continue;\n const ddlName = resolveDdlSchemaName(contract.storage, namespaceId);\n if (ddlName === UNBOUND_NAMESPACE_ID) continue;\n if (existing.has(ddlName)) continue;\n issues.push({\n kind: 'missing_schema',\n reason: 'not-found',\n namespaceId,\n message: `Schema \"${ddlName}\" is missing from database`,\n });\n }\n return issues;\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlMigrationPlannerPlanOptions,\n SqlPlannerConflict,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport {\n extractCodecControlHooks,\n partitionCallsByControlPolicy,\n partitionIssuesByControlPolicy,\n planFieldEventOperations,\n plannerFailure,\n} from '@prisma-next/family-sql/control';\nimport type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n SchemaDiffIssue,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { PostgresRlsPolicy } from '../postgres-rls-policy';\nimport { PostgresDatabaseSchemaNode } from '../schema-ir/postgres-database-schema-node';\nimport { PostgresPolicySchemaNode } from '../schema-ir/postgres-policy-schema-node';\nimport type { SqlSchemaDiffNode } from '../schema-ir/schema-node-kinds';\nimport {\n formatPostgresControlPolicySubjectLabel,\n resolvePostgresCallControlPolicySubject,\n resolvePostgresIssueControlPolicySubject,\n resolvePostgresIssueCreationFactoryName,\n} from './control-policy';\nimport { diffPostgresDatabaseSchema } from './diff-database-schema';\nimport { planIssues } from './issue-planner';\nimport type { PostgresOpFactoryCall } from './op-factory-call';\nimport {\n CreatePostgresRlsPolicyCall,\n DropPostgresRlsPolicyCall,\n EnableRowLevelSecurityCall,\n} from './op-factory-call';\nimport { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';\nimport { postgresPlannerStrategies } from './planner-strategies';\nimport { resolveDdlSchemaForNamespaceStorage } from './resolve-ddl-schema';\nimport { verifyPostgresNamespacePresence } from './verify-postgres-namespaces';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\nexport function createPostgresMigrationPlanner(\n lowerer: ExecuteRequestLowerer,\n): PostgresMigrationPlanner {\n return new PostgresMigrationPlanner(lowerer);\n}\n\n/**\n * Result of `PostgresMigrationPlanner.plan()`. A discriminated union whose\n * success variant carries a `TypeScriptRenderablePostgresMigration` — a\n * migration object that both the CLI (via `renderTypeScript()`) and the\n * SQL-typed callers (via `operations`, `describe()`, etc.) consume\n * uniformly.\n */\nexport type PostgresPlanResult =\n | {\n readonly kind: 'success';\n readonly plan: TypeScriptRenderablePostgresMigration;\n readonly warnings?: readonly SqlPlannerConflict[];\n }\n | SqlPlannerFailureResult;\n\n/**\n * Postgres migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the unified\n * `postgresPlannerStrategies` list: enum-change, NOT-NULL backfill,\n * type-change, nullable-tightening, codec-hook storage types,\n * component-declared dependency installs, and shared-temp-default /\n * empty-table-guarded NOT-NULL add-column. The same strategy list runs for\n * `migration plan`, `db update`, and `db init`; behavior diverges purely on\n * `policy.allowedOperationClasses` (the data-safe strategies short-circuit\n * when `'data'` is excluded). The issue planner applies operation-class\n * policy gates and emits a single `PostgresOpFactoryCall[]` that drives both\n * the runtime-ops view (via `renderOps`) and the `renderTypeScript()`\n * authoring surface.\n */\nexport class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgres'> {\n readonly #lowerer: ExecuteRequestLowerer | undefined;\n\n constructor(lowerer?: ExecuteRequestLowerer) {\n this.#lowerer = lowerer;\n }\n\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts\n * at), or `null` for reconciliation flows. Only `migration plan` ever\n * supplies a non-null value; `db update` / `db init` reconcile against\n * the live schema and pass `null`. When present alongside the\n * `'data'` operation class, strategies that need from/to column-shape\n * comparisons (unsafe type change, nullability tightening) activate.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly schemaName?: string;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n /**\n * Contract space this plan applies to. Stamped onto the produced\n * {@link TypeScriptRenderablePostgresMigration.spaceId} so the runner keys\n * the marker row by the right space.\n */\n readonly spaceId: string;\n }): PostgresPlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(\n context: MigrationScaffoldContext,\n spaceId: string,\n ): MigrationPlanWithAuthoringSurface {\n return new TypeScriptRenderablePostgresMigration(\n [],\n {\n from: context.fromHash,\n to: context.toHash,\n },\n spaceId,\n this.#lowerer,\n );\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): PostgresPlanResult {\n const schemaName =\n options.schemaName ??\n Object.keys(options.contract.storage.namespaces).find((id) => id !== UNBOUND_NAMESPACE_ID) ??\n UNBOUND_NAMESPACE_ID;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n // One combined database-schema diff drives the whole plan: the relational\n // findings (+ namespace presence) become structural DDL via `planIssues`,\n // the policy findings become RLS ops via `planPostgresSchemaDiff`. Verify\n // runs the same underlying comparison (via `verifyDatabaseSchema`) and\n // rejects on non-empty. The caller-supplied `keepDiffIssue` predicate is\n // applied blindly — any scoping (e.g. multi-space ownership) is the\n // orchestration's, never worked out here.\n PostgresDatabaseSchemaNode.assert(options.schema);\n const rawDiff = diffPostgresDatabaseSchema({\n contract: options.contract,\n actualSchema: options.schema,\n strict:\n options.policy.allowedOperationClasses.includes('widening') ||\n options.policy.allowedOperationClasses.includes('destructive'),\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n });\n const databaseDiff = options.keepDiffIssue ? rawDiff.filter(options.keepDiffIssue) : rawDiff;\n const schemaIssues = this.collectSchemaIssues(options, databaseDiff.issues);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n // The strategy layer reads the live schema by bare table name for existence\n // checks (shared-temp-default safety, FK/unique probes), so it takes one\n // per-schema namespace node — never the whole tree root, and never a flat\n // merge of every namespace (which would collide same-named tables across\n // schemas). Probing more than one namespace at once is future work.\n const relationalSchema = relationalNamespaceNode(options.schema, schemaName);\n\n // Input-side control-policy partition. `external` / `observed` subjects\n // — and non-creation issues for `tolerated` subjects — are dropped from\n // the planner's input entirely; the planner never observes them, never\n // diffs them, never generates DDL for them. Suppression warnings are\n // built directly from the suppressed partition (one per subject), so the\n // user-visible message survives even when the planner would have failed\n // to model the subject's live shape.\n const issuePartition = partitionIssuesByControlPolicy({\n issues: schemaIssues,\n contract: options.contract,\n resolveControlPolicySubject: (issue) =>\n resolvePostgresIssueControlPolicySubject(issue, options.contract),\n resolveCreationFactoryName: resolvePostgresIssueCreationFactoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n\n const result = planIssues({\n issues: issuePartition.plannable,\n toContract: options.contract,\n // `fromContract` is only supplied by `migration plan`. It is `null` for\n // `db update` / `db init`, which means data-safety strategies needing\n // from/to comparisons (unsafe type change, nullable tightening) are\n // inapplicable there — reconciliation falls through to\n // `mapIssueToCall`'s direct destructive handlers.\n fromContract: options.fromContract,\n schemaName,\n codecHooks,\n storageTypes,\n ...ifDefined('schema', relationalSchema),\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: postgresPlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n const schemaDiffCalls = this.planPostgresSchemaDiff(options, databaseDiff.schemaDiffIssues);\n const schemaDiffPartition = partitionCallsByControlPolicy({\n calls: schemaDiffCalls,\n contract: options.contract,\n resolveControlPolicySubject: (call) =>\n resolvePostgresCallControlPolicySubject(call, options.contract),\n resolveFactoryName: (call) => call.factoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n\n // Inline `onFieldEvent`-emitted ops after structural DDL. The fixed\n // ordering is `structural → added → dropped → altered`, with\n // within-group sorting by `(tableName, fieldName)` so re-emits are\n // byte-stable. The hook fires only at the application emitter —\n // extension-space planning never reaches this helper.\n const fieldEventOps = planFieldEventOperations({\n priorContract: options.fromContract,\n newContract: options.contract,\n codecHooks,\n });\n // Codec hook ops are target-agnostic `OpFactoryCall`; Postgres planning\n // lifts them at this integration boundary (see field-event-planner JSDoc).\n const fieldEventPostgresCalls = blindCast<\n readonly PostgresOpFactoryCall[],\n 'Codec hook ops conform to PostgresOpFactoryCall at the app emitter boundary'\n >(fieldEventOps);\n const fieldEventPartition = partitionCallsByControlPolicy({\n calls: fieldEventPostgresCalls,\n contract: options.contract,\n resolveControlPolicySubject: (call) =>\n resolvePostgresCallControlPolicySubject(call, options.contract),\n resolveFactoryName: (call) => call.factoryName,\n formatSubjectLabel: (factoryName, subject) =>\n formatPostgresControlPolicySubjectLabel(factoryName, subject, options.contract),\n });\n const calls = [...result.value.calls, ...schemaDiffPartition.kept, ...fieldEventPartition.kept];\n const warnings: SqlPlannerConflict[] = [\n ...issuePartition.warnings,\n ...schemaDiffPartition.warnings,\n ...fieldEventPartition.warnings,\n ];\n\n return Object.freeze({\n kind: 'success' as const,\n plan: new TypeScriptRenderablePostgresMigration(\n calls,\n {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n },\n options.spaceId,\n this.#lowerer,\n ),\n ...(warnings.length > 0 ? { warnings: Object.freeze(warnings) } : {}),\n });\n }\n\n /**\n * Maps the RLS policy presence findings of the shared\n * `diffPostgresDatabaseSchema` (already ownership-filtered) into\n * `ENABLE RLS` / `CREATE POLICY` / `DROP POLICY` ops. It no longer re-diffs —\n * it consumes the `schemaDiffIssues` of the one combined diff.\n */\n private planPostgresSchemaDiff(\n options: PlannerOptionsWithComponents,\n filteredDiffIssues: readonly SchemaDiffIssue<SqlSchemaDiffNode>[],\n ): readonly PostgresOpFactoryCall[] {\n const allowsDestructive = options.policy.allowedOperationClasses.includes('destructive');\n const calls: PostgresOpFactoryCall[] = [];\n const seenEnableTables = new Set<string>();\n\n for (const issue of filteredDiffIssues) {\n // 'mismatch' is unreachable for content-addressed policies: the wire name\n // encodes the body hash, so two policies sharing a local key (same name)\n // are always equal and isEqualTo never returns false.\n if (issue.outcome === 'missing') {\n const expected = issue.expected;\n PostgresPolicySchemaNode.assert(expected);\n // expected.namespaceId is the DDL schema name (resolved during projection);\n // this re-resolution is a no-op as long as PostgresSchema.ddlSchemaName() returns this.id.\n const schemaForTable = resolveDdlSchemaForNamespaceStorage(\n options.contract.storage,\n expected.namespaceId,\n );\n const tableKey = `${schemaForTable}.${expected.tableName}`;\n if (!seenEnableTables.has(tableKey)) {\n seenEnableTables.add(tableKey);\n calls.push(new EnableRowLevelSecurityCall(schemaForTable, expected.tableName));\n }\n calls.push(\n new CreatePostgresRlsPolicyCall(\n schemaForTable,\n expected.tableName,\n policyNodeToContractPolicy(expected),\n ),\n );\n } else if (issue.outcome === 'extra' && allowsDestructive) {\n const actual = issue.actual;\n PostgresPolicySchemaNode.assert(actual);\n const schemaForTable = resolveDdlSchemaForNamespaceStorage(\n options.contract.storage,\n actual.namespaceId,\n );\n calls.push(new DropPostgresRlsPolicyCall(schemaForTable, actual.tableName, actual.name));\n }\n }\n\n return calls;\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n /**\n * The structural issue list `planIssues` consumes: the relational findings\n * from the shared `diffPostgresDatabaseSchema` plus namespace presence.\n *\n * Schema presence (`missing_schema` → `CREATE SCHEMA`) is a planner-only\n * op-generation concern, so it is stitched in here rather than inside the\n * shared diff — verify never needs it (a missing schema already surfaces as\n * `missing_table` in the relational findings). It reads `existingSchemas` off\n * the database root, so it takes the whole tree. Policy drift is handled\n * separately via `planPostgresSchemaDiff` from the same shared diff's\n * `schemaDiffIssues`.\n */\n private collectSchemaIssues(\n options: PlannerOptionsWithComponents,\n relationalIssues: readonly SchemaIssue[],\n ): readonly SchemaIssue[] {\n const namespaceIssues = verifyPostgresNamespacePresence({\n contract: options.contract,\n schema: options.schema,\n });\n if (namespaceIssues.length === 0) {\n return relationalIssues;\n }\n return [...namespaceIssues, ...relationalIssues];\n }\n}\n\n/**\n * Returns the one namespace node whose tables the relational strategy layer\n * probes for live-table existence — the node matching the planner's resolved\n * schema name, or the first namespace when none matches. `undefined` when the\n * tree has no namespaces, so the strategy context uses its empty-schema default.\n *\n * The relational strategies key tables by bare name, so they can only probe one\n * namespace at a time; probing across every namespace at once is future work.\n */\nfunction relationalNamespaceNode(\n schema: PostgresDatabaseSchemaNode,\n schemaName: string,\n): SqlSchemaIR | undefined {\n const namespaceNodes = Object.values(schema.namespaces);\n const byName = namespaceNodes.find((node) => node.schemaName === schemaName);\n return byName ?? namespaceNodes[0];\n}\n\n/**\n * Rebuilds the `PostgresRlsPolicy` contract entity `CreatePostgresRlsPolicyCall`\n * carries (its `renderTypeScript`/`createRlsPolicy` paths serialize the whole\n * entity, `namespaceId` included). This reconstructs rather than looking the\n * original up in the contract on purpose: the diff node's `namespaceId` is the\n * *resolved DDL schema* (set when the expected tree was built), which is the\n * value the emitted op must carry; the contract-stored entity holds the raw,\n * pre-resolution coordinate, so a lookup would change the migration output.\n */\nfunction policyNodeToContractPolicy(node: PostgresPolicySchemaNode): PostgresRlsPolicy {\n return new PostgresRlsPolicy({\n name: node.name,\n prefix: node.prefix,\n tableName: node.tableName,\n namespaceId: node.namespaceId,\n operation: node.operation,\n roles: [...node.roles],\n ...ifDefined('using', node.using),\n ...ifDefined('withCheck', node.withCheck),\n permissive: node.permissive,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,SAAS,aAAa,QAA2B,aAA+C;CAC9F,OAAO,IAAI,yBAAyB;EAClC,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,WAAW,OAAO;EAClB;EACA,WAAW,OAAO;EAClB,OAAO,CAAC,GAAG,OAAO,KAAK;EACvB,GAAG,UAAU,SAAS,OAAO,KAAK;EAClC,GAAG,UAAU,aAAa,OAAO,SAAS;EAC1C,YAAY,OAAO;CACrB,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,qCACd,UACA,SAC4B;CAC5B,IAAI,aAAa,MACf,OAAO,IAAI,2BAA2B;EACpC,YAAY,CAAC;EACb,OAAO,CAAC;EACR,iBAAiB,CAAC;EAClB,WAAW;CACb,CAAC;CAGH,MAAM,aAA0D,CAAC;CACjE,MAAM,QAAkC,CAAC;CACzC,MAAM,eAAyB,CAAC;CAEhC,KAAK,MAAM,MAAM,OAAO,OAAO,SAAS,QAAQ,UAAU,GAAG;EAC3D,IAAI,CAAC,iBAAiB,EAAE,GAAG;EAC3B,MAAM,YAAY,oCAAoC,SAAS,SAAS,GAAG,EAAE;EAC7E,aAAa,KAAK,SAAS;EAK3B,MAAM,YAAY,4BAA4B,SAAS,SAAS,GAAG,IAAI,OAAO,CAAC,CAAC;EAEhF,MAAM,kCAAkB,IAAI,IAAwC;EACpE,KAAK,MAAM,UAAU,OAAO,OAAO,GAAG,MAAM,GAAG;GAC7C,MAAM,OAAO,gBAAgB,IAAI,OAAO,SAAS,KAAK,CAAC;GACvD,KAAK,KAAK,aAAa,QAAQ,SAAS,CAAC;GACzC,gBAAgB,IAAI,OAAO,WAAW,IAAI;EAC5C;EAEA,MAAM,SAAkD,CAAC;EACz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AM,SAAS,KAAK,eAAe,UACrD,KAAK,eAAe;AAClC;;;;;;;;;;AAWA,SAAS,2BAA2B,MAAmD;CACrF,OAAO,IAAI,kBAAkB;EAC3B,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,WAAW,KAAK;EAChB,aAAa,KAAK;EAClB,WAAW,KAAK;EAChB,OAAO,CAAC,GAAG,KAAK,KAAK;EACrB,GAAG,UAAU,SAAS,KAAK,KAAK;EAChC,GAAG,UAAU,aAAa,KAAK,SAAS;EACxC,YAAY,KAAK;CACnB,CAAC;AACH"}
@@ -1,4 +1,4 @@
1
- import { t as PostgresMigration } from "./postgres-migration-CZApTUCK.mjs";
1
+ import { t as PostgresMigration } from "./postgres-migration-D0QIVE-p.mjs";
2
2
  import { t as renderOps } from "./render-ops-BREh1kHe.mjs";
3
3
  import { t as renderCallsToTypeScript } from "./render-typescript-7yqILcwr.mjs";
4
4
  //#region src/core/migrations/planner-produced-postgres-migration.ts
@@ -40,4 +40,4 @@ var TypeScriptRenderablePostgresMigration = class extends PostgresMigration {
40
40
  //#endregion
41
41
  export { TypeScriptRenderablePostgresMigration as t };
42
42
 
43
- //# sourceMappingURL=planner-produced-postgres-migration-CikV-edi.mjs.map
43
+ //# sourceMappingURL=planner-produced-postgres-migration-C2_H6Vvl.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"planner-produced-postgres-migration-CikV-edi.mjs","names":["#calls","#meta","#spaceId","#lowerer","#operationsCache"],"sources":["../src/core/migrations/planner-produced-postgres-migration.ts"],"sourcesContent":["/**\n * Planner-produced Postgres migration.\n *\n * Returned by `PostgresMigrationPlanner.plan(...)` and `emptyMigration(...)`.\n * Holds the migration IR (`PostgresOpFactoryCall[]`) alongside\n * `MigrationMeta` and exposes both the runtime-ops view (`get operations`)\n * and the TypeScript authoring view (`renderTypeScript()`). Satisfies\n * `MigrationPlanWithAuthoringSurface` so the CLI can uniformly serialize any\n * planner result back to `migration.ts`.\n *\n * Extends the family-level `SqlMigration` alias rather than the target-local\n * migration base directly — mirrors Mongo's `PlannerProducedMongoMigration`\n * shape and keeps CLI wiring one step removed from target internals.\n *\n * Placeholder-bearing plans: `renderTypeScript()` always succeeds and embeds\n * `() => placeholder(\"slot\")` at each stub. `operations`, in contrast, is\n * _not safe to enumerate_ on a stub-bearing plan — `DataTransformCall.toOp()`\n * throws `PN-MIG-2001` because a planner-stubbed closure cannot be lowered\n * to a runtime op. Callers that know a plan may carry stubs must render to\n * `migration.ts`, let the user fill the slots, and re-load the edited\n * migration before enumerating ops. The walk-schema planner does not emit\n * `DataTransformCall`s today, so this asymmetry is invisible until the\n * issue-planner integration lands in Phase 2.\n */\n\nimport type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport type {\n MigrationPlanWithAuthoringSurface,\n OpFactoryCall,\n} from '@prisma-next/framework-components/control';\nimport type { MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport { PostgresMigration } from './postgres-migration';\nimport { renderOps } from './render-ops';\nimport { renderCallsToTypeScript } from './render-typescript';\n\nexport class TypeScriptRenderablePostgresMigration\n extends PostgresMigration\n implements MigrationPlanWithAuthoringSurface\n{\n readonly #calls: readonly OpFactoryCall[];\n readonly #meta: MigrationMeta;\n readonly #spaceId: string;\n readonly #lowerer: ExecuteRequestLowerer | undefined;\n #operationsCache:\n | readonly (\n | SqlMigrationPlanOperation<PostgresPlanTargetDetails>\n | Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>\n )[]\n | undefined;\n\n constructor(\n calls: readonly OpFactoryCall[],\n meta: MigrationMeta,\n spaceId: string,\n lowerer?: ExecuteRequestLowerer,\n ) {\n super();\n this.#calls = calls;\n this.#meta = meta;\n this.#spaceId = spaceId;\n this.#lowerer = lowerer;\n }\n\n override get operations(): readonly (\n | SqlMigrationPlanOperation<PostgresPlanTargetDetails>\n | Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>\n )[] {\n this.#operationsCache ??= renderOps(this.#calls, this.#lowerer);\n return this.#operationsCache;\n }\n\n override describe(): MigrationMeta {\n return this.#meta;\n }\n\n /**\n * Contract space this planner-produced plan applies to. Threaded\n * from the planner options so the runner keys the marker row by\n * the right space when executing the plan.\n */\n get spaceId(): string {\n return this.#spaceId;\n }\n\n renderTypeScript(): string {\n return renderCallsToTypeScript(this.#calls, { from: this.#meta.from, to: this.#meta.to });\n }\n}\n"],"mappings":";;;;AAqCA,IAAa,wCAAb,cACU,kBAEV;CACE;CACA;CACA;CACA;CACA;CAOA,YACE,OACA,MACA,SACA,SACA;EACA,MAAM;EACN,KAAKA,SAAS;EACd,KAAKC,QAAQ;EACb,KAAKC,WAAW;EAChB,KAAKC,WAAW;CAClB;CAEA,IAAa,aAGT;EACF,KAAKC,qBAAqB,UAAU,KAAKJ,QAAQ,KAAKG,QAAQ;EAC9D,OAAO,KAAKC;CACd;CAEA,WAAmC;EACjC,OAAO,KAAKH;CACd;;;;;;CAOA,IAAI,UAAkB;EACpB,OAAO,KAAKC;CACd;CAEA,mBAA2B;EACzB,OAAO,wBAAwB,KAAKF,QAAQ;GAAE,MAAM,KAAKC,MAAM;GAAM,IAAI,KAAKA,MAAM;EAAG,CAAC;CAC1F;AACF"}
1
+ {"version":3,"file":"planner-produced-postgres-migration-C2_H6Vvl.mjs","names":["#calls","#meta","#spaceId","#lowerer","#operationsCache"],"sources":["../src/core/migrations/planner-produced-postgres-migration.ts"],"sourcesContent":["/**\n * Planner-produced Postgres migration.\n *\n * Returned by `PostgresMigrationPlanner.plan(...)` and `emptyMigration(...)`.\n * Holds the migration IR (`PostgresOpFactoryCall[]`) alongside\n * `MigrationMeta` and exposes both the runtime-ops view (`get operations`)\n * and the TypeScript authoring view (`renderTypeScript()`). Satisfies\n * `MigrationPlanWithAuthoringSurface` so the CLI can uniformly serialize any\n * planner result back to `migration.ts`.\n *\n * Extends the family-level `SqlMigration` alias rather than the target-local\n * migration base directly — mirrors Mongo's `PlannerProducedMongoMigration`\n * shape and keeps CLI wiring one step removed from target internals.\n *\n * Placeholder-bearing plans: `renderTypeScript()` always succeeds and embeds\n * `() => placeholder(\"slot\")` at each stub. `operations`, in contrast, is\n * _not safe to enumerate_ on a stub-bearing plan — `DataTransformCall.toOp()`\n * throws `PN-MIG-2001` because a planner-stubbed closure cannot be lowered\n * to a runtime op. Callers that know a plan may carry stubs must render to\n * `migration.ts`, let the user fill the slots, and re-load the edited\n * migration before enumerating ops. The walk-schema planner does not emit\n * `DataTransformCall`s today, so this asymmetry is invisible until the\n * issue-planner integration lands in Phase 2.\n */\n\nimport type { SqlMigrationPlanOperation } from '@prisma-next/family-sql/control';\nimport type { ExecuteRequestLowerer } from '@prisma-next/family-sql/control-adapter';\nimport type {\n MigrationPlanWithAuthoringSurface,\n OpFactoryCall,\n} from '@prisma-next/framework-components/control';\nimport type { MigrationMeta } from '@prisma-next/migration-tools/migration';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport { PostgresMigration } from './postgres-migration';\nimport { renderOps } from './render-ops';\nimport { renderCallsToTypeScript } from './render-typescript';\n\nexport class TypeScriptRenderablePostgresMigration\n extends PostgresMigration\n implements MigrationPlanWithAuthoringSurface\n{\n readonly #calls: readonly OpFactoryCall[];\n readonly #meta: MigrationMeta;\n readonly #spaceId: string;\n readonly #lowerer: ExecuteRequestLowerer | undefined;\n #operationsCache:\n | readonly (\n | SqlMigrationPlanOperation<PostgresPlanTargetDetails>\n | Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>\n )[]\n | undefined;\n\n constructor(\n calls: readonly OpFactoryCall[],\n meta: MigrationMeta,\n spaceId: string,\n lowerer?: ExecuteRequestLowerer,\n ) {\n super();\n this.#calls = calls;\n this.#meta = meta;\n this.#spaceId = spaceId;\n this.#lowerer = lowerer;\n }\n\n override get operations(): readonly (\n | SqlMigrationPlanOperation<PostgresPlanTargetDetails>\n | Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>\n )[] {\n this.#operationsCache ??= renderOps(this.#calls, this.#lowerer);\n return this.#operationsCache;\n }\n\n override describe(): MigrationMeta {\n return this.#meta;\n }\n\n /**\n * Contract space this planner-produced plan applies to. Threaded\n * from the planner options so the runner keys the marker row by\n * the right space when executing the plan.\n */\n get spaceId(): string {\n return this.#spaceId;\n }\n\n renderTypeScript(): string {\n return renderCallsToTypeScript(this.#calls, { from: this.#meta.from, to: this.#meta.to });\n }\n}\n"],"mappings":";;;;AAqCA,IAAa,wCAAb,cACU,kBAEV;CACE;CACA;CACA;CACA;CACA;CAOA,YACE,OACA,MACA,SACA,SACA;EACA,MAAM;EACN,KAAKA,SAAS;EACd,KAAKC,QAAQ;EACb,KAAKC,WAAW;EAChB,KAAKC,WAAW;CAClB;CAEA,IAAa,aAGT;EACF,KAAKC,qBAAqB,UAAU,KAAKJ,QAAQ,KAAKG,QAAQ;EAC9D,OAAO,KAAKC;CACd;CAEA,WAAmC;EACjC,OAAO,KAAKH;CACd;;;;;;CAOA,IAAI,UAAkB;EACpB,OAAO,KAAKC;CACd;CAEA,mBAA2B;EACzB,OAAO,wBAAwB,KAAKF,QAAQ;GAAE,MAAM,KAAKC,MAAM;GAAM,IAAI,KAAKA,MAAM;EAAG,CAAC;CAC1F;AACF"}
@@ -1,2 +1,2 @@
1
- import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-CikV-edi.mjs";
1
+ import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-C2_H6Vvl.mjs";
2
2
  export { TypeScriptRenderablePostgresMigration };
package/dist/planner.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { i as contractToPostgresDatabaseSchemaNode, n as diffPostgresDatabaseSchema, t as createPostgresMigrationPlanner } from "./planner-CMXuFrQB.mjs";
1
+ import { i as contractToPostgresDatabaseSchemaNode, n as diffPostgresDatabaseSchema, t as createPostgresMigrationPlanner } from "./planner-Bq0Z2sVO.mjs";
2
2
  export { contractToPostgresDatabaseSchemaNode, createPostgresMigrationPlanner, diffPostgresDatabaseSchema };
@@ -1,5 +1,5 @@
1
1
  import { p as PG_INT_CODEC_ID, v as PG_TEXT_CODEC_ID } from "./codec-ids-C_-Hj6bL.mjs";
2
- import { a as nativeEnumEntityKind, o as policyEntityKind, r as isPostgresSchema, s as roleEntityKind, t as PostgresSchema } from "./postgres-schema-CajYAwny.mjs";
2
+ import { a as nativeEnumEntityKind, o as policyEntityKind, s as roleEntityKind, t as PostgresSchema } from "./postgres-schema-CajYAwny.mjs";
3
3
  import { t as postgresAuthoringEntityTypes } from "./authoring-DzHOdWTl.mjs";
4
4
  import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
5
5
  import { blindCast } from "@prisma-next/utils/casts";
@@ -69,12 +69,14 @@ var PostgresContractSerializer = class extends SqlContractSerializerBase {
69
69
  serializeContract(contract) {
70
70
  const { storage, ...rest } = contract;
71
71
  const namespacesJson = {};
72
- for (const [nsId, ns] of Object.entries(storage.namespaces)) if (isPostgresSchema(ns)) namespacesJson[nsId] = this.serializePostgresNamespace(ns, ns.id === UNBOUND_NAMESPACE_ID);
73
- else namespacesJson[nsId] = {
74
- id: nsId,
75
- kind: nsId === UNBOUND_NAMESPACE_ID ? "postgres-unbound-schema" : "postgres-schema",
76
- entries: { table: Object.fromEntries(Object.entries(ns.entries.table ?? {}).map(([tableName, table]) => [tableName, this.serializeJsonObject(table)])) }
77
- };
72
+ for (const [nsId, ns] of Object.entries(storage.namespaces)) {
73
+ const isUnboundSlot = ns.id === UNBOUND_NAMESPACE_ID;
74
+ namespacesJson[nsId] = {
75
+ id: ns.id,
76
+ kind: isUnboundSlot ? "postgres-unbound-schema" : "postgres-schema",
77
+ entries: this.serializeNamespaceEntries(ns.entries)
78
+ };
79
+ }
78
80
  const storageOut = {
79
81
  storageHash: String(storage.storageHash),
80
82
  namespaces: namespacesJson
@@ -89,41 +91,6 @@ var PostgresContractSerializer = class extends SqlContractSerializerBase {
89
91
  storage: storageOut
90
92
  });
91
93
  }
92
- /**
93
- * Native enums are deliberately not serialized here — `native_enum` is
94
- * authoring-time-only. Once lowered, its member values live on in the
95
- * `valueSet` slot it derives (via the SQL family's generic
96
- * `deriveValueSet` mechanism); nothing downstream reads the
97
- * `PostgresNativeEnum` entity itself, so re-emitting it into
98
- * `contract.json` would be dead weight.
99
- */
100
- serializePostgresNamespace(ns, isUnboundSlot) {
101
- const tablesOut = this.serializeEntries(ns.table);
102
- const valueSetOut = this.serializeEntries(ns.valueSet ?? {});
103
- const roleOut = this.serializeEntries(ns.role);
104
- const policyOut = this.serializeEntries(ns.policy);
105
- return {
106
- id: ns.id,
107
- kind: isUnboundSlot ? "postgres-unbound-schema" : "postgres-schema",
108
- entries: {
109
- table: tablesOut,
110
- ...Object.keys(valueSetOut).length > 0 ? { valueSet: valueSetOut } : {},
111
- ...Object.keys(roleOut).length > 0 ? { role: roleOut } : {},
112
- ...Object.keys(policyOut).length > 0 ? { policy: policyOut } : {}
113
- }
114
- };
115
- }
116
- serializeEntries(entries) {
117
- const out = {};
118
- for (const [name, entry] of Object.entries(entries)) out[name] = this.serializeJsonObject(entry);
119
- return out;
120
- }
121
- serializeJsonObject(value) {
122
- return blindCast(this.serializeJsonValue(value));
123
- }
124
- serializeJsonValue(value) {
125
- return blindCast(JSON.parse(JSON.stringify(value)));
126
- }
127
94
  };
128
95
  //#endregion
129
96
  //#region src/core/postgres-contract-view.ts
@@ -140,4 +107,4 @@ const PostgresContractView = {
140
107
  //#endregion
141
108
  export { PostgresContractSerializer as n, PostgresContractView as t };
142
109
 
143
- //# sourceMappingURL=postgres-contract-view-V3rGJCoe.mjs.map
110
+ //# sourceMappingURL=postgres-contract-view-3xfUgjnC.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-contract-view-3xfUgjnC.mjs","names":[],"sources":["../src/core/postgres-contract-serializer.ts","../src/core/postgres-contract-view.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport {\n SqlContractSerializerBase,\n type SqlEntityHydrationFactory,\n} from '@prisma-next/family-sql/ir';\nimport {\n type AuthoringEntityContext,\n type AuthoringEntityTypeFactoryOutput,\n type AuthoringEntityTypeNamespace,\n isAuthoringEntityTypeDescriptor,\n} from '@prisma-next/framework-components/authoring';\nimport {\n type AnyEntityKindDescriptor,\n type Namespace,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport type { SqlNamespaceInput, SqlStorage } from '@prisma-next/sql-contract/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport { postgresAuthoringEntityTypes } from './authoring';\nimport { PG_INT_CODEC_ID, PG_TEXT_CODEC_ID } from './codec-ids';\nimport { nativeEnumEntityKind, policyEntityKind, roleEntityKind } from './entity-kinds';\nimport { PostgresSchema } from './postgres-schema';\n\nconst POSTGRES_AUTHORING_CTX: AuthoringEntityContext = {\n family: 'sql',\n target: 'postgres',\n enumInferenceCodecs: { text: PG_TEXT_CODEC_ID, int: PG_INT_CODEC_ID },\n};\n\nfunction isAuthoringEntityTypeFactoryOutput(\n output: unknown,\n): output is AuthoringEntityTypeFactoryOutput<unknown, unknown> {\n return (\n typeof output === 'object' &&\n output !== null &&\n 'factory' in output &&\n typeof output.factory === 'function'\n );\n}\n\n/**\n * Walks a pack's entity-type namespace tree and emits hydration factories\n * keyed by the descriptor's `discriminator`. Used for `storage.types`\n * (codec-triple hydration). Namespace entries hydration dispatches by\n * entries key, not discriminator — handled by `hydrateNamespaceEntities`.\n */\nfunction collectStorageTypesHydrators(\n namespace: AuthoringEntityTypeNamespace,\n): ReadonlyMap<string, SqlEntityHydrationFactory> {\n const registry = new Map<string, SqlEntityHydrationFactory>();\n const walk = (node: AuthoringEntityTypeNamespace): void => {\n for (const value of Object.values(node)) {\n if (isAuthoringEntityTypeDescriptor(value)) {\n if (isAuthoringEntityTypeFactoryOutput(value.output)) {\n const { factory } = value.output;\n registry.set(value.discriminator, (raw) => factory(raw, POSTGRES_AUTHORING_CTX));\n }\n continue;\n }\n if (typeof value === 'object' && value !== null) {\n walk(value);\n }\n }\n };\n walk(namespace);\n return registry;\n}\n\nexport class PostgresContractSerializer extends SqlContractSerializerBase<Contract<SqlStorage>> {\n constructor(extraPackEntityKinds: readonly AnyEntityKindDescriptor[] = []) {\n const storageTypesHydrators = collectStorageTypesHydrators(postgresAuthoringEntityTypes);\n super(storageTypesHydrators, [\n policyEntityKind,\n roleEntityKind,\n nativeEnumEntityKind,\n ...extraPackEntityKinds,\n ]);\n }\n\n protected override hydrateSqlNamespaceEntry(\n nsId: string,\n raw: Record<string, unknown>,\n ): Namespace | SqlNamespaceInput {\n const hydrated = blindCast<\n SqlNamespaceInput,\n 'raw is always plain JSON, so super.hydrateSqlNamespaceEntry returns SqlNamespaceInput'\n >(super.hydrateSqlNamespaceEntry(nsId, raw));\n const { id, entries } = hydrated;\n\n const allSlotsEmpty = Object.values(entries).every(\n (slot) => slot === undefined || Object.keys(slot).length === 0,\n );\n if (id === UNBOUND_NAMESPACE_ID && allSlotsEmpty) {\n return PostgresSchema.unbound;\n }\n const valueSetSlot = entries['valueSet'];\n const hasValueSets = valueSetSlot !== undefined && Object.keys(valueSetSlot).length > 0;\n return new PostgresSchema({\n id,\n entries: {\n ...entries,\n table: entries['table'] ?? {},\n ...(hasValueSets ? { valueSet: valueSetSlot } : {}),\n },\n });\n }\n\n override serializeContract(contract: Contract<SqlStorage>): JsonObject {\n const { storage, ...rest } = contract;\n const namespacesJson: Record<string, JsonObject> = {};\n // Each namespace serializes to its id, its schema-kind tag, and the\n // base's generic entries walk. Native enums are excluded upstream —\n // carried non-enumerable on `PostgresSchema.entries`, so the walk\n // never sees them.\n for (const [nsId, ns] of Object.entries(storage.namespaces)) {\n const isUnboundSlot = ns.id === UNBOUND_NAMESPACE_ID;\n namespacesJson[nsId] = {\n id: ns.id,\n kind: isUnboundSlot ? 'postgres-unbound-schema' : 'postgres-schema',\n entries: this.serializeNamespaceEntries(ns.entries),\n };\n }\n const storageOut: Record<string, unknown> = {\n storageHash: String(storage.storageHash),\n namespaces: namespacesJson,\n };\n if (storage.types !== undefined) {\n const typesOut: Record<string, JsonObject> = {};\n for (const [name, entry] of Object.entries(storage.types)) {\n typesOut[name] = this.serializeJsonObject(entry);\n }\n storageOut['types'] = typesOut;\n }\n return blindCast<\n JsonObject,\n 'contract minus storage plus a JSON-shaped storageOut is a JsonObject'\n >({\n ...rest,\n storage: storageOut,\n });\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport {\n buildSqlSchemaQualifiedView,\n type SqlSchemaQualifiedView,\n} from '@prisma-next/sql-contract/contract-view';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport { PostgresContractSerializer } from './postgres-contract-serializer';\n\n/**\n * A schema-qualified Postgres contract view: the deserialized contract\n * intersected with a single `namespace` member holding every schema by id. It is\n * substitutable for `Contract` (carries `storage`, `domain`, …) and reaches each\n * schema's entities through `view.namespace.<schema>`:\n *\n * ```ts\n * const view = PostgresContractView.fromJson<Contract>(contractJson);\n * view.namespace.public.table.users // typed table leaf in the public schema\n * view.namespace.auth.table.users // the auth schema's own users table\n * view.namespace.public.entries.policy.X // pack-contributed kind (RLS / #771 path)\n * view.namespace.__unbound__.table.X // default schema, keyed by its raw id\n * view.storage // the full contract is still present\n * ```\n *\n * This mirrors the runtime `db.enums.<ns>` keying exactly (the default schema\n * keeps its literal `__unbound__` id). Schema names are NOT promoted to the\n * contract root, so there is no collision with contract envelope fields — a\n * schema named `storage` is `view.namespace.storage`, while `view.storage`\n * stays the contract's `storage`.\n */\nexport type PostgresContractView<TContract extends Contract<SqlStorage> = Contract<SqlStorage>> =\n SqlSchemaQualifiedView<TContract>;\n\nexport const PostgresContractView = {\n /** Wrap an already-deserialized Postgres contract in a schema-qualified view. */\n from<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n ): PostgresContractView<TContract> {\n return buildSqlSchemaQualifiedView(contract);\n },\n\n /** Deserialize a Postgres contract JSON envelope and wrap it in a view. */\n fromJson<TContract extends Contract<SqlStorage> = Contract<SqlStorage>>(\n json: unknown,\n ): PostgresContractView<TContract> {\n const contract = new PostgresContractSerializer().deserializeContract<TContract>(json);\n return buildSqlSchemaQualifiedView(contract);\n },\n};\n"],"mappings":";;;;;;;;;AAwBA,MAAM,yBAAiD;CACrD,QAAQ;CACR,QAAQ;CACR,qBAAqB;EAAE,MAAM;EAAkB,KAAK;CAAgB;AACtE;AAEA,SAAS,mCACP,QAC8D;CAC9D,OACE,OAAO,WAAW,YAClB,WAAW,QACX,aAAa,UACb,OAAO,OAAO,YAAY;AAE9B;;;;;;;AAQA,SAAS,6BACP,WACgD;CAChD,MAAM,2BAAW,IAAI,IAAuC;CAC5D,MAAM,QAAQ,SAA6C;EACzD,KAAK,MAAM,SAAS,OAAO,OAAO,IAAI,GAAG;GACvC,IAAI,gCAAgC,KAAK,GAAG;IAC1C,IAAI,mCAAmC,MAAM,MAAM,GAAG;KACpD,MAAM,EAAE,YAAY,MAAM;KAC1B,SAAS,IAAI,MAAM,gBAAgB,QAAQ,QAAQ,KAAK,sBAAsB,CAAC;IACjF;IACA;GACF;GACA,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,KAAK,KAAK;EAEd;CACF;CACA,KAAK,SAAS;CACd,OAAO;AACT;AAEA,IAAa,6BAAb,cAAgD,0BAAgD;CAC9F,YAAY,uBAA2D,CAAC,GAAG;EACzE,MAAM,wBAAwB,6BAA6B,4BAA4B;EACvF,MAAM,uBAAuB;GAC3B;GACA;GACA;GACA,GAAG;EACL,CAAC;CACH;CAEA,yBACE,MACA,KAC+B;EAK/B,MAAM,EAAE,IAAI,YAJK,UAGf,MAAM,yBAAyB,MAAM,GAAG,CACX;EAE/B,MAAM,gBAAgB,OAAO,OAAO,OAAO,CAAC,CAAC,OAC1C,SAAS,SAAS,KAAA,KAAa,OAAO,KAAK,IAAI,CAAC,CAAC,WAAW,CAC/D;EACA,IAAI,OAAO,wBAAwB,eACjC,OAAO,eAAe;EAExB,MAAM,eAAe,QAAQ;EAC7B,MAAM,eAAe,iBAAiB,KAAA,KAAa,OAAO,KAAK,YAAY,CAAC,CAAC,SAAS;EACtF,OAAO,IAAI,eAAe;GACxB;GACA,SAAS;IACP,GAAG;IACH,OAAO,QAAQ,YAAY,CAAC;IAC5B,GAAI,eAAe,EAAE,UAAU,aAAa,IAAI,CAAC;GACnD;EACF,CAAC;CACH;CAEA,kBAA2B,UAA4C;EACrE,MAAM,EAAE,SAAS,GAAG,SAAS;EAC7B,MAAM,iBAA6C,CAAC;EAKpD,KAAK,MAAM,CAAC,MAAM,OAAO,OAAO,QAAQ,QAAQ,UAAU,GAAG;GAC3D,MAAM,gBAAgB,GAAG,OAAO;GAChC,eAAe,QAAQ;IACrB,IAAI,GAAG;IACP,MAAM,gBAAgB,4BAA4B;IAClD,SAAS,KAAK,0BAA0B,GAAG,OAAO;GACpD;EACF;EACA,MAAM,aAAsC;GAC1C,aAAa,OAAO,QAAQ,WAAW;GACvC,YAAY;EACd;EACA,IAAI,QAAQ,UAAU,KAAA,GAAW;GAC/B,MAAM,WAAuC,CAAC;GAC9C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,QAAQ,KAAK,GACtD,SAAS,QAAQ,KAAK,oBAAoB,KAAK;GAEjD,WAAW,WAAW;EACxB;EACA,OAAO,UAGL;GACA,GAAG;GACH,SAAS;EACX,CAAC;CACH;AACF;;;AC9GA,MAAa,uBAAuB;;CAElC,KACE,UACiC;EACjC,OAAO,4BAA4B,QAAQ;CAC7C;;CAGA,SACE,MACiC;EAEjC,OAAO,4BADU,IAAI,2BAA2B,CAAC,CAAC,oBAA+B,IACvC,CAAC;CAC7C;AACF"}
@@ -1,6 +1,6 @@
1
1
  import { A as installExtension, E as SetNotNullCall, S as DropTableCall, T as SetDefaultCall, _ as DropConstraintCall, b as DropNotNullCall, c as AlterColumnTypeCall, f as CreateSchemaCall, g as DropColumnCall, h as DropCheckConstraintCall, n as AddColumnCall, o as AddPrimaryKeyCall, p as CreateTableCall, r as AddForeignKeyCall, s as AddUniqueCall, t as AddCheckConstraintCall, u as CreateIndexCall, v as DropDefaultCall, y as DropIndexCall } from "./op-factory-call-BuoGT5UI.mjs";
2
2
  import { t as errorPostgresMigrationStackMissing } from "./errors-CUk87ByX.mjs";
3
- import { t as PostgresContractView } from "./postgres-contract-view-V3rGJCoe.mjs";
3
+ import { t as PostgresContractView } from "./postgres-contract-view-3xfUgjnC.mjs";
4
4
  import { t as dataTransform } from "./data-transform-BOWpliq8.mjs";
5
5
  import { Migration } from "@prisma-next/family-sql/migration";
6
6
  import { MigrationContractViews } from "@prisma-next/migration-tools/migration";
@@ -161,4 +161,4 @@ var PostgresMigration = class extends Migration {
161
161
  //#endregion
162
162
  export { PostgresMigration as t };
163
163
 
164
- //# sourceMappingURL=postgres-migration-CZApTUCK.mjs.map
164
+ //# sourceMappingURL=postgres-migration-D0QIVE-p.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"postgres-migration-CZApTUCK.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 {\n AddCheckConstraintCall,\n AddColumnCall,\n AddForeignKeyCall,\n AddPrimaryKeyCall,\n AddUniqueCall,\n AlterColumnTypeCall,\n type AlterColumnTypeOptions,\n CreateIndexCall,\n CreateSchemaCall,\n CreateTableCall,\n DropCheckConstraintCall,\n DropColumnCall,\n DropConstraintCall,\n DropDefaultCall,\n DropIndexCall,\n DropNotNullCall,\n DropTableCall,\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); `dataTransform`\n * throws 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 * 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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return dataTransform(contract, name, options, this.controlAdapter);\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new CreateTableCall(\n options.schema,\n options.table,\n options.columns,\n options.constraints,\n ).toOp(this.controlAdapter);\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new CreateSchemaCall(options.schema).toOp(this.controlAdapter);\n }\n\n protected addColumn(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: DdlColumn;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddColumnCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddPrimaryKeyCall(\n options.schema,\n options.table,\n options.constraint,\n options.columns,\n ).toOp(this.controlAdapter);\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddUniqueCall(\n options.schema,\n options.table,\n options.constraint,\n options.columns,\n ).toOp(this.controlAdapter);\n }\n\n protected addForeignKey(options: {\n readonly schema: string;\n readonly table: string;\n readonly foreignKey: ForeignKeySpec;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddForeignKeyCall(options.schema, options.table, options.foreignKey).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddCheckConstraintCall(\n options.schema,\n options.table,\n options.constraint,\n options.column,\n options.values,\n ).toOp(this.controlAdapter);\n }\n\n protected dropCheckConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropCheckConstraintCall(options.schema, options.table, options.constraint).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropConstraintCall(\n options.schema,\n options.table,\n options.constraint,\n options.kind ?? 'unique',\n ).toOp(this.controlAdapter);\n }\n\n protected dropTable(options: {\n readonly schema: string;\n readonly table: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropTableCall(options.schema, options.table).toOp(this.controlAdapter);\n }\n\n protected dropColumn(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropColumnCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AlterColumnTypeCall(\n options.schema,\n options.table,\n options.column,\n options.options,\n ).toOp(this.controlAdapter);\n }\n\n protected setNotNull(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new SetNotNullCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\n );\n }\n\n protected dropNotNull(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropNotNullCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new SetDefaultCall(\n options.schema,\n options.table,\n options.column,\n options.defaultSql,\n options.operationClass,\n ).toOp(this.controlAdapter);\n }\n\n protected dropDefault(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropDefaultCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new CreateIndexCall(\n options.schema,\n options.table,\n options.index,\n options.columns,\n options.extras,\n ).toOp(this.controlAdapter);\n }\n\n protected dropIndex(options: {\n readonly schema: string;\n readonly table: string;\n readonly index: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropIndexCall(options.schema, options.table, options.index).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return installExtension(options, this.controlAdapter);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,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,IAAI,cAAyC;EAC3C,OAAO,KAAKC,SAAS;CACvB;;;;;CAMA,IAAI,gBAAoD;EACtD,OAAO,KAAKC,WAAW;CACzB;;;;;;CAOA,cACE,UACA,MACA,SAC+D;EAC/D,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,cAAc,UAAU,MAAM,SAAS,KAAK,cAAc;CACnE;;;;;;CAOA,YAAsB,SAM4C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAA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AK,KAAK,cAAc;CAC5B;CAEA,YAAsB,SAI4C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,gBAAgB,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,MAAM,CAAC,CAAC,KACxE,KAAK,cACP;CACF;CAEA,YAAsB,SAM4C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,gBACT,QAAQ,QACR,QAAQ,OACR,QAAQ,OACR,QAAQ,SACR,QAAQ,MACV,CAAC,CAAC,KAAK,KAAK,cAAc;CAC5B;CAEA,UAAoB,SAI8C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,cAAc,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,KAAK,CAAC,CAAC,KACrE,KAAK,cACP;CACF;CAEA,iBAA2B,SAKuC;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,iBAAiB,SAAS,KAAK,cAAc;CACtD;AACF"}
1
+ {"version":3,"file":"postgres-migration-D0QIVE-p.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 {\n AddCheckConstraintCall,\n AddColumnCall,\n AddForeignKeyCall,\n AddPrimaryKeyCall,\n AddUniqueCall,\n AlterColumnTypeCall,\n type AlterColumnTypeOptions,\n CreateIndexCall,\n CreateSchemaCall,\n CreateTableCall,\n DropCheckConstraintCall,\n DropColumnCall,\n DropConstraintCall,\n DropDefaultCall,\n DropIndexCall,\n DropNotNullCall,\n DropTableCall,\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); `dataTransform`\n * throws 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 * 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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return dataTransform(contract, name, options, this.controlAdapter);\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new CreateTableCall(\n options.schema,\n options.table,\n options.columns,\n options.constraints,\n ).toOp(this.controlAdapter);\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new CreateSchemaCall(options.schema).toOp(this.controlAdapter);\n }\n\n protected addColumn(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: DdlColumn;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddColumnCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddPrimaryKeyCall(\n options.schema,\n options.table,\n options.constraint,\n options.columns,\n ).toOp(this.controlAdapter);\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddUniqueCall(\n options.schema,\n options.table,\n options.constraint,\n options.columns,\n ).toOp(this.controlAdapter);\n }\n\n protected addForeignKey(options: {\n readonly schema: string;\n readonly table: string;\n readonly foreignKey: ForeignKeySpec;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddForeignKeyCall(options.schema, options.table, options.foreignKey).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AddCheckConstraintCall(\n options.schema,\n options.table,\n options.constraint,\n options.column,\n options.values,\n ).toOp(this.controlAdapter);\n }\n\n protected dropCheckConstraint(options: {\n readonly schema: string;\n readonly table: string;\n readonly constraint: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropCheckConstraintCall(options.schema, options.table, options.constraint).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropConstraintCall(\n options.schema,\n options.table,\n options.constraint,\n options.kind ?? 'unique',\n ).toOp(this.controlAdapter);\n }\n\n protected dropTable(options: {\n readonly schema: string;\n readonly table: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropTableCall(options.schema, options.table).toOp(this.controlAdapter);\n }\n\n protected dropColumn(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropColumnCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new AlterColumnTypeCall(\n options.schema,\n options.table,\n options.column,\n options.options,\n ).toOp(this.controlAdapter);\n }\n\n protected setNotNull(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new SetNotNullCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\n );\n }\n\n protected dropNotNull(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropNotNullCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new SetDefaultCall(\n options.schema,\n options.table,\n options.column,\n options.defaultSql,\n options.operationClass,\n ).toOp(this.controlAdapter);\n }\n\n protected dropDefault(options: {\n readonly schema: string;\n readonly table: string;\n readonly column: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropDefaultCall(options.schema, options.table, options.column).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new CreateIndexCall(\n options.schema,\n options.table,\n options.index,\n options.columns,\n options.extras,\n ).toOp(this.controlAdapter);\n }\n\n protected dropIndex(options: {\n readonly schema: string;\n readonly table: string;\n readonly index: string;\n }): Promise<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> {\n if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return new DropIndexCall(options.schema, options.table, options.index).toOp(\n this.controlAdapter,\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 if (!this.controlAdapter) {\n throw errorPostgresMigrationStackMissing();\n }\n return installExtension(options, this.controlAdapter);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,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,IAAI,cAAyC;EAC3C,OAAO,KAAKC,SAAS;CACvB;;;;;CAMA,IAAI,gBAAoD;EACtD,OAAO,KAAKC,WAAW;CACzB;;;;;;CAOA,cACE,UACA,MACA,SAC+D;EAC/D,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,cAAc,UAAU,MAAM,SAAS,KAAK,cAAc;CACnE;;;;;;CAOA,YAAsB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,QAAQ,OACR,QAAQ,QACR,QAAQ,YACR,QAAQ,cACV,CAAC,CAAC,KAAK,KAAK,cAAc;CAC5B;CAEA,YAAsB,SAI4C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,gBAAgB,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,MAAM,CAAC,CAAC,KACxE,KAAK,cACP;CACF;CAEA,YAAsB,SAM4C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,gBACT,QAAQ,QACR,QAAQ,OACR,QAAQ,OACR,QAAQ,SACR,QAAQ,MACV,CAAC,CAAC,KAAK,KAAK,cAAc;CAC5B;CAEA,UAAoB,SAI8C;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,IAAI,cAAc,QAAQ,QAAQ,QAAQ,OAAO,QAAQ,KAAK,CAAC,CAAC,KACrE,KAAK,cACP;CACF;CAEA,iBAA2B,SAKuC;EAChE,IAAI,CAAC,KAAK,gBACR,MAAM,mCAAmC;EAE3C,OAAO,iBAAiB,SAAS,KAAK,cAAc;CACtD;AACF"}
@@ -12,18 +12,6 @@ declare class PostgresContractSerializer extends SqlContractSerializerBase<Contr
12
12
  constructor(extraPackEntityKinds?: readonly AnyEntityKindDescriptor[]);
13
13
  protected hydrateSqlNamespaceEntry(nsId: string, raw: Record<string, unknown>): Namespace | SqlNamespaceInput;
14
14
  serializeContract(contract: Contract<SqlStorage>): JsonObject;
15
- /**
16
- * Native enums are deliberately not serialized here — `native_enum` is
17
- * authoring-time-only. Once lowered, its member values live on in the
18
- * `valueSet` slot it derives (via the SQL family's generic
19
- * `deriveValueSet` mechanism); nothing downstream reads the
20
- * `PostgresNativeEnum` entity itself, so re-emitting it into
21
- * `contract.json` would be dead weight.
22
- */
23
- private serializePostgresNamespace;
24
- private serializeEntries;
25
- private serializeJsonObject;
26
- private serializeJsonValue;
27
15
  }
28
16
  //#endregion
29
17
  //#region src/exports/runtime.d.ts
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/core/postgres-contract-serializer.ts","../src/exports/runtime.ts"],"mappings":";;;;;;;;;;cAqEa,0BAAA,SAAmC,yBAAA,CAA0B,QAAA,CAAS,UAAA;cACrE,oBAAA,YAA+B,uBAAA;EAAA,UAUxB,wBAAA,CACjB,IAAA,UACA,GAAA,EAAK,MAAA,oBACJ,SAAA,GAAY,iBAAA;EAyBN,iBAAA,CAAkB,QAAA,EAAU,QAAA,CAAS,UAAA,IAAc,UAAA;;AAvC9D;;;;;;;UAyFU,0BAAA;EAAA,QAiBA,gBAAA;EAAA,QAQA,mBAAA;EAAA,QAOA,kBAAA;AAAA;;;UCpLO,6BAAA,SAAsC,qBAAqB;;;;;AD2D5E;;cCnDM,+BAAA,EAAiC,uBAAA,oBAGrC,6BAAA;EAAA,SAES,MAAA,iBAAuB,kBAAA;AAAA"}
1
+ {"version":3,"file":"runtime.d.mts","names":[],"sources":["../src/core/postgres-contract-serializer.ts","../src/exports/runtime.ts"],"mappings":";;;;;;;;;;cAqEa,0BAAA,SAAmC,yBAAA,CAA0B,QAAA,CAAS,UAAA;cACrE,oBAAA,YAA+B,uBAAA;EAAA,UAUxB,wBAAA,CACjB,IAAA,UACA,GAAA,EAAK,MAAA,oBACJ,SAAA,GAAY,iBAAA;EAyBN,iBAAA,CAAkB,QAAA,EAAU,QAAA,CAAS,UAAA,IAAc,UAAA;AAAA;;;UClG7C,6BAAA,SAAsC,qBAAqB;;;;;AD2D5E;;cCnDM,+BAAA,EAAiC,uBAAA,oBAGrC,6BAAA;EAAA,SAES,MAAA,iBAAuB,kBAAA;AAAA"}
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-V3rGJCoe.mjs";
2
+ import { n as PostgresContractSerializer, t as PostgresContractView } from "./postgres-contract-view-3xfUgjnC.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
package/package.json CHANGED
@@ -1,35 +1,35 @@
1
1
  {
2
2
  "name": "@prisma-next/target-postgres",
3
- "version": "0.14.0-dev.46",
3
+ "version": "0.14.0-dev.47",
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.14.0-dev.46",
10
- "@prisma-next/contract": "0.14.0-dev.46",
11
- "@prisma-next/errors": "0.14.0-dev.46",
12
- "@prisma-next/family-sql": "0.14.0-dev.46",
13
- "@prisma-next/framework-components": "0.14.0-dev.46",
14
- "@prisma-next/migration-tools": "0.14.0-dev.46",
15
- "@prisma-next/sql-contract": "0.14.0-dev.46",
16
- "@prisma-next/sql-errors": "0.14.0-dev.46",
17
- "@prisma-next/sql-operations": "0.14.0-dev.46",
18
- "@prisma-next/sql-relational-core": "0.14.0-dev.46",
19
- "@prisma-next/sql-schema-ir": "0.14.0-dev.46",
20
- "@prisma-next/ts-render": "0.14.0-dev.46",
21
- "@prisma-next/utils": "0.14.0-dev.46",
9
+ "@prisma-next/cli": "0.14.0-dev.47",
10
+ "@prisma-next/contract": "0.14.0-dev.47",
11
+ "@prisma-next/errors": "0.14.0-dev.47",
12
+ "@prisma-next/family-sql": "0.14.0-dev.47",
13
+ "@prisma-next/framework-components": "0.14.0-dev.47",
14
+ "@prisma-next/migration-tools": "0.14.0-dev.47",
15
+ "@prisma-next/sql-contract": "0.14.0-dev.47",
16
+ "@prisma-next/sql-errors": "0.14.0-dev.47",
17
+ "@prisma-next/sql-operations": "0.14.0-dev.47",
18
+ "@prisma-next/sql-relational-core": "0.14.0-dev.47",
19
+ "@prisma-next/sql-schema-ir": "0.14.0-dev.47",
20
+ "@prisma-next/ts-render": "0.14.0-dev.47",
21
+ "@prisma-next/utils": "0.14.0-dev.47",
22
22
  "@standard-schema/spec": "^1.1.0",
23
23
  "arktype": "^2.2.0",
24
24
  "pathe": "^2.0.3"
25
25
  },
26
26
  "devDependencies": {
27
- "@prisma-next/psl-parser": "0.14.0-dev.46",
28
- "@prisma-next/psl-printer": "0.14.0-dev.46",
29
- "@prisma-next/sql-contract-psl": "0.14.0-dev.46",
30
- "@prisma-next/test-utils": "0.14.0-dev.46",
31
- "@prisma-next/tsconfig": "0.14.0-dev.46",
32
- "@prisma-next/tsdown": "0.14.0-dev.46",
27
+ "@prisma-next/psl-parser": "0.14.0-dev.47",
28
+ "@prisma-next/psl-printer": "0.14.0-dev.47",
29
+ "@prisma-next/sql-contract-psl": "0.14.0-dev.47",
30
+ "@prisma-next/test-utils": "0.14.0-dev.47",
31
+ "@prisma-next/tsconfig": "0.14.0-dev.47",
32
+ "@prisma-next/tsdown": "0.14.0-dev.47",
33
33
  "tsdown": "0.22.1",
34
34
  "typescript": "5.9.3",
35
35
  "vitest": "4.1.8"
@@ -16,11 +16,11 @@ import {
16
16
  } from '@prisma-next/framework-components/ir';
17
17
  import type { SqlNamespaceInput, SqlStorage } from '@prisma-next/sql-contract/types';
18
18
  import { blindCast } from '@prisma-next/utils/casts';
19
- import type { JsonObject, JsonValue } from '@prisma-next/utils/json';
19
+ import type { JsonObject } from '@prisma-next/utils/json';
20
20
  import { postgresAuthoringEntityTypes } from './authoring';
21
21
  import { PG_INT_CODEC_ID, PG_TEXT_CODEC_ID } from './codec-ids';
22
22
  import { nativeEnumEntityKind, policyEntityKind, roleEntityKind } from './entity-kinds';
23
- import { isPostgresSchema, PostgresSchema } from './postgres-schema';
23
+ import { PostgresSchema } from './postgres-schema';
24
24
 
25
25
  const POSTGRES_AUTHORING_CTX: AuthoringEntityContext = {
26
26
  family: 'sql',
@@ -109,24 +109,17 @@ export class PostgresContractSerializer extends SqlContractSerializerBase<Contra
109
109
  override serializeContract(contract: Contract<SqlStorage>): JsonObject {
110
110
  const { storage, ...rest } = contract;
111
111
  const namespacesJson: Record<string, JsonObject> = {};
112
+ // Each namespace serializes to its id, its schema-kind tag, and the
113
+ // base's generic entries walk. Native enums are excluded upstream —
114
+ // carried non-enumerable on `PostgresSchema.entries`, so the walk
115
+ // never sees them.
112
116
  for (const [nsId, ns] of Object.entries(storage.namespaces)) {
113
- if (isPostgresSchema(ns)) {
114
- namespacesJson[nsId] = this.serializePostgresNamespace(ns, ns.id === UNBOUND_NAMESPACE_ID);
115
- } else {
116
- const isUnboundSlot = nsId === UNBOUND_NAMESPACE_ID;
117
- namespacesJson[nsId] = {
118
- id: nsId,
119
- kind: isUnboundSlot ? 'postgres-unbound-schema' : 'postgres-schema',
120
- entries: {
121
- table: Object.fromEntries(
122
- Object.entries(ns.entries.table ?? {}).map(([tableName, table]) => [
123
- tableName,
124
- this.serializeJsonObject(table),
125
- ]),
126
- ),
127
- },
128
- };
129
- }
117
+ const isUnboundSlot = ns.id === UNBOUND_NAMESPACE_ID;
118
+ namespacesJson[nsId] = {
119
+ id: ns.id,
120
+ kind: isUnboundSlot ? 'postgres-unbound-schema' : 'postgres-schema',
121
+ entries: this.serializeNamespaceEntries(ns.entries),
122
+ };
130
123
  }
131
124
  const storageOut: Record<string, unknown> = {
132
125
  storageHash: String(storage.storageHash),
@@ -147,50 +140,4 @@ export class PostgresContractSerializer extends SqlContractSerializerBase<Contra
147
140
  storage: storageOut,
148
141
  });
149
142
  }
150
-
151
- /**
152
- * Native enums are deliberately not serialized here — `native_enum` is
153
- * authoring-time-only. Once lowered, its member values live on in the
154
- * `valueSet` slot it derives (via the SQL family's generic
155
- * `deriveValueSet` mechanism); nothing downstream reads the
156
- * `PostgresNativeEnum` entity itself, so re-emitting it into
157
- * `contract.json` would be dead weight.
158
- */
159
- private serializePostgresNamespace(ns: PostgresSchema, isUnboundSlot: boolean): JsonObject {
160
- const tablesOut = this.serializeEntries(ns.table);
161
- const valueSetOut = this.serializeEntries(ns.valueSet ?? {});
162
- const roleOut = this.serializeEntries(ns.role);
163
- const policyOut = this.serializeEntries(ns.policy);
164
- return {
165
- id: ns.id,
166
- kind: isUnboundSlot ? 'postgres-unbound-schema' : 'postgres-schema',
167
- entries: {
168
- table: tablesOut,
169
- ...(Object.keys(valueSetOut).length > 0 ? { valueSet: valueSetOut } : {}),
170
- ...(Object.keys(roleOut).length > 0 ? { role: roleOut } : {}),
171
- ...(Object.keys(policyOut).length > 0 ? { policy: policyOut } : {}),
172
- },
173
- };
174
- }
175
-
176
- private serializeEntries(entries: Readonly<Record<string, unknown>>): Record<string, JsonObject> {
177
- const out: Record<string, JsonObject> = {};
178
- for (const [name, entry] of Object.entries(entries)) {
179
- out[name] = this.serializeJsonObject(entry);
180
- }
181
- return out;
182
- }
183
-
184
- private serializeJsonObject(value: unknown): JsonObject {
185
- return blindCast<
186
- JsonObject,
187
- 'serializeJsonValue round-trips an IR node through JSON, yielding a JsonObject'
188
- >(this.serializeJsonValue(value));
189
- }
190
-
191
- private serializeJsonValue(value: unknown): JsonValue {
192
- return blindCast<JsonValue, 'JSON.parse(JSON.stringify(x)) yields a JsonValue'>(
193
- JSON.parse(JSON.stringify(value)),
194
- );
195
- }
196
143
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"postgres-contract-view-V3rGJCoe.mjs","names":[],"sources":["../src/core/postgres-contract-serializer.ts","../src/core/postgres-contract-view.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport {\n SqlContractSerializerBase,\n type SqlEntityHydrationFactory,\n} from '@prisma-next/family-sql/ir';\nimport {\n type AuthoringEntityContext,\n type AuthoringEntityTypeFactoryOutput,\n type AuthoringEntityTypeNamespace,\n isAuthoringEntityTypeDescriptor,\n} from '@prisma-next/framework-components/authoring';\nimport {\n type AnyEntityKindDescriptor,\n type Namespace,\n UNBOUND_NAMESPACE_ID,\n} from '@prisma-next/framework-components/ir';\nimport type { SqlNamespaceInput, SqlStorage } from '@prisma-next/sql-contract/types';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport type { JsonObject, JsonValue } from '@prisma-next/utils/json';\nimport { postgresAuthoringEntityTypes } from './authoring';\nimport { PG_INT_CODEC_ID, PG_TEXT_CODEC_ID } from './codec-ids';\nimport { nativeEnumEntityKind, policyEntityKind, roleEntityKind } from './entity-kinds';\nimport { isPostgresSchema, PostgresSchema } from './postgres-schema';\n\nconst POSTGRES_AUTHORING_CTX: AuthoringEntityContext = {\n family: 'sql',\n target: 'postgres',\n enumInferenceCodecs: { text: PG_TEXT_CODEC_ID, int: PG_INT_CODEC_ID },\n};\n\nfunction isAuthoringEntityTypeFactoryOutput(\n output: unknown,\n): output is AuthoringEntityTypeFactoryOutput<unknown, unknown> {\n return (\n typeof output === 'object' &&\n output !== null &&\n 'factory' in output &&\n typeof output.factory === 'function'\n );\n}\n\n/**\n * Walks a pack's entity-type namespace tree and emits hydration factories\n * keyed by the descriptor's `discriminator`. Used for `storage.types`\n * (codec-triple hydration). Namespace entries hydration dispatches by\n * entries key, not discriminator — handled by `hydrateNamespaceEntities`.\n */\nfunction collectStorageTypesHydrators(\n namespace: AuthoringEntityTypeNamespace,\n): ReadonlyMap<string, SqlEntityHydrationFactory> {\n const registry = new Map<string, SqlEntityHydrationFactory>();\n const walk = (node: AuthoringEntityTypeNamespace): void => {\n for (const value of Object.values(node)) {\n if (isAuthoringEntityTypeDescriptor(value)) {\n if (isAuthoringEntityTypeFactoryOutput(value.output)) {\n const { factory } = value.output;\n registry.set(value.discriminator, (raw) => factory(raw, POSTGRES_AUTHORING_CTX));\n }\n continue;\n }\n if (typeof value === 'object' && value !== null) {\n walk(value);\n }\n }\n };\n walk(namespace);\n return registry;\n}\n\nexport class PostgresContractSerializer extends SqlContractSerializerBase<Contract<SqlStorage>> {\n constructor(extraPackEntityKinds: readonly AnyEntityKindDescriptor[] = []) {\n const storageTypesHydrators = collectStorageTypesHydrators(postgresAuthoringEntityTypes);\n super(storageTypesHydrators, [\n policyEntityKind,\n roleEntityKind,\n nativeEnumEntityKind,\n ...extraPackEntityKinds,\n ]);\n }\n\n protected override hydrateSqlNamespaceEntry(\n nsId: string,\n raw: Record<string, unknown>,\n ): Namespace | SqlNamespaceInput {\n const hydrated = blindCast<\n SqlNamespaceInput,\n 'raw is always plain JSON, so super.hydrateSqlNamespaceEntry returns SqlNamespaceInput'\n >(super.hydrateSqlNamespaceEntry(nsId, raw));\n const { id, entries } = hydrated;\n\n const allSlotsEmpty = Object.values(entries).every(\n (slot) => slot === undefined || Object.keys(slot).length === 0,\n );\n if (id === UNBOUND_NAMESPACE_ID && allSlotsEmpty) {\n return PostgresSchema.unbound;\n }\n const valueSetSlot = entries['valueSet'];\n const hasValueSets = valueSetSlot !== undefined && Object.keys(valueSetSlot).length > 0;\n return new PostgresSchema({\n id,\n entries: {\n ...entries,\n table: entries['table'] ?? {},\n ...(hasValueSets ? { valueSet: valueSetSlot } : {}),\n },\n });\n }\n\n override serializeContract(contract: Contract<SqlStorage>): JsonObject {\n const { storage, ...rest } = contract;\n const namespacesJson: Record<string, JsonObject> = {};\n for (const [nsId, ns] of Object.entries(storage.namespaces)) {\n if (isPostgresSchema(ns)) {\n namespacesJson[nsId] = this.serializePostgresNamespace(ns, ns.id === UNBOUND_NAMESPACE_ID);\n } else {\n const isUnboundSlot = nsId === UNBOUND_NAMESPACE_ID;\n namespacesJson[nsId] = {\n id: nsId,\n kind: isUnboundSlot ? 'postgres-unbound-schema' : 'postgres-schema',\n entries: {\n table: Object.fromEntries(\n Object.entries(ns.entries.table ?? {}).map(([tableName, table]) => [\n tableName,\n this.serializeJsonObject(table),\n ]),\n ),\n },\n };\n }\n }\n const storageOut: Record<string, unknown> = {\n storageHash: String(storage.storageHash),\n namespaces: namespacesJson,\n };\n if (storage.types !== undefined) {\n const typesOut: Record<string, JsonObject> = {};\n for (const [name, entry] of Object.entries(storage.types)) {\n typesOut[name] = this.serializeJsonObject(entry);\n }\n storageOut['types'] = typesOut;\n }\n return blindCast<\n JsonObject,\n 'contract minus storage plus a JSON-shaped storageOut is a JsonObject'\n >({\n ...rest,\n storage: storageOut,\n });\n }\n\n /**\n * Native enums are deliberately not serialized here — `native_enum` is\n * authoring-time-only. Once lowered, its member values live on in the\n * `valueSet` slot it derives (via the SQL family's generic\n * `deriveValueSet` mechanism); nothing downstream reads the\n * `PostgresNativeEnum` entity itself, so re-emitting it into\n * `contract.json` would be dead weight.\n */\n private serializePostgresNamespace(ns: PostgresSchema, isUnboundSlot: boolean): JsonObject {\n const tablesOut = this.serializeEntries(ns.table);\n const valueSetOut = this.serializeEntries(ns.valueSet ?? {});\n const roleOut = this.serializeEntries(ns.role);\n const policyOut = this.serializeEntries(ns.policy);\n return {\n id: ns.id,\n kind: isUnboundSlot ? 'postgres-unbound-schema' : 'postgres-schema',\n entries: {\n table: tablesOut,\n ...(Object.keys(valueSetOut).length > 0 ? { valueSet: valueSetOut } : {}),\n ...(Object.keys(roleOut).length > 0 ? { role: roleOut } : {}),\n ...(Object.keys(policyOut).length > 0 ? { policy: policyOut } : {}),\n },\n };\n }\n\n private serializeEntries(entries: Readonly<Record<string, unknown>>): Record<string, JsonObject> {\n const out: Record<string, JsonObject> = {};\n for (const [name, entry] of Object.entries(entries)) {\n out[name] = this.serializeJsonObject(entry);\n }\n return out;\n }\n\n private serializeJsonObject(value: unknown): JsonObject {\n return blindCast<\n JsonObject,\n 'serializeJsonValue round-trips an IR node through JSON, yielding a JsonObject'\n >(this.serializeJsonValue(value));\n }\n\n private serializeJsonValue(value: unknown): JsonValue {\n return blindCast<JsonValue, 'JSON.parse(JSON.stringify(x)) yields a JsonValue'>(\n JSON.parse(JSON.stringify(value)),\n );\n }\n}\n","import type { Contract } from '@prisma-next/contract/types';\nimport {\n buildSqlSchemaQualifiedView,\n type SqlSchemaQualifiedView,\n} from '@prisma-next/sql-contract/contract-view';\nimport type { SqlStorage } from '@prisma-next/sql-contract/types';\nimport { PostgresContractSerializer } from './postgres-contract-serializer';\n\n/**\n * A schema-qualified Postgres contract view: the deserialized contract\n * intersected with a single `namespace` member holding every schema by id. It is\n * substitutable for `Contract` (carries `storage`, `domain`, …) and reaches each\n * schema's entities through `view.namespace.<schema>`:\n *\n * ```ts\n * const view = PostgresContractView.fromJson<Contract>(contractJson);\n * view.namespace.public.table.users // typed table leaf in the public schema\n * view.namespace.auth.table.users // the auth schema's own users table\n * view.namespace.public.entries.policy.X // pack-contributed kind (RLS / #771 path)\n * view.namespace.__unbound__.table.X // default schema, keyed by its raw id\n * view.storage // the full contract is still present\n * ```\n *\n * This mirrors the runtime `db.enums.<ns>` keying exactly (the default schema\n * keeps its literal `__unbound__` id). Schema names are NOT promoted to the\n * contract root, so there is no collision with contract envelope fields — a\n * schema named `storage` is `view.namespace.storage`, while `view.storage`\n * stays the contract's `storage`.\n */\nexport type PostgresContractView<TContract extends Contract<SqlStorage> = Contract<SqlStorage>> =\n SqlSchemaQualifiedView<TContract>;\n\nexport const PostgresContractView = {\n /** Wrap an already-deserialized Postgres contract in a schema-qualified view. */\n from<TContract extends Contract<SqlStorage>>(\n contract: TContract,\n ): PostgresContractView<TContract> {\n return buildSqlSchemaQualifiedView(contract);\n },\n\n /** Deserialize a Postgres contract JSON envelope and wrap it in a view. */\n fromJson<TContract extends Contract<SqlStorage> = Contract<SqlStorage>>(\n json: unknown,\n ): PostgresContractView<TContract> {\n const contract = new PostgresContractSerializer().deserializeContract<TContract>(json);\n return buildSqlSchemaQualifiedView(contract);\n },\n};\n"],"mappings":";;;;;;;;;AAwBA,MAAM,yBAAiD;CACrD,QAAQ;CACR,QAAQ;CACR,qBAAqB;EAAE,MAAM;EAAkB,KAAK;CAAgB;AACtE;AAEA,SAAS,mCACP,QAC8D;CAC9D,OACE,OAAO,WAAW,YAClB,WAAW,QACX,aAAa,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