@prisma-next/target-postgres 0.14.0-dev.4 → 0.14.0-dev.41
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/authoring-BX1WHIdN.mjs +220 -0
- package/dist/authoring-BX1WHIdN.mjs.map +1 -0
- package/dist/canonicalize-Bn3BM1Cn.mjs +46 -0
- package/dist/canonicalize-Bn3BM1Cn.mjs.map +1 -0
- package/dist/canonicalize-CAbXtVtB.d.mts +37 -0
- package/dist/canonicalize-CAbXtVtB.d.mts.map +1 -0
- package/dist/{codec-types-DHCkwPKE.d.mts → codec-types-CueCoGD0.d.mts} +2 -2
- package/dist/{codec-types-DHCkwPKE.d.mts.map → codec-types-CueCoGD0.d.mts.map} +1 -1
- package/dist/codec-types.d.mts +1 -1
- package/dist/{codecs--0A5_4Bq.d.mts → codecs-Ca8upop6.d.mts} +12 -1
- package/dist/codecs-Ca8upop6.d.mts.map +1 -0
- package/dist/codecs.d.mts +1 -1
- package/dist/codecs.mjs +34 -1
- package/dist/codecs.mjs.map +1 -1
- package/dist/contract-free.d.mts +8 -3
- package/dist/contract-free.d.mts.map +1 -1
- package/dist/contract-free.mjs +3 -3
- package/dist/control.d.mts +1 -1
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +639 -21
- package/dist/control.mjs.map +1 -1
- package/dist/data-transform-BOWpliq8.mjs.map +1 -1
- package/dist/{data-transform-DDgWdB5o.d.mts → data-transform-qKy1U5V9.d.mts} +2 -2
- package/dist/{data-transform-DDgWdB5o.d.mts.map → data-transform-qKy1U5V9.d.mts.map} +1 -1
- package/dist/data-transform.d.mts +1 -1
- package/dist/{ddl-QDyOSeLc.mjs → ddl-BmLIe1z_.mjs} +62 -5
- package/dist/ddl-BmLIe1z_.mjs.map +1 -0
- package/dist/ddl.d.mts +3 -2
- package/dist/ddl.mjs +2 -2
- package/dist/{default-normalizer-DyyCHQWs.mjs → default-normalizer-Dug8Fez9.mjs} +119 -2
- package/dist/default-normalizer-Dug8Fez9.mjs.map +1 -0
- package/dist/default-normalizer.d.mts +1 -1
- package/dist/default-normalizer.d.mts.map +1 -1
- package/dist/default-normalizer.mjs +1 -1
- package/dist/descriptor-meta-runtime-UwYdV8fD.mjs +12 -0
- package/dist/descriptor-meta-runtime-UwYdV8fD.mjs.map +1 -0
- package/dist/descriptor-meta-tjatyhtZ.mjs +18 -0
- package/dist/descriptor-meta-tjatyhtZ.mjs.map +1 -0
- package/dist/{issue-planner-DL6g3CmE.mjs → issue-planner-DbFvaAgu.mjs} +35 -10
- package/dist/issue-planner-DbFvaAgu.mjs.map +1 -0
- package/dist/issue-planner.d.mts +3 -3
- package/dist/issue-planner.d.mts.map +1 -1
- package/dist/issue-planner.mjs +1 -1
- package/dist/migration.d.mts +5 -5
- package/dist/migration.mjs +4 -4
- package/dist/nodes-CSkPX3rI.d.mts +120 -0
- package/dist/nodes-CSkPX3rI.d.mts.map +1 -0
- package/dist/{nodes-Bbhs2rwj.mjs → nodes-Dh__NS58.mjs} +56 -2
- package/dist/nodes-Dh__NS58.mjs.map +1 -0
- package/dist/{op-factory-call-DmQEc3XV.d.mts → op-factory-call-CJWUxyUW.d.mts} +44 -13
- package/dist/op-factory-call-CJWUxyUW.d.mts.map +1 -0
- package/dist/{op-factory-call-D_p5vxwt.mjs → op-factory-call-t65c4jyY.mjs} +201 -28
- package/dist/op-factory-call-t65c4jyY.mjs.map +1 -0
- package/dist/op-factory-call.d.mts +1 -1
- package/dist/op-factory-call.mjs +1 -1
- package/dist/pack.d.mts +74 -2
- package/dist/pack.d.mts.map +1 -1
- package/dist/pack.mjs +1 -1
- package/dist/planner-CG2pLHk-.mjs +640 -0
- package/dist/planner-CG2pLHk-.mjs.map +1 -0
- package/dist/{planner-ddl-builders-B2wOwLqI.mjs → planner-ddl-builders-B8Nn6nHN.mjs} +12 -27
- package/dist/planner-ddl-builders-B8Nn6nHN.mjs.map +1 -0
- package/dist/planner-ddl-builders.d.mts +2 -4
- package/dist/planner-ddl-builders.d.mts.map +1 -1
- package/dist/planner-ddl-builders.mjs +2 -2
- package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs → planner-produced-postgres-migration-BolD0Mvc.mjs} +3 -3
- package/dist/{planner-produced-postgres-migration-Cji5vxUf.mjs.map → planner-produced-postgres-migration-BolD0Mvc.mjs.map} +1 -1
- package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts → planner-produced-postgres-migration-Cz9--XOT.d.mts} +4 -4
- package/dist/{planner-produced-postgres-migration-QqHa2C2l.d.mts.map → planner-produced-postgres-migration-Cz9--XOT.d.mts.map} +1 -1
- package/dist/planner-produced-postgres-migration.d.mts +1 -1
- package/dist/planner-produced-postgres-migration.mjs +1 -1
- package/dist/{planner-sql-checks-jqUUGyQR.mjs → planner-sql-checks-DE9c4519.mjs} +2 -2
- package/dist/{planner-sql-checks-jqUUGyQR.mjs.map → planner-sql-checks-DE9c4519.mjs.map} +1 -1
- package/dist/planner-sql-checks.mjs +1 -1
- package/dist/{planner-target-details-CIY6tLeo.d.mts → planner-target-details-HkP4RrRO.d.mts} +2 -2
- package/dist/planner-target-details-HkP4RrRO.d.mts.map +1 -0
- package/dist/planner-target-details.d.mts +1 -1
- package/dist/planner.d.mts +82 -4
- package/dist/planner.d.mts.map +1 -1
- package/dist/planner.mjs +2 -2
- package/dist/{postgres-contract-serializer-k3TAcPMY.mjs → postgres-contract-view-BegduLr6.mjs} +50 -23
- package/dist/postgres-contract-view-BegduLr6.mjs.map +1 -0
- package/dist/postgres-contract-view-C9j5cqP0.d.mts +34 -0
- package/dist/postgres-contract-view-C9j5cqP0.d.mts.map +1 -0
- package/dist/postgres-database-schema-node-os8ogEap.d.mts +183 -0
- package/dist/postgres-database-schema-node-os8ogEap.d.mts.map +1 -0
- package/dist/{postgres-migration-B5jKrXv3.mjs → postgres-migration-BfMmK6tv.mjs} +21 -2
- package/dist/postgres-migration-BfMmK6tv.mjs.map +1 -0
- package/dist/{postgres-migration-Y4YBJqkS.d.mts → postgres-migration-D7kNVWVG.d.mts} +19 -6
- package/dist/postgres-migration-D7kNVWVG.d.mts.map +1 -0
- package/dist/postgres-rls-policy--CSddvMR.d.mts +52 -0
- package/dist/postgres-rls-policy--CSddvMR.d.mts.map +1 -0
- package/dist/{postgres-schema-COGZ1ark.mjs → postgres-schema-BLIHBEfX.mjs} +108 -5
- package/dist/postgres-schema-BLIHBEfX.mjs.map +1 -0
- package/dist/postgres-schema-BywoeKlt.d.mts +189 -0
- package/dist/postgres-schema-BywoeKlt.d.mts.map +1 -0
- package/dist/postgres-table-schema-node-1nNc8XDT.mjs +248 -0
- package/dist/postgres-table-schema-node-1nNc8XDT.mjs.map +1 -0
- package/dist/render-ops.d.mts +1 -1
- package/dist/{render-typescript-KMgosran.mjs → render-typescript-7yqILcwr.mjs} +45 -16
- package/dist/render-typescript-7yqILcwr.mjs.map +1 -0
- package/dist/render-typescript.mjs +1 -1
- package/dist/resolve-ddl-schema-CL1RR1mx.mjs +20 -0
- package/dist/resolve-ddl-schema-CL1RR1mx.mjs.map +1 -0
- package/dist/rls-canonicalize.d.mts +2 -0
- package/dist/rls-canonicalize.mjs +2 -0
- package/dist/runtime.d.mts +7 -6
- package/dist/runtime.d.mts.map +1 -1
- package/dist/runtime.mjs +3 -3
- package/dist/runtime.mjs.map +1 -1
- package/dist/schema-ir-annotations.d.mts +14 -0
- package/dist/schema-ir-annotations.d.mts.map +1 -0
- package/dist/schema-ir-annotations.mjs +2 -0
- package/dist/types.d.mts +4 -140
- package/dist/types.mjs +3 -2
- package/package.json +22 -17
- package/src/contract-free/checks.ts +73 -0
- package/src/contract-free/ddl.ts +45 -1
- package/src/core/authoring.ts +115 -1
- package/src/core/codecs.ts +35 -1
- package/src/core/ddl/nodes.ts +94 -2
- package/src/core/default-normalizer.ts +122 -2
- package/src/core/descriptor-meta.ts +4 -0
- package/src/core/entity-kinds.ts +16 -0
- package/src/core/migrations/bound-schema.ts +10 -0
- package/src/core/migrations/contract-to-postgres-database-schema-node.ts +125 -0
- package/src/core/migrations/control-policy.ts +3 -0
- package/src/core/migrations/diff-database-schema.ts +191 -0
- package/src/core/migrations/issue-planner.ts +44 -3
- package/src/core/migrations/op-factory-call.ts +109 -21
- package/src/core/migrations/operations/columns.ts +24 -12
- package/src/core/migrations/operations/data-transform.ts +6 -0
- package/src/core/migrations/operations/rls.ts +106 -0
- package/src/core/migrations/operations/shared.ts +0 -30
- package/src/core/migrations/planner-ddl-builders.ts +15 -56
- package/src/core/migrations/planner-recipes.ts +31 -13
- package/src/core/migrations/planner-strategies.ts +3 -11
- package/src/core/migrations/planner-target-details.ts +3 -1
- package/src/core/migrations/planner.ts +165 -33
- package/src/core/migrations/postgres-migration.ts +34 -4
- package/src/core/migrations/render-typescript.ts +42 -15
- package/src/core/migrations/resolve-ddl-schema.ts +24 -0
- package/src/core/migrations/runner.ts +13 -16
- package/src/core/migrations/verify-postgres-namespaces.ts +24 -19
- package/src/core/postgres-contract-serializer.ts +50 -33
- package/src/core/postgres-contract-view.ts +48 -0
- package/src/core/postgres-rls-policy.ts +64 -0
- package/src/core/postgres-role.ts +37 -0
- package/src/core/postgres-schema.ts +37 -13
- package/src/core/postgres-validators.ts +20 -0
- package/src/core/psl-infer/infer-psl-contract.ts +834 -0
- package/src/core/psl-infer/postgres-default-mapping.ts +16 -0
- package/src/core/psl-infer/postgres-type-map.ts +157 -0
- package/src/core/rls/canonicalize.ts +48 -0
- package/src/core/schema-ir/postgres-database-schema-node.ts +63 -0
- package/src/core/schema-ir/postgres-namespace-schema-node.ts +61 -0
- package/src/core/schema-ir/postgres-policy-schema-node.ts +93 -0
- package/src/core/schema-ir/postgres-role-schema-node.ts +66 -0
- package/src/core/schema-ir/postgres-table-schema-node.ts +107 -0
- package/src/core/schema-ir/schema-node-kinds.ts +28 -0
- package/src/exports/contract-free.ts +7 -1
- package/src/exports/control.ts +39 -12
- package/src/exports/ddl.ts +4 -0
- package/src/exports/migration.ts +1 -0
- package/src/exports/planner-ddl-builders.ts +0 -2
- package/src/exports/planner.ts +2 -0
- package/src/exports/rls-canonicalize.ts +6 -0
- package/src/exports/runtime.ts +1 -0
- package/src/exports/schema-ir-annotations.ts +1 -0
- package/src/exports/types.ts +28 -0
- package/dist/codecs--0A5_4Bq.d.mts.map +0 -1
- package/dist/ddl-QDyOSeLc.mjs.map +0 -1
- package/dist/default-normalizer-DyyCHQWs.mjs.map +0 -1
- package/dist/descriptor-meta-CpGygXpI.mjs +0 -140
- package/dist/descriptor-meta-CpGygXpI.mjs.map +0 -1
- package/dist/issue-planner-DL6g3CmE.mjs.map +0 -1
- package/dist/nodes-Bbhs2rwj.mjs.map +0 -1
- package/dist/nodes-pLeLgdis.d.mts +0 -67
- package/dist/nodes-pLeLgdis.d.mts.map +0 -1
- package/dist/op-factory-call-D_p5vxwt.mjs.map +0 -1
- package/dist/op-factory-call-DmQEc3XV.d.mts.map +0 -1
- package/dist/planner-Bs_baQax.mjs +0 -324
- package/dist/planner-Bs_baQax.mjs.map +0 -1
- package/dist/planner-ddl-builders-B2wOwLqI.mjs.map +0 -1
- package/dist/planner-target-details-CIY6tLeo.d.mts.map +0 -1
- package/dist/postgres-contract-serializer-k3TAcPMY.mjs.map +0 -1
- package/dist/postgres-migration-B5jKrXv3.mjs.map +0 -1
- package/dist/postgres-migration-Y4YBJqkS.d.mts.map +0 -1
- package/dist/postgres-schema-COGZ1ark.mjs.map +0 -1
- package/dist/render-typescript-KMgosran.mjs.map +0 -1
- package/dist/types.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"planner-CG2pLHk-.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 { 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 ['public'];\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,OAA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Y,KAAK;CACnB,CAAC;AACH"}
|
|
@@ -2,19 +2,6 @@ import { i as quoteIdentifier, n as escapeLiteral } from "./sql-utils-DcfMz4MQ.m
|
|
|
2
2
|
import { t as resolveColumnTypeMetadata } from "./planner-type-resolution-Bt2f_q-F.mjs";
|
|
3
3
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
4
4
|
//#region src/core/migrations/planner-ddl-builders.ts
|
|
5
|
-
function buildCreateTableSql(qualifiedTableName, table, codecHooks, storageTypes = {}) {
|
|
6
|
-
const columnDefinitions = Object.entries(table.columns).map(([columnName, column]) => {
|
|
7
|
-
return [
|
|
8
|
-
quoteIdentifier(columnName),
|
|
9
|
-
buildColumnTypeSql(column, codecHooks, storageTypes),
|
|
10
|
-
buildColumnDefaultSql(column.default, column),
|
|
11
|
-
column.nullable ? "" : "NOT NULL"
|
|
12
|
-
].filter(Boolean).join(" ");
|
|
13
|
-
});
|
|
14
|
-
const constraintDefinitions = [];
|
|
15
|
-
if (table.primaryKey) constraintDefinitions.push(`PRIMARY KEY (${table.primaryKey.columns.map(quoteIdentifier).join(", ")})`);
|
|
16
|
-
return `CREATE TABLE ${qualifiedTableName} (\n ${[...columnDefinitions, ...constraintDefinitions].join(",\n ")}\n)`;
|
|
17
|
-
}
|
|
18
5
|
/**
|
|
19
6
|
* Pattern for safe PostgreSQL type names.
|
|
20
7
|
* Allows letters, digits, underscores, spaces (for "double precision", "character varying"),
|
|
@@ -50,10 +37,13 @@ function buildColumnTypeSql(column, codecHooks, storageTypes = {}, allowPseudoTy
|
|
|
50
37
|
}
|
|
51
38
|
}
|
|
52
39
|
const expanded = expandParameterizedTypeSql(resolved, codecHooks);
|
|
53
|
-
if (expanded !== null) return expanded;
|
|
54
|
-
if (column.typeRef)
|
|
40
|
+
if (expanded !== null) return column.many ? `${expanded}[]` : expanded;
|
|
41
|
+
if (column.typeRef) {
|
|
42
|
+
const base = quoteIdentifier(resolved.nativeType);
|
|
43
|
+
return column.many ? `${base}[]` : base;
|
|
44
|
+
}
|
|
55
45
|
assertSafeNativeType(resolved.nativeType);
|
|
56
|
-
return resolved.nativeType;
|
|
46
|
+
return column.many ? `${resolved.nativeType}[]` : resolved.nativeType;
|
|
57
47
|
}
|
|
58
48
|
function expandParameterizedTypeSql(column, codecHooks) {
|
|
59
49
|
if (!column.typeParams || Object.keys(column.typeParams).length === 0) return null;
|
|
@@ -84,6 +74,7 @@ function buildColumnDefaultSql(columnDefault, column) {
|
|
|
84
74
|
}
|
|
85
75
|
function renderDefaultLiteral(value, column) {
|
|
86
76
|
const isJsonColumn = column?.nativeType === "json" || column?.nativeType === "jsonb";
|
|
77
|
+
if (column?.many && Array.isArray(value)) return renderArrayLiteralDefault(value);
|
|
87
78
|
if (value instanceof Date) return `'${escapeLiteral(value.toISOString())}'`;
|
|
88
79
|
if (typeof value === "string") return `'${escapeLiteral(value)}'`;
|
|
89
80
|
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
@@ -92,17 +83,11 @@ function renderDefaultLiteral(value, column) {
|
|
|
92
83
|
if (isJsonColumn) return `'${escapeLiteral(json)}'::${column.nativeType}`;
|
|
93
84
|
return `'${escapeLiteral(json)}'`;
|
|
94
85
|
}
|
|
95
|
-
function
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
return [
|
|
99
|
-
`ALTER TABLE ${qualifiedTableName}`,
|
|
100
|
-
`ADD COLUMN ${quoteIdentifier(columnName)} ${typeSql}`,
|
|
101
|
-
defaultSql,
|
|
102
|
-
column.nullable ? "" : "NOT NULL"
|
|
103
|
-
].filter(Boolean).join(" ");
|
|
86
|
+
function renderArrayLiteralDefault(elements) {
|
|
87
|
+
if (elements.length === 0) return "'{}'";
|
|
88
|
+
return `ARRAY[${elements.map((el) => renderDefaultLiteral(el)).join(", ")}]`;
|
|
104
89
|
}
|
|
105
90
|
//#endregion
|
|
106
|
-
export {
|
|
91
|
+
export { buildColumnTypeSql as n, renderDefaultLiteral as r, buildColumnDefaultSql as t };
|
|
107
92
|
|
|
108
|
-
//# sourceMappingURL=planner-ddl-builders-
|
|
93
|
+
//# sourceMappingURL=planner-ddl-builders-B8Nn6nHN.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"planner-ddl-builders-B8Nn6nHN.mjs","names":[],"sources":["../src/core/migrations/planner-ddl-builders.ts"],"sourcesContent":["import type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { escapeLiteral, quoteIdentifier } from '../sql-utils';\nimport type { PostgresColumnDefault } from '../types';\nimport { resolveColumnTypeMetadata } from './planner-type-resolution';\n\n/**\n * Pattern for safe PostgreSQL type names.\n * Allows letters, digits, underscores, spaces (for \"double precision\", \"character varying\"),\n * and trailing [] for array types.\n */\nconst SAFE_NATIVE_TYPE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_ ]*(\\[\\])?$/;\n\nfunction assertSafeNativeType(nativeType: string): void {\n if (!SAFE_NATIVE_TYPE_PATTERN.test(nativeType)) {\n throw new Error(\n `Unsafe native type name in contract: \"${nativeType}\". ` +\n 'Native type names must match /^[a-zA-Z][a-zA-Z0-9_ ]*(\\\\[\\\\])?$/',\n );\n }\n}\n\n/**\n * Sanity check against accidental SQL injection from malformed contract files.\n * Rejects semicolons, SQL comment tokens, and dollar-quoting.\n * Not a comprehensive security boundary — the contract is developer-authored.\n */\nfunction assertSafeDefaultExpression(expression: string): void {\n if (expression.includes(';') || /--|\\/\\*|\\$\\$|\\bSELECT\\b/i.test(expression)) {\n throw new Error(\n `Unsafe default expression in contract: \"${expression}\". ` +\n 'Default expressions must not contain semicolons, SQL comment tokens, dollar-quoting, or subqueries.',\n );\n }\n}\n\n/**\n * Renders the SQL type for a column in DDL context.\n *\n * @param allowPseudoTypes - When true (default), autoincrement integer columns\n * produce SERIAL/BIGSERIAL/SMALLSERIAL pseudo-types. Set to false for contexts\n * like ALTER COLUMN TYPE where pseudo-types are invalid.\n */\nexport function buildColumnTypeSql(\n column: StorageColumn,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n allowPseudoTypes = true,\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n\n if (allowPseudoTypes) {\n const columnDefault = column.default;\n if (columnDefault?.kind === 'function' && columnDefault.expression === 'autoincrement()') {\n if (resolved.nativeType === 'int4' || resolved.nativeType === 'integer') {\n return 'SERIAL';\n }\n if (resolved.nativeType === 'int8' || resolved.nativeType === 'bigint') {\n return 'BIGSERIAL';\n }\n if (resolved.nativeType === 'int2' || resolved.nativeType === 'smallint') {\n return 'SMALLSERIAL';\n }\n }\n }\n\n const expanded = expandParameterizedTypeSql(resolved, codecHooks);\n if (expanded !== null) {\n return column.many ? `${expanded}[]` : expanded;\n }\n\n if (column.typeRef) {\n const base = quoteIdentifier(resolved.nativeType);\n return column.many ? `${base}[]` : base;\n }\n\n assertSafeNativeType(resolved.nativeType);\n return column.many ? `${resolved.nativeType}[]` : resolved.nativeType;\n}\n\nfunction expandParameterizedTypeSql(\n column: Pick<StorageColumn, 'nativeType' | 'codecId' | 'typeParams'>,\n codecHooks: ReadonlyMap<string, CodecControlHooks>,\n): string | null {\n if (!column.typeParams || Object.keys(column.typeParams).length === 0) {\n return null;\n }\n\n if (!column.codecId) {\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" but has no codecId. ` +\n 'Ensure the column is associated with a codec.',\n );\n }\n\n const hooks = codecHooks.get(column.codecId);\n if (!hooks?.expandNativeType) {\n if (hooks?.planTypeOperations) {\n return null;\n }\n throw new Error(\n `Column declares typeParams for nativeType \"${column.nativeType}\" ` +\n `but no expandNativeType hook is registered for codecId \"${column.codecId}\". ` +\n 'Ensure the extension providing this codec is included in extensionPacks.',\n );\n }\n\n const expanded = hooks.expandNativeType({\n nativeType: column.nativeType,\n codecId: column.codecId,\n ...ifDefined('typeParams', column.typeParams),\n });\n\n return expanded !== column.nativeType ? expanded : null;\n}\n\n/** Autoincrement columns use SERIAL types, so this returns empty for them. */\nexport function buildColumnDefaultSql(\n columnDefault: PostgresColumnDefault | undefined,\n column?: StorageColumn,\n): string {\n if (!columnDefault) {\n return '';\n }\n\n switch (columnDefault.kind) {\n case 'literal':\n return `DEFAULT ${renderDefaultLiteral(columnDefault.value, column)}`;\n case 'function': {\n if (columnDefault.expression === 'autoincrement()') {\n return '';\n }\n assertSafeDefaultExpression(columnDefault.expression);\n return `DEFAULT (${columnDefault.expression})`;\n }\n case 'sequence':\n return `DEFAULT nextval('${escapeLiteral(quoteIdentifier(columnDefault.name))}'::regclass)`;\n }\n}\n\nexport function renderDefaultLiteral(value: unknown, column?: StorageColumn): string {\n const isJsonColumn = column?.nativeType === 'json' || column?.nativeType === 'jsonb';\n\n if (column?.many && Array.isArray(value)) {\n return renderArrayLiteralDefault(value);\n }\n\n if (value instanceof Date) {\n return `'${escapeLiteral(value.toISOString())}'`;\n }\n if (typeof value === 'string') {\n return `'${escapeLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (value === null) {\n return 'NULL';\n }\n const json = JSON.stringify(value);\n if (isJsonColumn) {\n return `'${escapeLiteral(json)}'::${column.nativeType}`;\n }\n return `'${escapeLiteral(json)}'`;\n}\n\nfunction renderArrayLiteralDefault(elements: unknown[]): string {\n if (elements.length === 0) {\n return \"'{}'\";\n }\n const rendered = elements.map((el) => renderDefaultLiteral(el)).join(', ');\n return `ARRAY[${rendered}]`;\n}\n"],"mappings":";;;;;;;;;AAYA,MAAM,2BAA2B;AAEjC,SAAS,qBAAqB,YAA0B;CACtD,IAAI,CAAC,yBAAyB,KAAK,UAAU,GAC3C,MAAM,IAAI,MACR,yCAAyC,WAAW,qEAEtD;AAEJ;;;;;;AAOA,SAAS,4BAA4B,YAA0B;CAC7D,IAAI,WAAW,SAAS,GAAG,KAAK,2BAA2B,KAAK,UAAU,GACxE,MAAM,IAA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W;AACrD;;AAGA,SAAgB,sBACd,eACA,QACQ;CACR,IAAI,CAAC,eACH,OAAO;CAGT,QAAQ,cAAc,MAAtB;EACE,KAAK,WACH,OAAO,WAAW,qBAAqB,cAAc,OAAO,MAAM;EACpE,KAAK;GACH,IAAI,cAAc,eAAe,mBAC/B,OAAO;GAET,4BAA4B,cAAc,UAAU;GACpD,OAAO,YAAY,cAAc,WAAW;EAE9C,KAAK,YACH,OAAO,oBAAoB,cAAc,gBAAgB,cAAc,IAAI,CAAC,EAAE;CAClF;AACF;AAEA,SAAgB,qBAAqB,OAAgB,QAAgC;CACnF,MAAM,eAAe,QAAQ,eAAe,UAAU,QAAQ,eAAe;CAE7E,IAAI,QAAQ,QAAQ,MAAM,QAAQ,KAAK,GACrC,OAAO,0BAA0B,KAAK;CAGxC,IAAI,iBAAiB,MACnB,OAAO,IAAI,cAAc,MAAM,YAAY,CAAC,EAAE;CAEhD,IAAI,OAAO,UAAU,UACnB,OAAO,IAAI,cAAc,KAAK,EAAE;CAElC,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,WAChD,OAAO,OAAO,KAAK;CAErB,IAAI,UAAU,MACZ,OAAO;CAET,MAAM,OAAO,KAAK,UAAU,KAAK;CACjC,IAAI,cACF,OAAO,IAAI,cAAc,IAAI,EAAE,KAAK,OAAO;CAE7C,OAAO,IAAI,cAAc,IAAI,EAAE;AACjC;AAEA,SAAS,0BAA0B,UAA6B;CAC9D,IAAI,SAAS,WAAW,GACtB,OAAO;CAGT,OAAO,SADU,SAAS,KAAK,OAAO,qBAAqB,EAAE,CAAC,CAAC,CAAC,KAAK,IAC9C,EAAE;AAC3B"}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { t as PostgresColumnDefault } from "./types-BDKkx8MA.mjs";
|
|
2
2
|
import { CodecControlHooks } from "@prisma-next/family-sql/control";
|
|
3
|
-
import { StorageColumn,
|
|
3
|
+
import { StorageColumn, StorageTypeInstance } from "@prisma-next/sql-contract/types";
|
|
4
4
|
|
|
5
5
|
//#region src/core/migrations/planner-ddl-builders.d.ts
|
|
6
|
-
declare function buildCreateTableSql(qualifiedTableName: string, table: StorageTable, codecHooks: ReadonlyMap<string, CodecControlHooks>, storageTypes?: Record<string, StorageTypeInstance>): string;
|
|
7
6
|
/**
|
|
8
7
|
* Renders the SQL type for a column in DDL context.
|
|
9
8
|
*
|
|
@@ -15,7 +14,6 @@ declare function buildColumnTypeSql(column: StorageColumn, codecHooks: ReadonlyM
|
|
|
15
14
|
/** Autoincrement columns use SERIAL types, so this returns empty for them. */
|
|
16
15
|
declare function buildColumnDefaultSql(columnDefault: PostgresColumnDefault | undefined, column?: StorageColumn): string;
|
|
17
16
|
declare function renderDefaultLiteral(value: unknown, column?: StorageColumn): string;
|
|
18
|
-
declare function buildAddColumnSql(qualifiedTableName: string, columnName: string, column: StorageColumn, codecHooks: ReadonlyMap<string, CodecControlHooks>, temporaryDefault?: string | null, storageTypes?: Record<string, StorageTypeInstance>): string;
|
|
19
17
|
//#endregion
|
|
20
|
-
export {
|
|
18
|
+
export { buildColumnDefaultSql, buildColumnTypeSql, renderDefaultLiteral };
|
|
21
19
|
//# sourceMappingURL=planner-ddl-builders.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planner-ddl-builders.d.mts","names":[],"sources":["../src/core/migrations/planner-ddl-builders.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"planner-ddl-builders.d.mts","names":[],"sources":["../src/core/migrations/planner-ddl-builders.ts"],"mappings":";;;;;;;AA4CA;;;;;iBAAgB,kBAAA,CACd,MAAA,EAAQ,aAAA,EACR,UAAA,EAAY,WAAA,SAAoB,iBAAA,GAChC,YAAA,GAAc,MAAA,SAAe,mBAAA,GAC7B,gBAAA;;iBAsEc,qBAAA,CACd,aAAA,EAAe,qBAAA,cACf,MAAA,GAAS,aAAa;AAAA,iBAqBR,oBAAA,CAAqB,KAAA,WAAgB,MAAA,GAAS,aAAa"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
1
|
+
import { n as buildColumnTypeSql, r as renderDefaultLiteral, t as buildColumnDefaultSql } from "./planner-ddl-builders-B8Nn6nHN.mjs";
|
|
2
|
+
export { buildColumnDefaultSql, buildColumnTypeSql, renderDefaultLiteral };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as PostgresMigration } from "./postgres-migration-
|
|
1
|
+
import { t as PostgresMigration } from "./postgres-migration-BfMmK6tv.mjs";
|
|
2
2
|
import { t as renderOps } from "./render-ops-BREh1kHe.mjs";
|
|
3
|
-
import { t as renderCallsToTypeScript } from "./render-typescript-
|
|
3
|
+
import { t as renderCallsToTypeScript } from "./render-typescript-7yqILcwr.mjs";
|
|
4
4
|
//#region src/core/migrations/planner-produced-postgres-migration.ts
|
|
5
5
|
var TypeScriptRenderablePostgresMigration = class extends PostgresMigration {
|
|
6
6
|
#calls;
|
|
@@ -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-
|
|
43
|
+
//# sourceMappingURL=planner-produced-postgres-migration-BolD0Mvc.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planner-produced-postgres-migration-
|
|
1
|
+
{"version":3,"file":"planner-produced-postgres-migration-BolD0Mvc.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,9 +1,9 @@
|
|
|
1
|
-
import { t as PostgresPlanTargetDetails } from "./planner-target-details-
|
|
2
|
-
import { t as PostgresMigration } from "./postgres-migration-
|
|
1
|
+
import { t as PostgresPlanTargetDetails } from "./planner-target-details-HkP4RrRO.mjs";
|
|
2
|
+
import { t as PostgresMigration } from "./postgres-migration-D7kNVWVG.mjs";
|
|
3
3
|
import { SqlMigrationPlanOperation } from "@prisma-next/family-sql/control";
|
|
4
4
|
import { MigrationPlanWithAuthoringSurface, OpFactoryCall } from "@prisma-next/framework-components/control";
|
|
5
|
-
import { ExecuteRequestLowerer } from "@prisma-next/family-sql/control-adapter";
|
|
6
5
|
import { MigrationMeta } from "@prisma-next/migration-tools/migration";
|
|
6
|
+
import { ExecuteRequestLowerer } from "@prisma-next/family-sql/control-adapter";
|
|
7
7
|
|
|
8
8
|
//#region src/core/migrations/planner-produced-postgres-migration.d.ts
|
|
9
9
|
declare class TypeScriptRenderablePostgresMigration extends PostgresMigration implements MigrationPlanWithAuthoringSurface {
|
|
@@ -21,4 +21,4 @@ declare class TypeScriptRenderablePostgresMigration extends PostgresMigration im
|
|
|
21
21
|
}
|
|
22
22
|
//#endregion
|
|
23
23
|
export { TypeScriptRenderablePostgresMigration as t };
|
|
24
|
-
//# sourceMappingURL=planner-produced-postgres-migration-
|
|
24
|
+
//# sourceMappingURL=planner-produced-postgres-migration-Cz9--XOT.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planner-produced-postgres-migration-
|
|
1
|
+
{"version":3,"file":"planner-produced-postgres-migration-Cz9--XOT.d.mts","names":[],"sources":["../src/core/migrations/planner-produced-postgres-migration.ts"],"mappings":";;;;;;;;cAqCa,qCAAA,SACH,iBAAA,YACG,iCAAA;EAAA;cAcT,KAAA,WAAgB,aAAA,IAChB,IAAA,EAAM,aAAA,EACN,OAAA,UACA,OAAA,GAAU,qBAAA;EAAA,IASC,UAAA,cACT,yBAAA,CAA0B,yBAAA,IAC1B,OAAA,CAAQ,yBAAA,CAA0B,yBAAA;EAM7B,QAAA,IAAY,aAAA;EARR;;;;;EAAA,IAiBT,OAAA;EAIJ,gBAAA;AAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-
|
|
1
|
+
import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-Cz9--XOT.mjs";
|
|
2
2
|
export { TypeScriptRenderablePostgresMigration };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-
|
|
1
|
+
import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-BolD0Mvc.mjs";
|
|
2
2
|
export { TypeScriptRenderablePostgresMigration };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as postgresCreateNamespace } from "./postgres-schema-
|
|
1
|
+
import { i as postgresCreateNamespace } from "./postgres-schema-BLIHBEfX.mjs";
|
|
2
2
|
import { i as quoteIdentifier } from "./sql-utils-DcfMz4MQ.mjs";
|
|
3
3
|
import { t as resolveColumnTypeMetadata } from "./planner-type-resolution-Bt2f_q-F.mjs";
|
|
4
4
|
//#region src/core/migrations/planner-sql-checks.ts
|
|
@@ -149,4 +149,4 @@ function buildExpectedFormatType(column, codecHooks, storageTypes = {}) {
|
|
|
149
149
|
//#endregion
|
|
150
150
|
export { qualifyTableName as n, buildExpectedFormatType as t };
|
|
151
151
|
|
|
152
|
-
//# sourceMappingURL=planner-sql-checks-
|
|
152
|
+
//# sourceMappingURL=planner-sql-checks-DE9c4519.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planner-sql-checks-
|
|
1
|
+
{"version":3,"file":"planner-sql-checks-DE9c4519.mjs","names":[],"sources":["../src/core/migrations/planner-sql-checks.ts"],"sourcesContent":["import type { CodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { StorageColumn, StorageTypeInstance } from '@prisma-next/sql-contract/types';\nimport { postgresCreateNamespace } from '../postgres-schema';\nimport { quoteIdentifier } from '../sql-utils';\nimport { resolveColumnTypeMetadata } from './planner-type-resolution';\n\n/**\n * String-keyed entry points the migration ops use to render\n * schema-qualified DDL and catalog checks. The `schema` argument is\n * interpreted as a namespace coordinate: the framework `__unbound__`\n * sentinel resolves to the late-bound `PostgresUnboundSchema` singleton\n * (which elides the qualifier so `search_path` decides at runtime); any\n * other id materialises a `PostgresSchema(id)` whose qualifier is the\n * named schema. Helpers route through these `Namespace` concretions so\n * the unbound branch lives in the polymorphic override, not the call\n * site.\n */\nexport function qualifyTableName(schema: string, table: string): string {\n return postgresCreateNamespace({ id: schema, entries: { table: {} } }).qualifyTable(table);\n}\n\nconst FORMAT_TYPE_DISPLAY: ReadonlyMap<string, string> = new Map([\n ['int2', 'smallint'],\n ['int4', 'integer'],\n ['int8', 'bigint'],\n ['float4', 'real'],\n ['float8', 'double precision'],\n ['bool', 'boolean'],\n ['timestamp', 'timestamp without time zone'],\n ['timestamptz', 'timestamp with time zone'],\n ['time', 'time without time zone'],\n ['timetz', 'time with time zone'],\n]);\n\nconst UNQUOTED_POSTGRES_IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_$]*$/;\n\nconst POSTGRES_RESERVED_IDENTIFIER_WORDS = new Set([\n 'all',\n 'analyse',\n 'analyze',\n 'and',\n 'any',\n 'array',\n 'as',\n 'asc',\n 'asymmetric',\n 'authorization',\n 'between',\n 'binary',\n 'both',\n 'case',\n 'cast',\n 'check',\n 'collate',\n 'column',\n 'constraint',\n 'create',\n 'current_catalog',\n 'current_date',\n 'current_role',\n 'current_time',\n 'current_timestamp',\n 'current_user',\n 'default',\n 'deferrable',\n 'desc',\n 'distinct',\n 'do',\n 'else',\n 'end',\n 'except',\n 'false',\n 'fetch',\n 'for',\n 'foreign',\n 'freeze',\n 'from',\n 'full',\n 'grant',\n 'group',\n 'having',\n 'ilike',\n 'in',\n 'initially',\n 'inner',\n 'intersect',\n 'into',\n 'is',\n 'isnull',\n 'join',\n 'lateral',\n 'leading',\n 'left',\n 'like',\n 'limit',\n 'localtime',\n 'localtimestamp',\n 'natural',\n 'not',\n 'notnull',\n 'null',\n 'offset',\n 'on',\n 'only',\n 'or',\n 'order',\n 'outer',\n 'overlaps',\n 'placing',\n 'primary',\n 'references',\n 'right',\n 'select',\n 'session_user',\n 'similar',\n 'some',\n 'symmetric',\n 'table',\n 'then',\n 'to',\n 'trailing',\n 'true',\n 'union',\n 'unique',\n 'user',\n 'using',\n 'variadic',\n 'verbose',\n 'when',\n 'where',\n 'window',\n 'with',\n]);\n\nfunction formatUserDefinedTypeName(identifier: string): string {\n if (\n UNQUOTED_POSTGRES_IDENTIFIER_PATTERN.test(identifier) &&\n !POSTGRES_RESERVED_IDENTIFIER_WORDS.has(identifier)\n ) {\n return identifier;\n }\n\n return quoteIdentifier(identifier);\n}\n\nexport function buildExpectedFormatType(\n column: StorageColumn,\n codecHooks: Map<string, CodecControlHooks>,\n storageTypes: Record<string, StorageTypeInstance> = {},\n): string {\n const resolved = resolveColumnTypeMetadata(column, storageTypes);\n\n if (resolved.typeParams && resolved.codecId) {\n const hooks = codecHooks.get(resolved.codecId);\n if (hooks?.expandNativeType) {\n return hooks.expandNativeType({\n nativeType: resolved.nativeType,\n codecId: resolved.codecId,\n typeParams: resolved.typeParams,\n });\n }\n }\n\n if (column.typeRef) {\n return formatUserDefinedTypeName(resolved.nativeType);\n }\n\n return FORMAT_TYPE_DISPLAY.get(resolved.nativeType) ?? resolved.nativeType;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,SAAgB,iBAAiB,QAAgB,OAAuB;CACtE,OAAO,wBAAwB;EAAE,IAAI;EAAQ,SAAS,EAAE,OAAO,CAAC,EAAE;CAAE,CAAC,CAAC,CAAC,aAAa,KAAK;AAC3F;AAEA,MAAM,sBAAmD,IAAI,IAAI;CAC/D,CAAC,QAAQ,UAAU;CACnB,CAAC,QAAQ,SAAS;CAClB,CAAC,QAAQ,QAAQ;CACjB,CAAC,UAAU,MAAM;CACjB,CAAC,UAAU,kBAAkB;CAC7B,CAAC,QAAQ,SAAS;CAClB,CAAC,aAAa,6BAA6B;CAC3C,CAAC,eAAe,0BAA0B;CAC1C,CAAC,QAAQ,wBAAwB;CACjC,CAAC,UAAU,qBAAqB;AAClC,CAAC;AAED,MAAM,uCAAuC;AAE7C,MAAM,qCAAqC,IAAI,IAAI;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,SAAS,0BAA0B,YAA4B;CAC7D,IACE,qCAAqC,KAAK,UAAU,KACpD,CAAC,mCAAmC,IAAI,UAAU,GAElD,OAAO;CAGT,OAAO,gBAAgB,UAAU;AACnC;AAEA,SAAgB,wBACd,QACA,YACA,eAAoD,CAAC,GAC7C;CACR,MAAM,WAAW,0BAA0B,QAAQ,YAAY;CAE/D,IAAI,SAAS,cAAc,SAAS,SAAS;EAC3C,MAAM,QAAQ,WAAW,IAAI,SAAS,OAAO;EAC7C,IAAI,OAAO,kBACT,OAAO,MAAM,iBAAiB;GAC5B,YAAY,SAAS;GACrB,SAAS,SAAS;GAClB,YAAY,SAAS;EACvB,CAAC;CAEL;CAEA,IAAI,OAAO,SACT,OAAO,0BAA0B,SAAS,UAAU;CAGtD,OAAO,oBAAoB,IAAI,SAAS,UAAU,KAAK,SAAS;AAClE"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as qualifyTableName, t as buildExpectedFormatType } from "./planner-sql-checks-
|
|
1
|
+
import { n as qualifyTableName, t as buildExpectedFormatType } from "./planner-sql-checks-DE9c4519.mjs";
|
|
2
2
|
export { buildExpectedFormatType, qualifyTableName };
|
package/dist/{planner-target-details-CIY6tLeo.d.mts → planner-target-details-HkP4RrRO.d.mts}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
//#region src/core/migrations/planner-target-details.d.ts
|
|
2
|
-
type OperationClass = 'dependency' | 'type' | 'table' | 'column' | 'primaryKey' | 'unique' | 'index' | 'foreignKey' | 'checkConstraint';
|
|
2
|
+
type OperationClass = 'dependency' | 'type' | 'table' | 'column' | 'primaryKey' | 'unique' | 'index' | 'foreignKey' | 'checkConstraint' | 'rlsPolicy' | 'rowLevelSecurity';
|
|
3
3
|
interface PostgresPlanTargetDetails {
|
|
4
4
|
readonly schema: string;
|
|
5
5
|
readonly objectType: OperationClass;
|
|
@@ -8,4 +8,4 @@ interface PostgresPlanTargetDetails {
|
|
|
8
8
|
}
|
|
9
9
|
//#endregion
|
|
10
10
|
export { PostgresPlanTargetDetails as t };
|
|
11
|
-
//# sourceMappingURL=planner-target-details-
|
|
11
|
+
//# sourceMappingURL=planner-target-details-HkP4RrRO.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"planner-target-details-HkP4RrRO.d.mts","names":[],"sources":["../src/core/migrations/planner-target-details.ts"],"mappings":";KAEY,cAAA;AAAA,UAaK,yBAAA;EAAA,SACN,MAAA;EAAA,SACA,UAAA,EAAY,cAAc;EAAA,SAC1B,IAAA;EAAA,SACA,KAAA;AAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as PostgresPlanTargetDetails } from "./planner-target-details-
|
|
1
|
+
import { t as PostgresPlanTargetDetails } from "./planner-target-details-HkP4RrRO.mjs";
|
|
2
2
|
export type { PostgresPlanTargetDetails };
|
package/dist/planner.d.mts
CHANGED
|
@@ -1,10 +1,69 @@
|
|
|
1
|
-
import { t as
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { t as PostgresContract } from "./postgres-schema-BywoeKlt.mjs";
|
|
2
|
+
import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-Cz9--XOT.mjs";
|
|
3
|
+
import { t as PostgresDatabaseSchemaNode } from "./postgres-database-schema-node-os8ogEap.mjs";
|
|
4
|
+
import { ContractToSchemaIROptions, MigrationOperationPolicy, SqlPlannerConflict, SqlPlannerFailureResult } from "@prisma-next/family-sql/control";
|
|
5
|
+
import { SqlStorage } from "@prisma-next/sql-contract/types";
|
|
6
|
+
import { SqlSchemaIRNode } from "@prisma-next/sql-schema-ir/types";
|
|
7
|
+
import { DiffableNode, MigrationPlanWithAuthoringSurface, MigrationPlanner, MigrationScaffoldContext, SchemaDiff } from "@prisma-next/framework-components/control";
|
|
4
8
|
import { Contract } from "@prisma-next/contract/types";
|
|
5
9
|
import { ExecuteRequestLowerer } from "@prisma-next/family-sql/control-adapter";
|
|
6
10
|
import { TargetBoundComponentDescriptor } from "@prisma-next/framework-components/components";
|
|
7
11
|
|
|
12
|
+
//#region src/core/migrations/contract-to-postgres-database-schema-node.d.ts
|
|
13
|
+
/**
|
|
14
|
+
* Projects a Postgres contract into the expected schema-diff tree: a
|
|
15
|
+
* `PostgresDatabaseSchemaNode` root holding one `PostgresNamespaceSchemaNode`
|
|
16
|
+
* per Postgres namespace, each holding its `PostgresTableSchemaNode`s with
|
|
17
|
+
* their `PostgresPolicySchemaNode`s, plus the database roles on the root.
|
|
18
|
+
*
|
|
19
|
+
* Not a duplicate of the family's `contractToSchemaIR`: that builds a flat,
|
|
20
|
+
* single `{ tables }` map (and throws on cross-namespace name collisions, with
|
|
21
|
+
* no RLS/role concept) for SQLite's single-schema world. This is the
|
|
22
|
+
* Postgres-specific *tree* shape — multi-schema, RLS-policy-aware, role-aware.
|
|
23
|
+
* It reuses the family's per-namespace table conversion (`contractNamespaceToSchemaIR`)
|
|
24
|
+
* for column/FK/index building and only adds the Postgres tree/policy/role shape.
|
|
25
|
+
*
|
|
26
|
+
* Tables are grouped by their owning namespace (resolved DDL schema name) so
|
|
27
|
+
* the tree mirrors Postgres's object hierarchy. The DDL schema name is
|
|
28
|
+
* resolved once per namespace.
|
|
29
|
+
*
|
|
30
|
+
* A policy that references a table absent from its namespace is a malformed
|
|
31
|
+
* contract — the loop throws rather than fabricating a stub table.
|
|
32
|
+
*/
|
|
33
|
+
declare function contractToPostgresDatabaseSchemaNode(contract: PostgresContract | null, options: ContractToSchemaIROptions): PostgresDatabaseSchemaNode;
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/core/schema-ir/schema-node-kinds.d.ts
|
|
36
|
+
/**
|
|
37
|
+
* A Postgres schema-diff-tree node: a `SqlSchemaIRNode` that also implements
|
|
38
|
+
* `DiffableNode` (the five `Postgres*SchemaNode` classes). `SqlSchemaIRNode`
|
|
39
|
+
* alone is not a `DiffableNode` — its relational subclasses (`SqlColumnIR`, …)
|
|
40
|
+
* carry no `id`/`isEqualTo`/`children` — so this intersection is the honest node
|
|
41
|
+
* type the differ produces and the planner consumes (`SchemaDiff<SqlSchemaDiffNode>`).
|
|
42
|
+
*/
|
|
43
|
+
type SqlSchemaDiffNode = SqlSchemaIRNode & DiffableNode;
|
|
44
|
+
//#endregion
|
|
45
|
+
//#region src/core/migrations/diff-database-schema.d.ts
|
|
46
|
+
interface PostgresDiffDatabaseSchemaInput {
|
|
47
|
+
readonly contract: Contract<SqlStorage>;
|
|
48
|
+
readonly actualSchema: SqlSchemaIRNode;
|
|
49
|
+
readonly strict: boolean;
|
|
50
|
+
readonly typeMetadataRegistry: ReadonlyMap<string, {
|
|
51
|
+
readonly nativeType?: string;
|
|
52
|
+
}>;
|
|
53
|
+
readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The `SchemaDiffer` for Postgres: the target's black-box comparison,
|
|
57
|
+
* projected to the two issue lists. Namespace presence (`missing_schema` →
|
|
58
|
+
* `CREATE SCHEMA`) is intentionally NOT composed here: it is a planner-only
|
|
59
|
+
* op-generation concern (verify rejects on the relational `missing_table` a
|
|
60
|
+
* missing schema already produces), so the planner stitches it in around this
|
|
61
|
+
* diff. Control-policy suppression of the policy issues is likewise a
|
|
62
|
+
* per-consumer post-step (verify filters the issues; the planner filters the
|
|
63
|
+
* calls).
|
|
64
|
+
*/
|
|
65
|
+
declare function diffPostgresDatabaseSchema(input: PostgresDiffDatabaseSchemaInput): SchemaDiff<SqlSchemaDiffNode>;
|
|
66
|
+
//#endregion
|
|
8
67
|
//#region src/core/migrations/planner.d.ts
|
|
9
68
|
declare function createPostgresMigrationPlanner(lowerer: ExecuteRequestLowerer): PostgresMigrationPlanner;
|
|
10
69
|
/**
|
|
@@ -68,9 +127,28 @@ declare class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postg
|
|
|
68
127
|
}): PostgresPlanResult;
|
|
69
128
|
emptyMigration(context: MigrationScaffoldContext, spaceId: string): MigrationPlanWithAuthoringSurface;
|
|
70
129
|
private planSql;
|
|
130
|
+
/**
|
|
131
|
+
* Maps the RLS policy presence findings of the shared
|
|
132
|
+
* `diffPostgresDatabaseSchema` (already ownership-filtered) into
|
|
133
|
+
* `ENABLE RLS` / `CREATE POLICY` / `DROP POLICY` ops. It no longer re-diffs —
|
|
134
|
+
* it consumes the `schemaDiffIssues` of the one combined diff.
|
|
135
|
+
*/
|
|
136
|
+
private planPostgresSchemaDiff;
|
|
71
137
|
private ensureAdditivePolicy;
|
|
138
|
+
/**
|
|
139
|
+
* The structural issue list `planIssues` consumes: the relational findings
|
|
140
|
+
* from the shared `diffPostgresDatabaseSchema` plus namespace presence.
|
|
141
|
+
*
|
|
142
|
+
* Schema presence (`missing_schema` → `CREATE SCHEMA`) is a planner-only
|
|
143
|
+
* op-generation concern, so it is stitched in here rather than inside the
|
|
144
|
+
* shared diff — verify never needs it (a missing schema already surfaces as
|
|
145
|
+
* `missing_table` in the relational findings). It reads `existingSchemas` off
|
|
146
|
+
* the database root, so it takes the whole tree. Policy drift is handled
|
|
147
|
+
* separately via `planPostgresSchemaDiff` from the same shared diff's
|
|
148
|
+
* `schemaDiffIssues`.
|
|
149
|
+
*/
|
|
72
150
|
private collectSchemaIssues;
|
|
73
151
|
}
|
|
74
152
|
//#endregion
|
|
75
|
-
export { createPostgresMigrationPlanner };
|
|
153
|
+
export { contractToPostgresDatabaseSchemaNode, createPostgresMigrationPlanner, diffPostgresDatabaseSchema };
|
|
76
154
|
//# sourceMappingURL=planner.d.mts.map
|
package/dist/planner.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"planner.d.mts","names":[],"sources":["../src/core/migrations/planner.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"planner.d.mts","names":[],"sources":["../src/core/migrations/contract-to-postgres-database-schema-node.ts","../src/core/schema-ir/schema-node-kinds.ts","../src/core/migrations/diff-database-schema.ts","../src/core/migrations/planner.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+CA;;;;;;;;;;;iBAAgB,oCAAA,CACd,QAAA,EAAU,gBAAA,SACV,OAAA,EAAS,yBAAA,GACR,0BAAA;;;;;;;;;;KCxCS,iBAAA,GAAoB,eAAA,GAAkB,YAAY;;;UCSpD,+BAAA;EAAA,SACC,QAAA,EAAU,QAAA,CAAS,UAAA;EAAA,SACnB,YAAA,EAAc,eAAA;EAAA,SACd,MAAA;EAAA,SACA,oBAAA,EAAsB,WAAA;IAAA,SAA+B,UAAA;EAAA;EAAA,SACrD,mBAAA,EAAqB,aAAA,CAAc,8BAAA;AAAA;;;;;;;;;;AF0BjB;iBEiDb,0BAAA,CACd,KAAA,EAAO,+BAAA,GACN,UAAA,CAAW,iBAAA;;;iBCzCE,8BAAA,CACd,OAAA,EAAS,qBAAA,GACR,wBAAwB;;;;;;AHf3B;;KG0BY,kBAAA;EAAA,SAEG,IAAA;EAAA,SACA,IAAA,EAAM,qCAAA;EAAA,SACN,QAAA,YAAoB,kBAAA;AAAA,IAE/B,uBAAA;;;;;;;;AH7ByB;;;;ACxC7B;;;;AAA8D;cEuFjD,wBAAA,YAAoC,gBAAA;EAAA;cAGnC,OAAA,GAAU,qBAAA;EAItB,IAAA,CAAK,OAAA;IAAA,SACM,QAAA;IAAA,SACA,MAAA;IAAA,SACA,MAAA,EAAQ,wBAAA;IDvFA;;;;;;;;;;;;;;IAAA,SCsGR,YAAA,EAAc,QAAA;IAAA,SACd,UAAA;IAAA,SACA,mBAAA,EAAqB,aAAA,CAAc,8BAAA;IDpGhB;;;AAA4C;AA2E5E;IA3EgC,SC0GnB,OAAA;EAAA,IACP,kBAAA;EAIJ,cAAA,CACE,OAAA,EAAS,wBAAA,EACT,OAAA,WACC,iCAAA;EAAA,QAYK,OAAA;EDjDP;;;;;;EAAA,QC8LO,sBAAA;EAAA,QA+CA,oBAAA;ED7OqB;;;;ACzC/B;;;;;;;;EDyC+B,QCsQrB,mBAAA;AAAA"}
|
package/dist/planner.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as createPostgresMigrationPlanner } from "./planner-
|
|
2
|
-
export { createPostgresMigrationPlanner };
|
|
1
|
+
import { i as contractToPostgresDatabaseSchemaNode, n as diffPostgresDatabaseSchema, t as createPostgresMigrationPlanner } from "./planner-CG2pLHk-.mjs";
|
|
2
|
+
export { contractToPostgresDatabaseSchemaNode, createPostgresMigrationPlanner, diffPostgresDatabaseSchema };
|