@prisma/orm-target-postgres 8.0.0-rc.18-dev.25 → 8.0.0-rc.18-dev.27
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/{adapter-UEtFYllx-DXa1Ekth.mjs → adapter-BkfuSVLm-DmjWB5c9.mjs} +14 -14
- package/dist/adapter-BkfuSVLm-DmjWB5c9.mjs.map +1 -0
- package/dist/{adapter-CA0jY1EK.d.mts → adapter-vfsQ80l6.d.mts} +3 -3
- package/dist/adapter-vfsQ80l6.d.mts.map +1 -0
- package/dist/adapter.d.mts +3 -4
- package/dist/adapter.mjs +6 -7
- package/dist/adapter__adapter.d.mts +1 -1
- package/dist/adapter__adapter.mjs +2 -2
- package/dist/adapter__control.d.mts +2 -3
- package/dist/adapter__control.mjs +8 -9
- package/dist/adapter__control.mjs.map +1 -1
- package/dist/adapter__runtime.mjs +6 -6
- package/dist/adapter__runtime.mjs.map +1 -1
- package/dist/adapter__sql-renderer.mjs +1 -1
- package/dist/{authoring-mmK5aduF-BltVG_HJ.mjs → authoring-DhyLHFHA-pB4NuFxh.mjs} +5 -5
- package/dist/{authoring-mmK5aduF-BltVG_HJ.mjs.map → authoring-DhyLHFHA-pB4NuFxh.mjs.map} +1 -1
- package/dist/{autoincrement-widths-djl9Gw7k-C4Vk6s7I.mjs → autoincrement-widths-1v9UfTSw-NFaqRGCV.mjs} +3 -3
- package/dist/{autoincrement-widths-djl9Gw7k-C4Vk6s7I.mjs.map → autoincrement-widths-1v9UfTSw-NFaqRGCV.mjs.map} +1 -1
- package/dist/{check-expressions-DoxKokL1-RVvYRdA6.mjs → check-expressions-7uCCP01t-WtUqfqkP.mjs} +3 -3
- package/dist/{check-expressions-DoxKokL1-RVvYRdA6.mjs.map → check-expressions-7uCCP01t-WtUqfqkP.mjs.map} +1 -1
- package/dist/{codec-registry-CvKdYTYj-4xXqgKKs.mjs → codec-registry-T79ktJL4-B9_zlIhI.mjs} +4 -4
- package/dist/{codec-registry-CvKdYTYj-4xXqgKKs.mjs.map → codec-registry-T79ktJL4-B9_zlIhI.mjs.map} +1 -1
- package/dist/{codecs-D183NDmb-DKryvPH2.mjs → codecs-UZ1NEbvk-CMnI6Ti0.mjs} +3 -3
- package/dist/{codecs-D183NDmb-DKryvPH2.mjs.map → codecs-UZ1NEbvk-CMnI6Ti0.mjs.map} +1 -1
- package/dist/{contract-contributions-DrHk5h_E-BbmViVsC.mjs → contract-contributions-CQqafzSC-DrMFSSO4.mjs} +49 -40
- package/dist/contract-contributions-CQqafzSC-DrMFSSO4.mjs.map +1 -0
- package/dist/{contract-free-CiUW36L2.mjs → contract-free-Kwm74Hg9.mjs} +3 -3
- package/dist/{contract-free-CiUW36L2.mjs.map → contract-free-Kwm74Hg9.mjs.map} +1 -1
- package/dist/{control-policy-BdfDPcjX-BueP9PBT.mjs → control-policy-BHjZnca1-DUWuKmdJ.mjs} +65 -89
- package/dist/control-policy-BHjZnca1-DUWuKmdJ.mjs.map +1 -0
- package/dist/{control-l0spLFiu.d.mts → control-vBNwKZ7Q.d.mts} +6 -4
- package/dist/control-vBNwKZ7Q.d.mts.map +1 -0
- package/dist/{data-type-entries-KJ4Mn8C5-DY3rLz33.mjs → data-type-entries-CqnLlCkK-uN0WjREd.mjs} +3 -3
- package/dist/{data-type-entries-KJ4Mn8C5-DY3rLz33.mjs.map → data-type-entries-CqnLlCkK-uN0WjREd.mjs.map} +1 -1
- package/dist/{data-types-BkFfMhgz.d.mts → data-types-BTUMiCZS.d.mts} +5 -2
- package/dist/data-types-BTUMiCZS.d.mts.map +1 -0
- package/dist/{data-types-CQs1yW4F-CSexn8mK.mjs → data-types-Cs-LkJBw-CJN57Y5M.mjs} +4 -4
- package/dist/{data-types-CQs1yW4F-CSexn8mK.mjs.map → data-types-Cs-LkJBw-CJN57Y5M.mjs.map} +1 -1
- package/dist/{ddl-V9Yxnoa6-BcStSw33.mjs → ddl-2L13tYjC-enYPQJnG.mjs} +5 -5
- package/dist/{ddl-V9Yxnoa6-BcStSw33.mjs.map → ddl-2L13tYjC-enYPQJnG.mjs.map} +1 -1
- package/dist/{default-normalizer-BqFHmlox-CP8ywN-r.mjs → default-normalizer-BqK6XxdC-BAgxt9FF.mjs} +10 -12
- package/dist/default-normalizer-BqK6XxdC-BAgxt9FF.mjs.map +1 -0
- package/dist/{default-normalizer-CTAiFe9Y.d.mts → default-normalizer-P-u2VRBf.d.mts} +5 -5
- package/dist/default-normalizer-P-u2VRBf.d.mts.map +1 -0
- package/dist/{descriptor-meta-axWY-kHl-Bt2_NjH4.mjs → descriptor-meta-Bzs7kSyA-BjbnpZLW.mjs} +8 -8
- package/dist/{descriptor-meta-axWY-kHl-Bt2_NjH4.mjs.map → descriptor-meta-Bzs7kSyA-BjbnpZLW.mjs.map} +1 -1
- package/dist/{descriptor-meta-CvJvXGfx-CGIgsveo.mjs → descriptor-meta-DDh7-s6c-D6qC3SDx.mjs} +4 -4
- package/dist/{descriptor-meta-CvJvXGfx-CGIgsveo.mjs.map → descriptor-meta-DDh7-s6c-D6qC3SDx.mjs.map} +1 -1
- package/dist/{descriptor-meta-runtime-CMaPJG46-CPYTMJ7t.mjs → descriptor-meta-runtime-C1AjrKaP-CYer0qt7.mjs} +3 -3
- package/dist/{descriptor-meta-runtime-CMaPJG46-CPYTMJ7t.mjs.map → descriptor-meta-runtime-C1AjrKaP-CYer0qt7.mjs.map} +1 -1
- package/dist/{diff-database-schema-DLIpM5BX-DlEJquxk.mjs → diff-database-schema-DyCIRT80-C1zMCmRx.mjs} +7 -7
- package/dist/{diff-database-schema-DLIpM5BX-DlEJquxk.mjs.map → diff-database-schema-DyCIRT80-C1zMCmRx.mjs.map} +1 -1
- package/dist/{full-text-search-document-DbegbX0J-jrbc8kfp.mjs → full-text-search-document-Doy5TF7c-DezgYsP-.mjs} +3 -3
- package/dist/{full-text-search-document-DbegbX0J-jrbc8kfp.mjs.map → full-text-search-document-Doy5TF7c-DezgYsP-.mjs.map} +1 -1
- package/dist/{indexes-ca4Dxsym-By_PZuYD.d.mts → indexes-DtIXFHAb-DBubdl32.d.mts} +3 -2
- package/dist/indexes-DtIXFHAb-DBubdl32.d.mts.map +1 -0
- package/dist/{issue-planner-B3E9yChD.d.mts → issue-planner-DrWlNiAf.d.mts} +5 -6
- package/dist/issue-planner-DrWlNiAf.d.mts.map +1 -0
- package/dist/migration-CbOh59ZJ.mjs.map +1 -1
- package/dist/{migration-cGzKlTv0.d.mts → migration-DO23kNde.d.mts} +3 -3
- package/dist/{migration-cGzKlTv0.d.mts.map → migration-DO23kNde.d.mts.map} +1 -1
- package/dist/native-type-normalizer-DFE5L3YY.d.mts +30 -0
- package/dist/native-type-normalizer-DFE5L3YY.d.mts.map +1 -0
- package/dist/native-type-normalizer-a1XJSlk6.mjs +24 -0
- package/dist/native-type-normalizer-a1XJSlk6.mjs.map +1 -0
- package/dist/op-factory-call-CijzNDaJ.d.mts +1 -0
- package/dist/{op-factory-call-B-EoYQIO-BIfzqVX6.mjs → op-factory-call-No9Z2tdw-Lap8xvVy.mjs} +35 -27
- package/dist/op-factory-call-No9Z2tdw-Lap8xvVy.mjs.map +1 -0
- package/dist/{op-factory-call-z5TKsamx-DDfPa57U.d.mts → op-factory-call-kdPO0kgG-DV8hS6qA.d.mts} +10 -9
- package/dist/op-factory-call-kdPO0kgG-DV8hS6qA.d.mts.map +1 -0
- package/dist/{planner-BBGH1cAB.d.mts → planner-B_MRApHM.d.mts} +3 -3
- package/dist/{planner-BBGH1cAB.d.mts.map → planner-B_MRApHM.d.mts.map} +1 -1
- package/dist/{planner-BNoWx3rb-rkajA65G.mjs → planner-C1czBCmI-C-x1Ip-_.mjs} +10 -10
- package/dist/{planner-BNoWx3rb-rkajA65G.mjs.map → planner-C1czBCmI-C-x1Ip-_.mjs.map} +1 -1
- package/dist/{planner-ddl-builders-Bo_8ozOV-AMIs8Og7.mjs → planner-ddl-builders-B8PhQZ2T-D1KBJxcS.mjs} +3 -3
- package/dist/{planner-ddl-builders-Bo_8ozOV-AMIs8Og7.mjs.map → planner-ddl-builders-B8PhQZ2T-D1KBJxcS.mjs.map} +1 -1
- package/dist/{planner-ddl-builders-Byw5BICu.d.mts → planner-ddl-builders-DbG9_uAk.d.mts} +3 -3
- package/dist/{planner-ddl-builders-Byw5BICu.d.mts.map → planner-ddl-builders-DbG9_uAk.d.mts.map} +1 -1
- package/dist/{planner-identity-values-Dr5FgyF1.d.mts → planner-identity-values-B-NAiN7I.d.mts} +3 -3
- package/dist/planner-identity-values-B-NAiN7I.d.mts.map +1 -0
- package/dist/{planner-identity-values--pbIuAZR-lgKcM-Zu.mjs → planner-identity-values-BnxSwhlS-CzyBeK0a.mjs} +3 -3
- package/dist/{planner-identity-values--pbIuAZR-lgKcM-Zu.mjs.map → planner-identity-values-BnxSwhlS-CzyBeK0a.mjs.map} +1 -1
- package/dist/{planner-produced-postgres-migration-sxhIP3Te-Cn3sD9zE.d.mts → planner-produced-postgres-migration-B6NsNaam-BmvloI2L.d.mts} +3 -3
- package/dist/planner-produced-postgres-migration-B6NsNaam-BmvloI2L.d.mts.map +1 -0
- package/dist/planner-produced-postgres-migration-BW8GJFjS.d.mts +1 -0
- package/dist/{planner-produced-postgres-migration-BIKLMKpf-B5h4hpvf.mjs → planner-produced-postgres-migration-F9joIngl-C04yYu-i.mjs} +4 -4
- package/dist/{planner-produced-postgres-migration-BIKLMKpf-B5h4hpvf.mjs.map → planner-produced-postgres-migration-F9joIngl-C04yYu-i.mjs.map} +1 -1
- package/dist/planner-sql-checks-CB4oLSuZ.d.mts +1 -0
- package/dist/planner-sql-checks-CxlrM4J2-VqQpmMwn.d.mts +37 -0
- package/dist/planner-sql-checks-CxlrM4J2-VqQpmMwn.d.mts.map +1 -0
- package/dist/planner-sql-checks-pkURMYMz-2QAIKyW-.mjs +139 -0
- package/dist/planner-sql-checks-pkURMYMz-2QAIKyW-.mjs.map +1 -0
- package/dist/{postgres-codec-traits-Da2UyO_9-BsGjYJHf.mjs → postgres-codec-traits-D3muwxMS-OwnBG0Mz.mjs} +3 -3
- package/dist/{postgres-codec-traits-Da2UyO_9-BsGjYJHf.mjs.map → postgres-codec-traits-D3muwxMS-OwnBG0Mz.mjs.map} +1 -1
- package/dist/{postgres-contract-view-csjnSNLt-M2QaYBn0.mjs → postgres-contract-view-B-bLZB7o-zpuamDXT.mjs} +7 -7
- package/dist/{postgres-contract-view-csjnSNLt-M2QaYBn0.mjs.map → postgres-contract-view-B-bLZB7o-zpuamDXT.mjs.map} +1 -1
- package/dist/{postgres-migration-BGkcs09r-BmUXCs80.mjs → postgres-migration-BbXm1l5I-DDy8IgYB.mjs} +15 -32
- package/dist/postgres-migration-BbXm1l5I-DDy8IgYB.mjs.map +1 -0
- package/dist/{postgres-migration-D6_R3__I-rFg_i2gz.d.mts → postgres-migration-CRLV93uK-ThJW3tFf.d.mts} +3 -3
- package/dist/{postgres-migration-D6_R3__I-rFg_i2gz.d.mts.map → postgres-migration-CRLV93uK-ThJW3tFf.d.mts.map} +1 -1
- package/dist/{postgres-schema-BtW3Sw0F-CH3NqoOo.mjs → postgres-schema-DyUXtYIT-vb-RxpRN.mjs} +3 -3
- package/dist/{postgres-schema-BtW3Sw0F-CH3NqoOo.mjs.map → postgres-schema-DyUXtYIT-vb-RxpRN.mjs.map} +1 -1
- package/dist/{prisma7-binding-XSuxkjqy.d.mts → prisma7-binding-C5RLV6kJ.d.mts} +12 -121
- package/dist/prisma7-binding-C5RLV6kJ.d.mts.map +1 -0
- package/dist/{prisma7-binding-ZUOUC530.mjs → prisma7-binding-CzO7rkpS.mjs} +80 -141
- package/dist/prisma7-binding-CzO7rkpS.mjs.map +1 -0
- package/dist/{render-ops-WhXRiDGu-LZMJf0aV.mjs → render-ops-MeXLgeOa-nL4PdJzz.mjs} +3 -3
- package/dist/{render-ops-WhXRiDGu-LZMJf0aV.mjs.map → render-ops-MeXLgeOa-nL4PdJzz.mjs.map} +1 -1
- package/dist/{resolve-ddl-schema-B8cX92k0-DzN6Alxy.mjs → resolve-ddl-schema-IdPEiyLX-BZGpy8Wz.mjs} +3 -3
- package/dist/{resolve-ddl-schema-B8cX92k0-DzN6Alxy.mjs.map → resolve-ddl-schema-IdPEiyLX-BZGpy8Wz.mjs.map} +1 -1
- package/dist/{sql-renderer-CD5aYQos-DZotmt9U.mjs → sql-renderer-CD5aYQos-1hGCWT0S.mjs} +3 -3
- package/dist/{sql-renderer-CD5aYQos-DZotmt9U.mjs.map → sql-renderer-CD5aYQos-1hGCWT0S.mjs.map} +1 -1
- package/dist/{sql-utils-DxE_vJt4-Dkjw9U45.mjs → sql-utils-Bnw3JbWf-zvWDkyrr.mjs} +3 -178
- package/dist/sql-utils-Bnw3JbWf-zvWDkyrr.mjs.map +1 -0
- package/dist/target.d.mts +17 -16
- package/dist/target.mjs +29 -29
- package/dist/target__codecs.mjs +2 -2
- package/dist/target__contract-free.mjs +3 -3
- package/dist/target__control.mjs +2558 -3
- package/dist/target__control.mjs.map +1 -0
- package/dist/target__data-types.d.mts +2 -2
- package/dist/target__data-types.mjs +3 -3
- package/dist/target__default-normalizer.d.mts +1 -1
- package/dist/target__default-normalizer.mjs +1 -1
- package/dist/target__diff-database-schema.mjs +1 -1
- package/dist/target__full-text-index-authoring.mjs +1 -1
- package/dist/target__issue-planner.d.mts +1 -1
- package/dist/target__issue-planner.mjs +1 -1
- package/dist/target__migration.d.mts +2 -2
- package/dist/target__migration.mjs +2 -2
- package/dist/target__native-type-normalizer.d.mts +2 -2
- package/dist/target__native-type-normalizer.mjs +2 -2
- package/dist/target__op-factory-call.d.mts +2 -2
- package/dist/target__op-factory-call.mjs +1 -1
- package/dist/target__pack.mjs +1 -1
- package/dist/target__planner-ddl-builders.d.mts +1 -1
- package/dist/target__planner-ddl-builders.mjs +1 -1
- package/dist/target__planner-identity-values.d.mts +1 -1
- package/dist/target__planner-identity-values.mjs +1 -1
- package/dist/target__planner-produced-postgres-migration.d.mts +2 -2
- package/dist/target__planner-produced-postgres-migration.mjs +1 -1
- package/dist/target__planner-sql-checks.d.mts +3 -2
- package/dist/target__planner-sql-checks.mjs +2 -2
- package/dist/target__planner.d.mts +1 -1
- package/dist/target__planner.mjs +2 -2
- package/dist/target__prisma7-binding.d.mts +1 -1
- package/dist/target__prisma7-binding.mjs +1 -1
- package/dist/target__render-ops.mjs +1 -1
- package/dist/target__runtime.mjs +5 -5
- package/dist/target__runtime.mjs.map +1 -1
- package/dist/target__schema-ir-annotations.mjs +1 -1
- package/dist/target__sql-utils.mjs +2 -2
- package/dist/target__types.mjs +2 -2
- package/dist/{infer-psl-contract-CKP3nwjB-x1_ji7Z9.mjs → type-constructors-CrNUrtwZ-dmWF-mtV.mjs} +385 -15
- package/dist/type-constructors-CrNUrtwZ-dmWF-mtV.mjs.map +1 -0
- package/package.json +9 -9
- package/dist/adapter-CA0jY1EK.d.mts.map +0 -1
- package/dist/adapter-UEtFYllx-DXa1Ekth.mjs.map +0 -1
- package/dist/contract-contributions-DrHk5h_E-BbmViVsC.mjs.map +0 -1
- package/dist/control-CwTFk4YS.mjs +0 -2929
- package/dist/control-CwTFk4YS.mjs.map +0 -1
- package/dist/control-l0spLFiu.d.mts.map +0 -1
- package/dist/control-policy-BdfDPcjX-BueP9PBT.mjs.map +0 -1
- package/dist/data-types-BkFfMhgz.d.mts.map +0 -1
- package/dist/default-normalizer-BqFHmlox-CP8ywN-r.mjs.map +0 -1
- package/dist/default-normalizer-CTAiFe9Y.d.mts.map +0 -1
- package/dist/indexes-ca4Dxsym-By_PZuYD.d.mts.map +0 -1
- package/dist/infer-psl-contract-CKP3nwjB-x1_ji7Z9.mjs.map +0 -1
- package/dist/issue-planner-B3E9yChD.d.mts.map +0 -1
- package/dist/native-type-normalizer-BFo5tSyh.d.mts +0 -37
- package/dist/native-type-normalizer-BFo5tSyh.d.mts.map +0 -1
- package/dist/native-type-normalizer-CwyVR7xB.mjs +0 -96
- package/dist/native-type-normalizer-CwyVR7xB.mjs.map +0 -1
- package/dist/op-factory-call-B-EoYQIO-BIfzqVX6.mjs.map +0 -1
- package/dist/op-factory-call-uVDKZqw1.d.mts +0 -1
- package/dist/op-factory-call-z5TKsamx-DDfPa57U.d.mts.map +0 -1
- package/dist/planner-identity-values-Dr5FgyF1.d.mts.map +0 -1
- package/dist/planner-produced-postgres-migration-D-ZcNy7h.d.mts +0 -1
- package/dist/planner-produced-postgres-migration-sxhIP3Te-Cn3sD9zE.d.mts.map +0 -1
- package/dist/planner-sql-checks-C54jJ5qt.d.mts +0 -39
- package/dist/planner-sql-checks-C54jJ5qt.d.mts.map +0 -1
- package/dist/planner-sql-checks-pAQfWJz_-CosbjrRp.mjs +0 -132
- package/dist/planner-sql-checks-pAQfWJz_-CosbjrRp.mjs.map +0 -1
- package/dist/postgres-migration-BGkcs09r-BmUXCs80.mjs.map +0 -1
- package/dist/prisma7-binding-XSuxkjqy.d.mts.map +0 -1
- package/dist/prisma7-binding-ZUOUC530.mjs.map +0 -1
- package/dist/sql-utils-DxE_vJt4-Dkjw9U45.mjs.map +0 -1
package/dist/target__control.mjs
CHANGED
|
@@ -1,4 +1,2559 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { c as
|
|
3
|
-
import { i as
|
|
1
|
+
import { S as PG_TEXT_CODEC_ID, s as PG_ENUM_CODEC_ID } from "./codec-ids-Cb0yO-IS--e0P2rfI.mjs";
|
|
2
|
+
import { c as postgresError } from "./errors-BrhQYgdL-D_lIrddD.mjs";
|
|
3
|
+
import { i as quoteIdentifier } from "./sql-utils-Bnw3JbWf-zvWDkyrr.mjs";
|
|
4
|
+
import { t as DEFAULT_NAMESPACE_ID } from "./namespace-ids-xtp_ZY86-Cpp8PTxD.mjs";
|
|
5
|
+
import { t as PostgresNativeEnum } from "./postgres-native-enum-CdP3b_-R-Cgz9KEKx.mjs";
|
|
6
|
+
import { P as setFallbackTemporal, i as decodePostgresListText, o as parsePostgresListText } from "./codecs-UZ1NEbvk-CMnI6Ti0.mjs";
|
|
7
|
+
import { s as fullTextIndexDefinitionOf } from "./full-text-index-definition-BPxQQBuC-BrpDsuJu.mjs";
|
|
8
|
+
import { i as PostgresRlsPolicy, n as PostgresRlsEnablement, o as PostgresRole } from "./postgres-schema-DyUXtYIT-vb-RxpRN.mjs";
|
|
9
|
+
import { r as computeContentHash } from "./canonicalize-RdxoUHao-DK_M6HU-.mjs";
|
|
10
|
+
import { c as postgresNowGeneratorControlDescriptors, t as POLICY_BLOCK_KEYWORDS } from "./authoring-DhyLHFHA-pB4NuFxh.mjs";
|
|
11
|
+
import { t as postgresRenderCheckExpressions } from "./check-expressions-7uCCP01t-WtUqfqkP.mjs";
|
|
12
|
+
import { t as postgresTargetDescriptorMeta } from "./descriptor-meta-Bzs7kSyA-BjbnpZLW.mjs";
|
|
13
|
+
import { a as postgresDiffSubjectGranularity, i as postgresDiffSubjectEntityKind } from "./postgres-table-schema-node-BBkitBQh-DT1T5VWU.mjs";
|
|
14
|
+
import { t as PostgresDatabaseSchemaNode } from "./postgres-role-schema-node-B8Z5i5D--PObwlU2Z.mjs";
|
|
15
|
+
import { i as qualifyTableName } from "./planner-sql-checks-pkURMYMz-2QAIKyW-.mjs";
|
|
16
|
+
import { r as diffPostgresSchema } from "./diff-database-schema-DyCIRT80-C1zMCmRx.mjs";
|
|
17
|
+
import { t as PostgresContractSerializer } from "./postgres-contract-view-B-bLZB7o-zpuamDXT.mjs";
|
|
18
|
+
import { o as postgresContractToSchema } from "./postgres-migration-BbXm1l5I-DDy8IgYB.mjs";
|
|
19
|
+
import { t as createPostgresMigrationPlanner } from "./planner-C1czBCmI-C-x1Ip-_.mjs";
|
|
20
|
+
import { n as MARKER_LOCK_SQL, t as MARKER_LOCK_KEY } from "./marker-lock-DFc1Tfv5-QMJSzMIa.mjs";
|
|
21
|
+
import { _ as postgresNativeAuthoringTypes, a as buildIndexAttribute, c as buildNativeEnumBlock, d as inferPostgresPslContract, f as namedArg, g as positionalArg, h as parseDefaultAttributeString, i as buildFullTextIndexAttribute, n as buildAttribute, o as buildMapAttribute, r as buildCheckAttribute, s as buildModelConstraintAttribute, t as SYNTHETIC_SPAN, v as postgresPslTypeConstructors, y as postgresScalarAuthoringTypes } from "./type-constructors-CrNUrtwZ-dmWF-mtV.mjs";
|
|
22
|
+
import { dataTypeParams, requiredParamKeys, validateCodecTypeParams } from "@prisma/orm-framework/components/codec";
|
|
23
|
+
import { blindCast } from "@prisma/orm-framework/utils/casts";
|
|
24
|
+
import { isSqlDataType, unquotedSqlBaseName } from "@prisma/orm-family-sql/contract/data-type";
|
|
25
|
+
import { escapePslString } from "@prisma/orm-family-sql/contract/data-type-support";
|
|
26
|
+
import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
|
|
27
|
+
import { StorageColumn, resolvedTypeParams } from "@prisma/orm-family-sql/contract/types";
|
|
28
|
+
import { APP_SPACE_ID } from "@prisma/orm-framework/components/control";
|
|
29
|
+
import { assertDefined, invariant } from "@prisma/orm-framework/utils/assertions";
|
|
30
|
+
import { composeCheckWirePrefix, computeCheckContentHash, computeIndexContentHash, formatWireName, parseNaming } from "@prisma/orm-family-sql/schema-ir/naming";
|
|
31
|
+
import { ifDefined } from "@prisma/orm-framework/utils/defined";
|
|
32
|
+
import { convertedColumnOf, requiredColumnOf, requiredColumnsOfMigration, rowsWithoutValueFailure, runnerFailure, runnerSuccess, unconvertedFieldOf } from "@prisma/orm-family-sql/family/control";
|
|
33
|
+
import { authoringTypeConstructorArguments, findAuthoringTypeConstructorCall } from "@prisma/orm-framework/components/authoring";
|
|
34
|
+
import { NAME_THE_PSL_SOURCE_LOSES, isPslIdentifier } from "@prisma/orm-framework/psl-parser";
|
|
35
|
+
import { printSqlExpressionLiteral, sqlTextsReadBack } from "@prisma/orm-family-sql/contract/sql-expression";
|
|
36
|
+
import { InternalError } from "@prisma/orm-framework/utils/internal-error";
|
|
37
|
+
import { notOk, ok, okVoid } from "@prisma/orm-framework/utils/result";
|
|
38
|
+
import { SqlSchemaVerifierBase } from "@prisma/orm-family-sql/family/ir";
|
|
39
|
+
import { defaultFunctionCallFor, fieldPresetCallFor, inferredTypeConstructors, mapDefault, pslTypeArgumentText } from "@prisma/orm-family-sql/family/psl-build";
|
|
40
|
+
import { UNBOUND_PSL_NAMESPACE_NAME, UNSPECIFIED_PSL_NAMESPACE_ID, makePslNamespace, makePslNamespaceEntries } from "@prisma/orm-framework/components/psl-ast";
|
|
41
|
+
import { effectiveControlPolicy } from "@prisma/orm-framework/contract/types";
|
|
42
|
+
import { Temporal } from "temporal-polyfill/full/implementation";
|
|
43
|
+
import { SqlQueryError } from "@prisma/orm-family-sql/errors";
|
|
44
|
+
import { canonicalizeJson } from "@prisma/orm-framework/components/utils";
|
|
45
|
+
import { pslFieldMapName, pslModelMapName } from "@prisma/orm-family-sql/contract-psl/map-names";
|
|
46
|
+
import { defaultForeignKeyIndex } from "@prisma/orm-family-sql/contract/foreign-key-materialization";
|
|
47
|
+
//#region ../../../3-targets/3-targets/postgres/dist/control.mjs
|
|
48
|
+
/**
|
|
49
|
+
* Deep clones and freezes a record object to prevent mutation.
|
|
50
|
+
* Recursively clones nested objects and arrays to ensure complete isolation.
|
|
51
|
+
*/
|
|
52
|
+
function cloneAndFreezeRecord(value) {
|
|
53
|
+
const cloned = {};
|
|
54
|
+
for (const [key, val] of Object.entries(value)) if (val === null || val === void 0) cloned[key] = val;
|
|
55
|
+
else if (Array.isArray(val)) cloned[key] = Object.freeze([...val]);
|
|
56
|
+
else if (typeof val === "object") cloned[key] = cloneAndFreezeRecord(blindCast(val));
|
|
57
|
+
else cloned[key] = val;
|
|
58
|
+
return blindCast(Object.freeze(cloned));
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* SQLSTATE classes of failures that come from the connection or the server, not from the SQL a step
|
|
62
|
+
* runs: connection exceptions, transaction rollbacks, resources, operator intervention, system and
|
|
63
|
+
* internal errors.
|
|
64
|
+
*/
|
|
65
|
+
const NOT_THE_STEPS_SQL = [
|
|
66
|
+
"08",
|
|
67
|
+
"40",
|
|
68
|
+
"53",
|
|
69
|
+
"57",
|
|
70
|
+
"58",
|
|
71
|
+
"XX"
|
|
72
|
+
];
|
|
73
|
+
/**
|
|
74
|
+
* The type change a failed step carries out. For the database's cast, a data exception (class 22)
|
|
75
|
+
* is a value it could not convert, and 42846 (`cannot_coerce`) a pair of types with no cast. For
|
|
76
|
+
* the migration's own conversion, every error of the step's SQL is the conversion's: a data
|
|
77
|
+
* exception is a value, an integrity violation (class 23) a value the new type cannot hold, and
|
|
78
|
+
* anything else an error in its expression.
|
|
79
|
+
*/
|
|
80
|
+
function failedTypeChangeOf(step, sqlState, plan) {
|
|
81
|
+
const converted = convertedColumnOf(step);
|
|
82
|
+
const field = unconvertedFieldOf(step, plan.contract);
|
|
83
|
+
if (converted === void 0 || field === void 0 || sqlState === void 0) return void 0;
|
|
84
|
+
const { operationIndex } = plan;
|
|
85
|
+
if (converted.by === "conversion") {
|
|
86
|
+
if (NOT_THE_STEPS_SQL.some((sqlClass) => sqlState.startsWith(sqlClass))) return void 0;
|
|
87
|
+
return {
|
|
88
|
+
field,
|
|
89
|
+
by: "conversion",
|
|
90
|
+
reason: sqlState.startsWith("22") ? "value" : sqlState.startsWith("23") ? "invalidResult" : "expressionError",
|
|
91
|
+
operationIndex
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
const reason = sqlState === "42846" ? "noCast" : sqlState.startsWith("22") ? "value" : void 0;
|
|
95
|
+
return reason === void 0 ? void 0 : {
|
|
96
|
+
field,
|
|
97
|
+
by: "cast",
|
|
98
|
+
reason,
|
|
99
|
+
operationIndex
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function createPostgresMigrationRunner(family) {
|
|
103
|
+
return new PostgresMigrationRunner(family);
|
|
104
|
+
}
|
|
105
|
+
var PostgresMigrationRunner = class {
|
|
106
|
+
family;
|
|
107
|
+
constructor(family) {
|
|
108
|
+
this.family = family;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Body of the migration runner without transaction management. The
|
|
112
|
+
* caller ({@link PostgresMigrationRunner.execute}) owns the
|
|
113
|
+
* `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.
|
|
114
|
+
*/
|
|
115
|
+
async executeOnConnection(options) {
|
|
116
|
+
const driver = options.driver;
|
|
117
|
+
if (options.space !== void 0 && options.space !== options.plan.spaceId) throw postgresError("MIGRATION.CONTRACT_SPACE_VIOLATION", `SqlMigrationRunner: options.space (${options.space}) does not match plan.spaceId (${options.plan.spaceId})`, { meta: {
|
|
118
|
+
space: options.space,
|
|
119
|
+
planSpaceId: options.plan.spaceId
|
|
120
|
+
} });
|
|
121
|
+
const space = options.plan.spaceId;
|
|
122
|
+
const planOps = blindCast(await Promise.all(options.plan.operations));
|
|
123
|
+
const destinationCheck = this.ensurePlanMatchesDestinationContract(options.plan.destination, options.destinationContract);
|
|
124
|
+
if (!destinationCheck.ok) return destinationCheck;
|
|
125
|
+
const policyCheck = this.enforcePolicyCompatibility(options.policy, planOps);
|
|
126
|
+
if (!policyCheck.ok) return policyCheck;
|
|
127
|
+
await this.acquireLock(driver);
|
|
128
|
+
const ensureResult = await this.ensureControlTables(driver, options.destinationContract);
|
|
129
|
+
if (!ensureResult.ok) return ensureResult;
|
|
130
|
+
const existingMarker = await this.family.readMarker({
|
|
131
|
+
driver,
|
|
132
|
+
space
|
|
133
|
+
});
|
|
134
|
+
const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);
|
|
135
|
+
if (!markerCheck.ok) return markerCheck;
|
|
136
|
+
const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);
|
|
137
|
+
const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;
|
|
138
|
+
const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;
|
|
139
|
+
let applyValue;
|
|
140
|
+
if (skipOperations) applyValue = {
|
|
141
|
+
operationsExecuted: 0,
|
|
142
|
+
executedOperations: []
|
|
143
|
+
};
|
|
144
|
+
else {
|
|
145
|
+
const applyResult = await this.applyPlan(driver, options, planOps);
|
|
146
|
+
if (!applyResult.ok) return applyResult;
|
|
147
|
+
applyValue = applyResult.value;
|
|
148
|
+
}
|
|
149
|
+
if (space === APP_SPACE_ID) {
|
|
150
|
+
const schemaNode = await this.family.introspect({
|
|
151
|
+
driver,
|
|
152
|
+
contract: options.destinationContract
|
|
153
|
+
});
|
|
154
|
+
const schemaVerifyResult = this.family.verifySchema({
|
|
155
|
+
contract: options.destinationContract,
|
|
156
|
+
schema: schemaNode,
|
|
157
|
+
strict: options.strictVerification ?? true,
|
|
158
|
+
frameworkComponents: options.frameworkComponents
|
|
159
|
+
});
|
|
160
|
+
if (!schemaVerifyResult.ok) return runnerFailure("MIGRATION.SCHEMA_VERIFY_FAILED", schemaVerifyResult.summary, {
|
|
161
|
+
why: "The resulting database schema does not satisfy the destination contract.",
|
|
162
|
+
meta: { issues: schemaVerifyResult.schema.issues },
|
|
163
|
+
schemaIssues: schemaVerifyResult.schema.issues
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
const incomingInvariants = options.plan.providedInvariants ?? [];
|
|
167
|
+
const existingInvariants = new Set(existingMarker?.invariants ?? []);
|
|
168
|
+
const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));
|
|
169
|
+
if (!(isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting)) {
|
|
170
|
+
const markerResult = await this.upsertMarker(driver, options, existingMarker, space);
|
|
171
|
+
if (!markerResult.ok) return markerResult;
|
|
172
|
+
await this.recordLedgerEntries(driver, options, applyValue.executedOperations, planOps.length);
|
|
173
|
+
}
|
|
174
|
+
return runnerSuccess({
|
|
175
|
+
operationsPlanned: planOps.length,
|
|
176
|
+
operationsExecuted: applyValue.operationsExecuted
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
async execute(options) {
|
|
180
|
+
const driver = options.driver;
|
|
181
|
+
const perSpaceOptions = options.perSpaceOptions;
|
|
182
|
+
if (perSpaceOptions.length === 0) return ok({ perSpaceResults: [] });
|
|
183
|
+
await this.beginTransaction(driver);
|
|
184
|
+
let committed = false;
|
|
185
|
+
try {
|
|
186
|
+
const perSpaceResults = [];
|
|
187
|
+
for (const spaceOptions of perSpaceOptions) {
|
|
188
|
+
const space = spaceOptions.space ?? spaceOptions.plan.spaceId;
|
|
189
|
+
const result = await this.executeOnConnection({
|
|
190
|
+
...spaceOptions,
|
|
191
|
+
driver,
|
|
192
|
+
space
|
|
193
|
+
});
|
|
194
|
+
if (!result.ok) return notOk({
|
|
195
|
+
...result.failure,
|
|
196
|
+
failingSpace: space
|
|
197
|
+
});
|
|
198
|
+
perSpaceResults.push({
|
|
199
|
+
space,
|
|
200
|
+
value: result.value
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
await this.commitTransaction(driver);
|
|
204
|
+
committed = true;
|
|
205
|
+
return ok({ perSpaceResults });
|
|
206
|
+
} finally {
|
|
207
|
+
if (!committed) await this.rollbackTransaction(driver);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
async applyPlan(driver, options, ops) {
|
|
211
|
+
const checks = options.executionChecks;
|
|
212
|
+
const runPrechecks = checks?.prechecks !== false;
|
|
213
|
+
const runPostchecks = checks?.postchecks !== false;
|
|
214
|
+
const runIdempotency = checks?.idempotencyChecks !== false;
|
|
215
|
+
let operationsExecuted = 0;
|
|
216
|
+
const executedOperations = [];
|
|
217
|
+
for (const operation of ops) {
|
|
218
|
+
options.callbacks?.onOperationStart?.(operation);
|
|
219
|
+
try {
|
|
220
|
+
if (runPostchecks && runIdempotency) {
|
|
221
|
+
if (await this.expectationsAreSatisfied(driver, operation.postcheck)) {
|
|
222
|
+
executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const position = {
|
|
227
|
+
contract: options.destinationContract,
|
|
228
|
+
operationIndex: ops.indexOf(operation),
|
|
229
|
+
operations: ops,
|
|
230
|
+
edges: options.migrationEdges
|
|
231
|
+
};
|
|
232
|
+
if (runPrechecks) {
|
|
233
|
+
const precheckResult = await this.runExpectationSteps(driver, operation.precheck, operation, "precheck", position);
|
|
234
|
+
if (!precheckResult.ok) return precheckResult;
|
|
235
|
+
}
|
|
236
|
+
const executeResult = await this.runExecuteSteps(driver, operation, position);
|
|
237
|
+
if (!executeResult.ok) return executeResult;
|
|
238
|
+
if (runPostchecks) {
|
|
239
|
+
const postcheckResult = await this.runExpectationSteps(driver, operation.postcheck, operation, "postcheck", position);
|
|
240
|
+
if (!postcheckResult.ok) return postcheckResult;
|
|
241
|
+
}
|
|
242
|
+
executedOperations.push(operation);
|
|
243
|
+
operationsExecuted += 1;
|
|
244
|
+
} finally {
|
|
245
|
+
options.callbacks?.onOperationComplete?.(operation);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return ok({
|
|
249
|
+
operationsExecuted,
|
|
250
|
+
executedOperations
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
async ensureControlTables(driver, contract) {
|
|
254
|
+
const lowererContext = { contract };
|
|
255
|
+
const [schemaQuery, ...tableQueries] = this.family.bootstrapControlTableQueries();
|
|
256
|
+
if (schemaQuery === void 0) throw new InternalError("Postgres control-table bootstrap must include CREATE SCHEMA");
|
|
257
|
+
await this.executeStatement(driver, await this.family.lowerAst(schemaQuery, lowererContext));
|
|
258
|
+
for (const query of tableQueries) await this.executeStatement(driver, await this.family.lowerAst(query, lowererContext));
|
|
259
|
+
return okVoid();
|
|
260
|
+
}
|
|
261
|
+
async runExpectationSteps(driver, steps, operation, phase, plan) {
|
|
262
|
+
for (const step of steps) {
|
|
263
|
+
const result = await driver.query(step.sql, step.params ?? []);
|
|
264
|
+
if (!this.stepResultIsTrue(result.rows)) {
|
|
265
|
+
const code = phase === "precheck" ? "MIGRATION.PRECHECK_FAILED" : "MIGRATION.POSTCHECK_FAILED";
|
|
266
|
+
const failed = `Operation ${operation.id} failed during ${phase}: ${step.description}`;
|
|
267
|
+
const required = requiredColumnOf(step);
|
|
268
|
+
const rowsWithoutValue = required === void 0 ? void 0 : await this.rowsWithoutValue(driver, operation, required, plan);
|
|
269
|
+
return runnerFailure(code, rowsWithoutValue?.summary ?? failed, {
|
|
270
|
+
...ifDefined("why", rowsWithoutValue === void 0 ? void 0 : failed),
|
|
271
|
+
meta: {
|
|
272
|
+
operationId: operation.id,
|
|
273
|
+
phase,
|
|
274
|
+
stepDescription: step.description
|
|
275
|
+
},
|
|
276
|
+
failedCheck: {
|
|
277
|
+
operationId: operation.id,
|
|
278
|
+
phase,
|
|
279
|
+
description: step.description
|
|
280
|
+
},
|
|
281
|
+
rowsWithoutValue: rowsWithoutValue?.reports
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return okVoid();
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Counts the rows the failed step's column has no value in, then those of every other column the
|
|
289
|
+
* failed operation's migration makes required.
|
|
290
|
+
*/
|
|
291
|
+
rowsWithoutValue(driver, operation, required, plan) {
|
|
292
|
+
return rowsWithoutValueFailure({
|
|
293
|
+
failed: [{
|
|
294
|
+
operation,
|
|
295
|
+
operationIndex: plan.operationIndex,
|
|
296
|
+
required
|
|
297
|
+
}],
|
|
298
|
+
others: requiredColumnsOfMigration(plan.operations, plan.edges, plan.operationIndex),
|
|
299
|
+
count: async ({ operation: marked, required: column }) => {
|
|
300
|
+
const schema = marked.target.details?.schema;
|
|
301
|
+
if (schema === void 0) return 0;
|
|
302
|
+
const where = column.reason !== "newField" ? ` WHERE ${quoteIdentifier(column.column)} IS NULL` : "";
|
|
303
|
+
return (await driver.query(`SELECT COUNT(*)::int AS rows FROM ${qualifyTableName(schema, column.table)}${where}`)).rows[0]?.rows ?? 0;
|
|
304
|
+
},
|
|
305
|
+
contract: plan.contract
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
async runExecuteSteps(driver, operation, plan) {
|
|
309
|
+
for (const step of operation.execute) try {
|
|
310
|
+
await driver.query(step.sql, step.params ?? []);
|
|
311
|
+
} catch (error) {
|
|
312
|
+
if (SqlQueryError.is(error)) return runnerFailure("MIGRATION.EXECUTION_FAILED", `Operation ${operation.id} failed during execution: ${step.description}`, {
|
|
313
|
+
why: error.message,
|
|
314
|
+
failedTypeChange: failedTypeChangeOf(step, error.sqlState, plan),
|
|
315
|
+
meta: {
|
|
316
|
+
operationId: operation.id,
|
|
317
|
+
stepDescription: step.description,
|
|
318
|
+
sql: step.sql,
|
|
319
|
+
sqlState: error.sqlState,
|
|
320
|
+
constraint: error.constraint,
|
|
321
|
+
table: error.table,
|
|
322
|
+
column: error.column,
|
|
323
|
+
detail: error.detail
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
328
|
+
return okVoid();
|
|
329
|
+
}
|
|
330
|
+
stepResultIsTrue(rows) {
|
|
331
|
+
if (!rows || rows.length === 0) return false;
|
|
332
|
+
const firstRow = rows[0];
|
|
333
|
+
const firstValue = firstRow ? Object.values(firstRow)[0] : void 0;
|
|
334
|
+
if (typeof firstValue === "boolean") return firstValue;
|
|
335
|
+
if (typeof firstValue === "number") return firstValue !== 0;
|
|
336
|
+
if (typeof firstValue === "string") {
|
|
337
|
+
const lower = firstValue.toLowerCase();
|
|
338
|
+
if (lower === "t" || lower === "true" || lower === "1") return true;
|
|
339
|
+
if (lower === "f" || lower === "false" || lower === "0") return false;
|
|
340
|
+
return firstValue.length > 0;
|
|
341
|
+
}
|
|
342
|
+
return Boolean(firstValue);
|
|
343
|
+
}
|
|
344
|
+
async expectationsAreSatisfied(driver, steps) {
|
|
345
|
+
if (steps.length === 0) return false;
|
|
346
|
+
for (const step of steps) {
|
|
347
|
+
const result = await driver.query(step.sql, step.params ?? []);
|
|
348
|
+
if (!this.stepResultIsTrue(result.rows)) return false;
|
|
349
|
+
}
|
|
350
|
+
return true;
|
|
351
|
+
}
|
|
352
|
+
createPostcheckPreSatisfiedSkipRecord(operation) {
|
|
353
|
+
const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : void 0;
|
|
354
|
+
const runnerMeta = Object.freeze({
|
|
355
|
+
skipped: true,
|
|
356
|
+
reason: "postcheck_pre_satisfied"
|
|
357
|
+
});
|
|
358
|
+
const mergedMeta = Object.freeze({
|
|
359
|
+
...clonedMeta ?? {},
|
|
360
|
+
runner: runnerMeta
|
|
361
|
+
});
|
|
362
|
+
const frozenPostcheck = Object.freeze([...operation.postcheck]);
|
|
363
|
+
return Object.freeze({
|
|
364
|
+
id: operation.id,
|
|
365
|
+
label: operation.label,
|
|
366
|
+
...ifDefined("summary", operation.summary),
|
|
367
|
+
operationClass: operation.operationClass,
|
|
368
|
+
target: operation.target,
|
|
369
|
+
precheck: Object.freeze([]),
|
|
370
|
+
execute: Object.freeze([]),
|
|
371
|
+
postcheck: frozenPostcheck,
|
|
372
|
+
...ifDefined("meta", operation.meta || mergedMeta ? mergedMeta : void 0)
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
markerMatchesDestination(marker, plan) {
|
|
376
|
+
if (!marker) return false;
|
|
377
|
+
if (marker.storageHash !== plan.destination.storageHash) return false;
|
|
378
|
+
if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) return false;
|
|
379
|
+
return true;
|
|
380
|
+
}
|
|
381
|
+
enforcePolicyCompatibility(policy, operations) {
|
|
382
|
+
const allowedClasses = new Set(policy.allowedOperationClasses);
|
|
383
|
+
for (const operation of operations) if (!allowedClasses.has(operation.operationClass)) return runnerFailure("MIGRATION.POLICY_VIOLATION", `Operation ${operation.id} has class "${operation.operationClass}" which is not allowed by policy.`, {
|
|
384
|
+
why: `Policy only allows: ${policy.allowedOperationClasses.join(", ")}.`,
|
|
385
|
+
meta: {
|
|
386
|
+
operationId: operation.id,
|
|
387
|
+
operationClass: operation.operationClass,
|
|
388
|
+
allowedClasses: policy.allowedOperationClasses
|
|
389
|
+
}
|
|
390
|
+
});
|
|
391
|
+
return okVoid();
|
|
392
|
+
}
|
|
393
|
+
ensureMarkerCompatibility(marker, plan) {
|
|
394
|
+
const origin = plan.origin ?? null;
|
|
395
|
+
if (!origin) return okVoid();
|
|
396
|
+
if (!marker) return runnerFailure("MIGRATION.MARKER_ORIGIN_MISMATCH", `Missing contract marker: expected origin storage hash ${origin.storageHash}.`, { meta: { expectedOriginStorageHash: origin.storageHash } });
|
|
397
|
+
if (marker.storageHash !== origin.storageHash) return runnerFailure("MIGRATION.MARKER_ORIGIN_MISMATCH", `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`, { meta: {
|
|
398
|
+
markerStorageHash: marker.storageHash,
|
|
399
|
+
expectedOriginStorageHash: origin.storageHash
|
|
400
|
+
} });
|
|
401
|
+
if (origin.profileHash && marker.profileHash !== origin.profileHash) return runnerFailure("MIGRATION.MARKER_ORIGIN_MISMATCH", `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`, { meta: {
|
|
402
|
+
markerProfileHash: marker.profileHash,
|
|
403
|
+
expectedOriginProfileHash: origin.profileHash
|
|
404
|
+
} });
|
|
405
|
+
return okVoid();
|
|
406
|
+
}
|
|
407
|
+
ensurePlanMatchesDestinationContract(destination, contract) {
|
|
408
|
+
if (destination.storageHash !== contract.storage.storageHash) return runnerFailure("MIGRATION.DESTINATION_CONTRACT_MISMATCH", `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`, { meta: {
|
|
409
|
+
planStorageHash: destination.storageHash,
|
|
410
|
+
contractStorageHash: contract.storage.storageHash
|
|
411
|
+
} });
|
|
412
|
+
if (destination.profileHash && contract.profileHash && destination.profileHash !== contract.profileHash) return runnerFailure("MIGRATION.DESTINATION_CONTRACT_MISMATCH", `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`, { meta: {
|
|
413
|
+
planProfileHash: destination.profileHash,
|
|
414
|
+
contractProfileHash: contract.profileHash
|
|
415
|
+
} });
|
|
416
|
+
return okVoid();
|
|
417
|
+
}
|
|
418
|
+
async upsertMarker(driver, options, existingMarker, space) {
|
|
419
|
+
const destination = {
|
|
420
|
+
storageHash: options.plan.destination.storageHash,
|
|
421
|
+
profileHash: options.plan.destination.profileHash ?? options.destinationContract.profileHash ?? options.plan.destination.storageHash,
|
|
422
|
+
invariants: options.plan.providedInvariants ?? []
|
|
423
|
+
};
|
|
424
|
+
if (!existingMarker) {
|
|
425
|
+
await this.family.initMarker({
|
|
426
|
+
driver,
|
|
427
|
+
space,
|
|
428
|
+
destination
|
|
429
|
+
});
|
|
430
|
+
return okVoid();
|
|
431
|
+
}
|
|
432
|
+
if (!await this.family.updateMarker({
|
|
433
|
+
driver,
|
|
434
|
+
space,
|
|
435
|
+
expectedFrom: existingMarker.storageHash,
|
|
436
|
+
destination
|
|
437
|
+
})) {
|
|
438
|
+
const found = await this.family.readMarker({
|
|
439
|
+
driver,
|
|
440
|
+
space
|
|
441
|
+
});
|
|
442
|
+
return runnerFailure("MIGRATION.MARKER_CAS_FAILURE", "Marker was modified by another process during migration execution.", { meta: {
|
|
443
|
+
space,
|
|
444
|
+
expectedStorageHash: existingMarker.storageHash,
|
|
445
|
+
foundStorageHash: found?.storageHash ?? null,
|
|
446
|
+
destinationStorageHash: options.plan.destination.storageHash
|
|
447
|
+
} });
|
|
448
|
+
}
|
|
449
|
+
return okVoid();
|
|
450
|
+
}
|
|
451
|
+
async recordLedgerEntries(driver, options, executedOperations, planOpsLength) {
|
|
452
|
+
const space = options.plan.spaceId;
|
|
453
|
+
const edges = options.migrationEdges;
|
|
454
|
+
const totalEdgeOps = edges.reduce((sum, edge) => sum + edge.operationCount, 0);
|
|
455
|
+
if (totalEdgeOps !== planOpsLength) throw new InternalError(`Ledger write: plan.operations length (${planOpsLength}) does not match sum of migrationEdges operationCount (${totalEdgeOps})`);
|
|
456
|
+
let offset = 0;
|
|
457
|
+
for (const edge of edges) {
|
|
458
|
+
const edgeOps = executedOperations.slice(offset, offset + edge.operationCount);
|
|
459
|
+
offset += edge.operationCount;
|
|
460
|
+
await this.family.writeLedgerEntry({
|
|
461
|
+
driver,
|
|
462
|
+
space,
|
|
463
|
+
entry: {
|
|
464
|
+
edgeId: `${edge.from}->${edge.to}`,
|
|
465
|
+
from: edge.from,
|
|
466
|
+
to: edge.to,
|
|
467
|
+
migrationName: edge.dirName,
|
|
468
|
+
migrationHash: edge.migrationHash,
|
|
469
|
+
operations: edgeOps,
|
|
470
|
+
...ifDefined("destinationContractJson", edge.destinationContractJson)
|
|
471
|
+
}
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
async acquireLock(driver) {
|
|
476
|
+
await driver.query(MARKER_LOCK_SQL, [MARKER_LOCK_KEY]);
|
|
477
|
+
}
|
|
478
|
+
async beginTransaction(driver) {
|
|
479
|
+
await driver.query("BEGIN");
|
|
480
|
+
}
|
|
481
|
+
async commitTransaction(driver) {
|
|
482
|
+
await driver.query("COMMIT");
|
|
483
|
+
}
|
|
484
|
+
async rollbackTransaction(driver) {
|
|
485
|
+
await driver.query("ROLLBACK");
|
|
486
|
+
}
|
|
487
|
+
async executeStatement(driver, statement) {
|
|
488
|
+
await driver.query(statement.sql, statement.params);
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
/**
|
|
492
|
+
* Postgres target `SchemaVerifier` concretion. Plugs into the
|
|
493
|
+
* SQL-shared verification surface; production verification today still
|
|
494
|
+
* routes through the family verify verdict (`verifySqlSchemaByDiff` over
|
|
495
|
+
* `diffPostgresSchema`), which carries options (codec hooks,
|
|
496
|
+
* normalizers, framework components) that the framework-level
|
|
497
|
+
* `SchemaVerifyOptions` shape does not yet surface.
|
|
498
|
+
*
|
|
499
|
+
* The hooks return the empty list pending the call-site migration that
|
|
500
|
+
* routes the existing verifier behaviour through the SPI — at that
|
|
501
|
+
* point `verifyCommonSqlSchema` will likely lift onto the family base
|
|
502
|
+
* (mirroring `verifyCommonMongoSchema`) and `verifyTargetExtensions`
|
|
503
|
+
* will house Postgres-only kinds (functions, RLS policies in a future
|
|
504
|
+
* project).
|
|
505
|
+
*/
|
|
506
|
+
var PostgresSchemaVerifier = class extends SqlSchemaVerifierBase {
|
|
507
|
+
verifyCommonSqlSchema(_options) {
|
|
508
|
+
return [];
|
|
509
|
+
}
|
|
510
|
+
verifyTargetExtensions(_options) {
|
|
511
|
+
return [];
|
|
512
|
+
}
|
|
513
|
+
};
|
|
514
|
+
/** The name a contract namespace is written under in PSL. */
|
|
515
|
+
function pslNamespaceName(namespaceId) {
|
|
516
|
+
return namespaceId === UNBOUND_NAMESPACE_ID ? UNBOUND_PSL_NAMESPACE_NAME : namespaceId;
|
|
517
|
+
}
|
|
518
|
+
function modelCoordinate(namespaceId, modelName) {
|
|
519
|
+
return JSON.stringify([namespaceId, modelName]);
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Every domain model of the contract, in declaration order, with its storage table. Contract
|
|
523
|
+
* validation has checked that each model's table exists, in the namespace of the model.
|
|
524
|
+
*/
|
|
525
|
+
function indexContractModels(contract) {
|
|
526
|
+
const entries = [];
|
|
527
|
+
for (const [namespaceId, domainNamespace] of Object.entries(contract.domain.namespaces)) for (const [name, model] of Object.entries(domainNamespace.models)) {
|
|
528
|
+
const storage = blindCast(model.storage);
|
|
529
|
+
const table = contract.storage.namespaces[storage.namespaceId]?.entries.table?.[storage.table];
|
|
530
|
+
assertDefined(table, `model "${namespaceId}.${name}" is stored in table "${storage.namespaceId}"."${storage.table}", which the storage does not declare`);
|
|
531
|
+
const fields = Object.entries(storage.fields);
|
|
532
|
+
entries.push({
|
|
533
|
+
namespaceId: storage.namespaceId,
|
|
534
|
+
name,
|
|
535
|
+
tableName: storage.table,
|
|
536
|
+
storage,
|
|
537
|
+
model,
|
|
538
|
+
table,
|
|
539
|
+
fieldNamesByColumn: new Map(fields.map(([fieldName, field]) => [field.column, fieldName])),
|
|
540
|
+
ownColumns: new Set(fields.map(([, field]) => field.column))
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
return entries;
|
|
544
|
+
}
|
|
545
|
+
/** Models keyed by their `(namespace, model)` coordinate. */
|
|
546
|
+
function modelsByCoordinate(entries) {
|
|
547
|
+
return new Map(entries.map((entry) => [modelCoordinate(entry.namespaceId, entry.name), entry]));
|
|
548
|
+
}
|
|
549
|
+
/** A cross reference's coordinate; one into another contract space never matches a model of this contract. */
|
|
550
|
+
function crossReferenceCoordinate(reference) {
|
|
551
|
+
return reference.space === void 0 ? modelCoordinate(reference.namespace, reference.model) : JSON.stringify([
|
|
552
|
+
reference.space,
|
|
553
|
+
reference.namespace,
|
|
554
|
+
reference.model
|
|
555
|
+
]);
|
|
556
|
+
}
|
|
557
|
+
/** The base a variant model extends, with the discriminator value it is stored under. */
|
|
558
|
+
function variantInfo(entry, byCoordinate) {
|
|
559
|
+
if (entry.model.base === void 0) return void 0;
|
|
560
|
+
const base = byCoordinate.get(crossReferenceCoordinate(entry.model.base));
|
|
561
|
+
const value = Object.entries(base?.model.variants ?? {}).find(([, reference]) => reference.namespace === entry.namespaceId && reference.model === entry.name)?.[0];
|
|
562
|
+
assertDefined(base, `model "${entry.namespaceId}.${entry.name}" extends a base the contract does not declare`);
|
|
563
|
+
assertDefined(value, `model "${entry.namespaceId}.${entry.name}" extends base "${base.name}", which does not list it as a variant`);
|
|
564
|
+
return {
|
|
565
|
+
base,
|
|
566
|
+
value,
|
|
567
|
+
singleTable: base.namespaceId === entry.namespaceId && base.tableName === entry.tableName
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
/** The columns the PSL source adds to a multi-table variant's table: its base's primary key. */
|
|
571
|
+
function variantLinkColumns(entry, variant) {
|
|
572
|
+
if (variant === void 0 || variant.singleTable) return [];
|
|
573
|
+
return (variant.base.table.primaryKey?.columns ?? []).filter((column) => !entry.ownColumns.has(column));
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* The foreign key the PSL source synthesizes from a multi-table variant to its base: unnamed, over
|
|
577
|
+
* the base's primary key columns, cascading on delete.
|
|
578
|
+
*/
|
|
579
|
+
function isVariantLinkForeignKey(fk, variant) {
|
|
580
|
+
if (variant === void 0 || variant.singleTable) return false;
|
|
581
|
+
const baseKey = canonicalizeJson(variant.base.table.primaryKey?.columns ?? []);
|
|
582
|
+
return fk.target.namespaceId === variant.base.namespaceId && fk.target.tableName === variant.base.tableName && fk.target.spaceId === void 0 && canonicalizeJson(fk.source.columns) === baseKey && canonicalizeJson(fk.target.columns) === baseKey && fk.name === void 0 && fk.onDelete === "cascade" && fk.onUpdate === void 0;
|
|
583
|
+
}
|
|
584
|
+
const KEEP_SOURCE = "Keep authoring this contract in its current source.";
|
|
585
|
+
function unsupported(message, why, fix, meta) {
|
|
586
|
+
return postgresError("CONTRACT.PRINT_UNSUPPORTED", `contract print: ${message}`, {
|
|
587
|
+
why,
|
|
588
|
+
fix,
|
|
589
|
+
meta
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
function sameJson(left, right) {
|
|
593
|
+
return canonicalizeJson(left) === canonicalizeJson(right);
|
|
594
|
+
}
|
|
595
|
+
function sameValues$1(left, right) {
|
|
596
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
597
|
+
}
|
|
598
|
+
function refuseColumnWithoutPslType(column, coordinate) {
|
|
599
|
+
throw unsupported(`column ${coordinate} has data type "${column.dataType}" with codec "${column.codecId}", and no PSL type in the configured stack produces that pair.`, "A column is written as a PSL type that reads back with its codec and data type, and none of the types the target, adapter and extensions contribute does.", "Add the extension that contributes this type to the config, or keep authoring this contract in its current source.", {
|
|
600
|
+
coordinate,
|
|
601
|
+
dataType: column.dataType,
|
|
602
|
+
codecId: column.codecId
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Refuses a string type argument the PSL source would read back differently: it reads a string
|
|
607
|
+
* argument between its quotes as written, with no escapes.
|
|
608
|
+
*/
|
|
609
|
+
function refuseUnwritableTypeArgument(value, coordinate) {
|
|
610
|
+
throw unsupported(`column ${coordinate} takes the type argument ${JSON.stringify(value)}, which a PSL type argument cannot carry.`, "The PSL source reads a string type argument as written between its quotes, with no escapes, so a quote, backslash or line break in it would read back differently.", KEEP_SOURCE, {
|
|
611
|
+
coordinate,
|
|
612
|
+
argument: value
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
function refuseDefaultOutsideEnum(input) {
|
|
616
|
+
throw unsupported(`column ${input.coordinate} defaults to ${JSON.stringify(input.value)}, which is not a member of enum ${input.pslTypeName}.`, "A default on a domain enum column is written as the member name, and no member carries this value.", "Give the column a default that is one of the enum members, or drop it.", {
|
|
617
|
+
coordinate: input.coordinate,
|
|
618
|
+
pslTypeName: input.pslTypeName
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
function refuseUnwritableLiteralDefault(input) {
|
|
622
|
+
throw unsupported(`column ${input.coordinate} has a default that cannot be written in Prisma 8 PSL: no data type the ${input.pslTypeName} type takes writes ${input.written}.`, "Writing the value in any other form would parse, but the PSL source would read it back as a different value.", "Replace the default with a database expression default, or drop the default before printing.", {
|
|
623
|
+
coordinate: input.coordinate,
|
|
624
|
+
pslTypeName: input.pslTypeName
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
function describePhases(phases) {
|
|
628
|
+
return [phases.onCreate === void 0 ? void 0 : `"${phases.onCreate}" on create`, phases.onUpdate === void 0 ? void 0 : `"${phases.onUpdate}" on update`].filter((phase) => phase !== void 0).join(" and ");
|
|
629
|
+
}
|
|
630
|
+
function refuseGeneratorsNoPresetWritesTogether(phases) {
|
|
631
|
+
throw unsupported(`column ${phases.coordinate} generates ${describePhases(phases)}, which cannot be written in Prisma 8 PSL.`, "The field preset in the configured stack that writes one of these generators for the column codec does not also write the other phase, so that phase would be dropped from the written file, and no default function in the configured stack writes the column's generators instead.", KEEP_SOURCE, {
|
|
632
|
+
coordinate: phases.coordinate,
|
|
633
|
+
onCreate: phases.onCreate,
|
|
634
|
+
onUpdate: phases.onUpdate
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
function describeGenerator(generator) {
|
|
638
|
+
if (generator === void 0) return "no generator";
|
|
639
|
+
const params = generator.params ?? {};
|
|
640
|
+
return Object.keys(params).length === 0 ? `"${generator.id}"` : `"${generator.id}" with params ${canonicalizeJson(params)}`;
|
|
641
|
+
}
|
|
642
|
+
function describeDifference(difference) {
|
|
643
|
+
switch (difference.part) {
|
|
644
|
+
case "codecId": return `codec "${difference.printed}" instead of "${difference.column}"`;
|
|
645
|
+
case "typeParams": return `type params ${canonicalizeJson(difference.printed ?? {})} instead of ${canonicalizeJson(difference.column ?? {})}`;
|
|
646
|
+
case "onCreate":
|
|
647
|
+
case "onUpdate": return `${difference.part === "onCreate" ? "on create" : "on update"} ${describeGenerator(difference.printed)} instead of ${describeGenerator(difference.column)}`;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
const COLUMN_TYPE_KINDS = {
|
|
651
|
+
namedType: "a named type",
|
|
652
|
+
valueObject: "a value object",
|
|
653
|
+
enum: "an enum"
|
|
654
|
+
};
|
|
655
|
+
function describeUnwritableReason(reason) {
|
|
656
|
+
switch (reason.kind) {
|
|
657
|
+
case "columnType": return `its type ${reason.typeName} is ${COLUMN_TYPE_KINDS[reason.columnType]}, which the preset call would replace`;
|
|
658
|
+
case "list": return "the column is a list, and a preset call cannot be a list element";
|
|
659
|
+
case "unwritableArgument": return `its type param "${reason.argument}" is ${JSON.stringify(reason.value)}, which a PSL argument cannot carry`;
|
|
660
|
+
case "argumentsRejected": return `the preset does not accept the call, since ${reason.message}`;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
function refuseUnwritablePresetCall(input) {
|
|
664
|
+
throw unsupported(`column ${input.coordinate} cannot be written with field preset ${input.preset}: ${describeUnwritableReason(input.reason)}.`, "The printer writes a column's generators as the call of the field preset that writes the column's codec with them, or a create-only generator as the call of its default function. The preset call cannot be written for this column, and no default function in the configured stack writes its generators.", KEEP_SOURCE, {
|
|
665
|
+
coordinate: input.coordinate,
|
|
666
|
+
preset: input.preset,
|
|
667
|
+
reason: input.reason
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
function refusePresetCallReadingBackDifferently(input) {
|
|
671
|
+
throw unsupported(`column ${input.coordinate} is written with field preset ${input.preset}, and that call reads back as a different column: ${input.differences.map(describeDifference).join("; ")}.`, "The printer writes a column's generators as the call of the field preset that writes the column's codec with them, and that call must read back with the column's codec, type params and generators. No default function in the configured stack writes its generators instead.", KEEP_SOURCE, {
|
|
672
|
+
coordinate: input.coordinate,
|
|
673
|
+
preset: input.preset,
|
|
674
|
+
differences: input.differences
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
function refuseGeneratorOnUpdate(phases) {
|
|
678
|
+
throw unsupported(`column ${phases.coordinate} generates a value on update ("${phases.onUpdate}"), which cannot be written in Prisma 8 PSL.`, "`@default(…)` writes a generator for create only; a generator on update is written only through a field preset, and the configured stack has no field preset for the column codec that contract print can write with this generator.", KEEP_SOURCE, {
|
|
679
|
+
coordinate: phases.coordinate,
|
|
680
|
+
onCreate: phases.onCreate,
|
|
681
|
+
onUpdate: phases.onUpdate
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
function refuseGeneratorWithoutPslFunction(input) {
|
|
685
|
+
const { coordinate, onCreate, onUpdate, registeredBy } = input;
|
|
686
|
+
const meta = {
|
|
687
|
+
coordinate,
|
|
688
|
+
onCreate,
|
|
689
|
+
onUpdate
|
|
690
|
+
};
|
|
691
|
+
if (registeredBy === void 0) throw unsupported(`column ${coordinate} is generated by "${onCreate}", which no component in the configured stack registers.`, "The printer writes each generator as the PSL call of the default function in the configured stack that produces it, and no component in the stack registers this generator.", "Add the extension that registers the generator and its default function to the config, or keep authoring this contract in its current source.", meta);
|
|
692
|
+
const { componentId } = registeredBy;
|
|
693
|
+
throw unsupported(`column ${coordinate} is generated by "${onCreate}", which ${componentId === void 0 ? "a configured component" : `"${componentId}"`} registers, but no default function in the configured stack declares how contract print writes it, and the stack has no field preset for the column codec that contract print can write with it.`, "The printer writes a generator as the call of the field preset that writes the column's codec with it, or else as the PSL call of the default function that declares `printArguments` for it. The configured stack has neither for this generator.", `If ${componentId === void 0 ? `the component that registers "${onCreate}"` : `"${componentId}"`} has a default function that produces ${componentId === void 0 ? "it" : `"${onCreate}"`}, its author must add \`printArguments\` for "${onCreate}" to it, as the upgrade instructions "contract-print-generated-values" for extension authors describe. Otherwise "${onCreate}" is written only through a field preset of the column codec, and the configured stack has none that contract print can write. Until then, keep authoring this contract in its current source.`, {
|
|
694
|
+
...meta,
|
|
695
|
+
...ifDefined("componentId", componentId)
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
function refuseGeneratorWithDatabaseDefault(input) {
|
|
699
|
+
throw unsupported(`column ${input.coordinate} has both a generated value ("${input.onCreate}") and a database default, which cannot be written in Prisma 8 PSL.`, "`@default(…)` writes either the generator or the database default, so the other would be lost.", "Drop one of the two, or keep authoring this contract in its current source.", {
|
|
700
|
+
coordinate: input.coordinate,
|
|
701
|
+
onCreate: input.onCreate
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* The value-set references the PSL source gives a field typed by a domain enum, one per plane: the
|
|
706
|
+
* domain names the enum and the storage column names the enum's value set, both in the default
|
|
707
|
+
* namespace. A field with no domain enum has neither.
|
|
708
|
+
*/
|
|
709
|
+
function derivedValueSetRefs(enumName) {
|
|
710
|
+
if (enumName === void 0) return {
|
|
711
|
+
domain: void 0,
|
|
712
|
+
storage: void 0
|
|
713
|
+
};
|
|
714
|
+
const common = {
|
|
715
|
+
namespaceId: DEFAULT_NAMESPACE_ID,
|
|
716
|
+
entityName: enumName
|
|
717
|
+
};
|
|
718
|
+
return {
|
|
719
|
+
domain: {
|
|
720
|
+
plane: "domain",
|
|
721
|
+
entityKind: "enum",
|
|
722
|
+
...common
|
|
723
|
+
},
|
|
724
|
+
storage: {
|
|
725
|
+
plane: "storage",
|
|
726
|
+
entityKind: "valueSet",
|
|
727
|
+
...common
|
|
728
|
+
}
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Refuses a field whose column the PSL source would not derive from it: PSL writes the field once,
|
|
733
|
+
* and the PSL source derives the column's nullability, list marker, codec and type parameters from
|
|
734
|
+
* what is written.
|
|
735
|
+
*/
|
|
736
|
+
function refuseFieldColumnMismatch(input) {
|
|
737
|
+
const { field, column, coordinate } = input;
|
|
738
|
+
const fix = "Make the field and its column agree, or keep authoring this contract in its current source.";
|
|
739
|
+
const fixForEarlierRelease = `If an earlier release emitted this contract, emit it again. ${fix}`;
|
|
740
|
+
if (input.singleTableVariant && !column.nullable) throw unsupported(`column ${coordinate} of single-table variant "${input.modelName}" is not nullable, which cannot be written in Prisma 8 PSL.`, "The PSL source makes every column of a single-table variant nullable, because the base's other rows leave it empty.", fix, { coordinate });
|
|
741
|
+
if (!input.singleTableVariant && field.nullable !== column.nullable) throw unsupported(`field ${coordinate} is ${field.nullable ? "optional" : "required"} but its column is ${column.nullable ? "nullable" : "not nullable"}, which cannot be written in Prisma 8 PSL.`, "PSL writes `?` once, and the PSL source derives the column from the field.", fix, { coordinate });
|
|
742
|
+
if ((field.type.kind === "scalar" && !!field.many) !== (column.many !== false)) throw unsupported(`field ${coordinate} is ${field.many ? "a list" : "not a list"} but its column is ${column.many !== false ? "a list" : "not a list"}, which cannot be written in Prisma 8 PSL.`, "PSL writes `[]` once: the PSL source stores a list of scalars in a list column, and a list of value objects in one JSON column.", fix, { coordinate });
|
|
743
|
+
if (field.type.kind === "scalar" && (field.type.codecId !== column.codecId || !sameJson(resolvedTypeParams(field.type, void 0), resolvedTypeParams(column, input.namedTypes)))) throw unsupported(`field ${coordinate} has a different codec or type parameters from its column, which cannot be written in Prisma 8 PSL.`, "The PSL source derives a scalar field's codec and type parameters from its column.", fixForEarlierRelease, { coordinate });
|
|
744
|
+
if (field.type.kind !== "scalar" || column.codecId === "pg/enum@1") return;
|
|
745
|
+
const enumName = column.valueSet?.entityName;
|
|
746
|
+
const derived = derivedValueSetRefs(enumName);
|
|
747
|
+
if (!sameJson(field.valueSet, derived.domain) || !sameJson(column.valueSet, derived.storage) || enumName !== void 0 && !input.domainEnumNames.has(enumName)) throw unsupported(`field ${coordinate} and its column do not name the enum of the default namespace and its value set that the PSL source derives for a field typed by an enum, which cannot be written in Prisma 8 PSL.`, "PSL types the field by the enum name, and the PSL source then points the column at the value set of that enum in the default namespace, and the field at the enum.", fixForEarlierRelease, { coordinate });
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* Refuses a field PSL has no form for: one whose type is a union of types, or one that is a
|
|
751
|
+
* dictionary. Runs for model fields and value-object members alike.
|
|
752
|
+
*/
|
|
753
|
+
function refuseUnwritableFieldShape(field, coordinate) {
|
|
754
|
+
if (field.type.kind === "union") throw unsupported(`field ${coordinate} has a ${field.type.kind} type, which cannot be written in Prisma 8 PSL.`, "A PSL field names one scalar, enum, or value-object type; a union of types has no PSL form.", "Give the field a single type, or keep authoring this contract in its current source.", {
|
|
755
|
+
coordinate,
|
|
756
|
+
kind: field.type.kind
|
|
757
|
+
});
|
|
758
|
+
if (field.dict !== true) return;
|
|
759
|
+
throw unsupported(`field ${coordinate} is a dictionary, which cannot be written in Prisma 8 PSL.`, "PSL writes a field as one value or a list; it has no form for a keyed dictionary.", KEEP_SOURCE, { coordinate });
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Refuses a value-object member with a value set other than the one the PSL source derives for a member typed by an enum: the enum of the default namespace, with the enum's codec and no type parameters.
|
|
763
|
+
*/
|
|
764
|
+
function refuseUnderivedMemberValueSet(input) {
|
|
765
|
+
const { field, type, coordinate } = input;
|
|
766
|
+
const { valueSet } = field;
|
|
767
|
+
if (valueSet === void 0) return;
|
|
768
|
+
const domainEnum = input.domainEnums[valueSet.entityName];
|
|
769
|
+
if (sameJson(valueSet, derivedValueSetRefs(valueSet.entityName).domain) && domainEnum?.codecId === type.codecId && type.typeParams === void 0) return;
|
|
770
|
+
throw unsupported(`value-object member ${coordinate} carries a value set other than an enum of the default namespace with that enum's codec and no type parameters, which cannot be written in Prisma 8 PSL.`, "PSL types the member by the enum name, and the PSL source then points the member at that enum in the default namespace and gives it the enum's codec.", KEEP_SOURCE, { coordinate });
|
|
771
|
+
}
|
|
772
|
+
function refuseMemberCodecWithoutNativeType(codecId, coordinate) {
|
|
773
|
+
throw unsupported(`value-object member ${coordinate} uses codec "${codecId}", which no Postgres codec in the configured stack names a native type for.`, "A value-object member has no storage column, so its PSL type is derived from the native type its codec names.", KEEP_SOURCE, {
|
|
774
|
+
coordinate,
|
|
775
|
+
codecId
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
function refuseMemberCodecNeedingTypeParameters(codecId, coordinate) {
|
|
779
|
+
throw unsupported(`value-object member ${coordinate} uses codec "${codecId}", which names a native type only from type parameters the member does not carry.`, "A value-object member has no storage column, so its PSL type is derived from the native type its codec names for its type parameters.", KEEP_SOURCE, {
|
|
780
|
+
coordinate,
|
|
781
|
+
codecId
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
/** Refuses a column a model stores under a field name the model does not declare. */
|
|
785
|
+
function refuseStorageOfUndeclaredField(input) {
|
|
786
|
+
const { entry, fieldName } = input;
|
|
787
|
+
throw unsupported(`model "${entry.namespaceId}.${entry.name}" stores "${fieldName}" in column ${input.coordinate}, but the model has no field of that name, so it cannot be written in Prisma 8 PSL.`, "PSL declares a field together with the column it is stored in.", "Declare the field on the model, or keep authoring this contract in its current source.", {
|
|
788
|
+
namespaceId: entry.namespaceId,
|
|
789
|
+
modelName: entry.name,
|
|
790
|
+
field: fieldName
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Refuses a column typed by a named type when the contract declares no such type, or when the
|
|
795
|
+
* column's data type or codec is not the named type's. PSL writes the column as the name of the
|
|
796
|
+
* type, and the PSL source copies both from the named type.
|
|
797
|
+
*/
|
|
798
|
+
function refuseColumnDifferingFromNamedType(input) {
|
|
799
|
+
const { column, typeRef, namedType, coordinate } = input;
|
|
800
|
+
if (namedType?.dataType === column.dataType && namedType.codecId === column.codecId) return;
|
|
801
|
+
throw unsupported(namedType === void 0 ? `column ${coordinate} is typed by the named type "${typeRef}", which the contract does not declare, so it cannot be written in Prisma 8 PSL.` : `column ${coordinate} is typed by the named type "${typeRef}" but has a different data type or codec from it, which cannot be written in Prisma 8 PSL.`, "PSL writes such a column as the name of its named type, and the PSL source gives the column the data type and codec of that named type.", "Make the column and its named type agree, or keep authoring this contract in its current source.", {
|
|
802
|
+
coordinate,
|
|
803
|
+
typeRef
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
function refuseColumnControl(column, coordinate) {
|
|
807
|
+
if (column.control === void 0) return;
|
|
808
|
+
throw unsupported(`column ${coordinate} carries its own control policy "${column.control}", which cannot be written in Prisma 8 PSL.`, "PSL declares a control policy per model with `@@control`; a field has no control attribute.", "Move the policy to the model, or keep authoring this contract in its current source.", {
|
|
809
|
+
coordinate,
|
|
810
|
+
control: column.control
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
/** Refuses a storage table no model is stored in, and a column no field or variant link stores. */
|
|
814
|
+
function refuseUnmodelledTablesAndColumns(contract, models, variants) {
|
|
815
|
+
const tableKey = (namespaceId, tableName) => JSON.stringify([namespaceId, tableName]);
|
|
816
|
+
const coveredColumns = /* @__PURE__ */ new Map();
|
|
817
|
+
for (const entry of models) {
|
|
818
|
+
const key = tableKey(entry.namespaceId, entry.tableName);
|
|
819
|
+
const columns = coveredColumns.get(key) ?? /* @__PURE__ */ new Set();
|
|
820
|
+
for (const column of entry.ownColumns) columns.add(column);
|
|
821
|
+
for (const column of variantLinkColumns(entry, variants.get(entry))) columns.add(column);
|
|
822
|
+
coveredColumns.set(key, columns);
|
|
823
|
+
}
|
|
824
|
+
for (const [namespaceId, namespace] of Object.entries(contract.storage.namespaces)) for (const [tableName, table] of Object.entries(namespace.entries.table ?? {})) {
|
|
825
|
+
const covered = coveredColumns.get(tableKey(namespaceId, tableName));
|
|
826
|
+
if (covered === void 0) throw unsupported(`table "${namespaceId}"."${tableName}" has no model stored in it, so it cannot be written in Prisma 8 PSL.`, "PSL declares a table through the model stored in it.", "Declare a model for the table, or keep authoring this contract in its current source.", {
|
|
827
|
+
namespaceId,
|
|
828
|
+
table: tableName
|
|
829
|
+
});
|
|
830
|
+
for (const column of Object.keys(table.columns)) {
|
|
831
|
+
if (covered.has(column)) continue;
|
|
832
|
+
throw unsupported(`column "${namespaceId}"."${tableName}"."${column}" is not stored by any field, so it cannot be written in Prisma 8 PSL.`, "PSL declares a column through the field stored in it; the only columns the PSL source adds are the primary key columns that link a multi-table variant to its base.", "Add a field for the column, or keep authoring this contract in its current source.", {
|
|
833
|
+
namespaceId,
|
|
834
|
+
table: tableName,
|
|
835
|
+
column
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
function refuseModelOwner(entry) {
|
|
841
|
+
if (entry.model.owner === void 0) return;
|
|
842
|
+
throw unsupported(`model "${entry.namespaceId}.${entry.name}" is owned by "${entry.model.owner}", which cannot be written in Prisma 8 PSL.`, "`owner` names the model this model is embedded in, and SQL PSL has no syntax for an owned model.", KEEP_SOURCE, {
|
|
843
|
+
namespaceId: entry.namespaceId,
|
|
844
|
+
modelName: entry.name,
|
|
845
|
+
owner: entry.model.owner
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
/**
|
|
849
|
+
* Refuses a multi-table variant whose link to its base differs from the one the PSL source derives:
|
|
850
|
+
* the base's primary key columns copied into the variant's table as its unnamed primary key, and
|
|
851
|
+
* the link foreign key.
|
|
852
|
+
*/
|
|
853
|
+
function refuseUnderivedVariantLink(entry, variant) {
|
|
854
|
+
const baseKey = variant.base.table.primaryKey?.columns ?? [];
|
|
855
|
+
const derivedKey = baseKey.length === 0 ? void 0 : { columns: baseKey };
|
|
856
|
+
const linkColumnsMatch = variantLinkColumns(entry, variant).every((column) => {
|
|
857
|
+
const base = variant.base.table.columns[column];
|
|
858
|
+
const expected = base === void 0 ? void 0 : new StorageColumn({
|
|
859
|
+
dataType: base.dataType,
|
|
860
|
+
codecId: base.codecId,
|
|
861
|
+
nullable: false,
|
|
862
|
+
...ifDefined("typeParams", base.typeParams),
|
|
863
|
+
...ifDefined("typeRef", base.typeRef)
|
|
864
|
+
});
|
|
865
|
+
return sameJson(entry.table.columns[column], expected);
|
|
866
|
+
});
|
|
867
|
+
const linkForeignKeys = entry.table.foreignKeys.filter((fk) => isVariantLinkForeignKey(fk, variant));
|
|
868
|
+
if (linkColumnsMatch && sameJson(entry.table.primaryKey, derivedKey) && linkForeignKeys.length === (baseKey.length === 0 ? 0 : 1)) return;
|
|
869
|
+
throw unsupported(`multi-table variant "${entry.namespaceId}.${entry.name}" is linked to its base "${variant.base.name}" differently from the link the PSL source derives, so it cannot be written in Prisma 8 PSL.`, "The PSL source links a multi-table variant to its base itself: it copies the base's primary key columns into the variant's table as its unnamed primary key, and adds an unnamed foreign key over them to the base that cascades on delete.", KEEP_SOURCE, {
|
|
870
|
+
namespaceId: entry.namespaceId,
|
|
871
|
+
modelName: entry.name
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* The PSL source groups relations by bare model name, so two models with the same name in
|
|
876
|
+
* different namespaces would get each other's relations.
|
|
877
|
+
*/
|
|
878
|
+
function refuseDuplicateModelNames(models) {
|
|
879
|
+
const namespacesByName = /* @__PURE__ */ new Map();
|
|
880
|
+
for (const entry of models) {
|
|
881
|
+
const namespaces = namespacesByName.get(entry.name) ?? [];
|
|
882
|
+
namespaces.push(entry.namespaceId);
|
|
883
|
+
namespacesByName.set(entry.name, namespaces);
|
|
884
|
+
}
|
|
885
|
+
for (const [name, namespaces] of namespacesByName) {
|
|
886
|
+
if (namespaces.length <= 1) continue;
|
|
887
|
+
throw unsupported(`model "${name}" is declared in more than one namespace (${namespaces.join(", ")}), which Prisma 8 PSL cannot carry: the PSL source groups relations by bare model name.`, "The PSL source groups relations by bare model name, so when the file is read back the two models would get each other's relations.", "Rename one of the models, then print again.", {
|
|
888
|
+
modelName: name,
|
|
889
|
+
namespaces
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* A PSL `enum` block is declared at the top level and lands in the default namespace, so only the
|
|
895
|
+
* default namespace's domain enums have a PSL form.
|
|
896
|
+
*/
|
|
897
|
+
function refuseEnumsOutsideDefaultNamespace(contract) {
|
|
898
|
+
for (const [namespaceId, domainNamespace] of Object.entries(contract.domain.namespaces)) {
|
|
899
|
+
const names = Object.keys(domainNamespace.enum ?? {});
|
|
900
|
+
if (namespaceId === "public" || names.length === 0) continue;
|
|
901
|
+
throw unsupported(`namespace "${namespaceId}" declares the enum${names.length === 1 ? "" : "s"} ${names.join(", ")}, which cannot be written in Prisma 8 PSL: an enum block is declared at the top level and belongs to the default namespace.`, "The PSL source refuses an enum block inside a namespace block, so an enum outside the default namespace has no PSL form.", "Move the enum to the default namespace, or keep authoring this contract in its current source.", {
|
|
902
|
+
namespaceId,
|
|
903
|
+
names
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
/** The PSL source reads every `type` block into the default namespace. */
|
|
908
|
+
function refuseValueObjectsOutsideDefaultNamespace(contract, namespaceId) {
|
|
909
|
+
const names = Object.keys(contract.domain.namespaces[namespaceId]?.valueObjects ?? {});
|
|
910
|
+
if (namespaceId === "public" || names.length === 0) return;
|
|
911
|
+
throw unsupported(`namespace "${namespaceId}" declares the value object${names.length === 1 ? "" : "s"} ${names.join(", ")}, which cannot be written in Prisma 8 PSL: the PSL source reads every value object into the default namespace.`, "A `type` block written in any namespace reads back into the default namespace, so the value object would move.", "Move the value object to the default namespace, or keep authoring this contract in its current source.", {
|
|
912
|
+
namespaceId,
|
|
913
|
+
names
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Refuses a check or index whose name is neither its prefix followed by the hash of its content,
|
|
918
|
+
* which `name:` derives, nor free of a prefix, which `map:` needs.
|
|
919
|
+
*/
|
|
920
|
+
function refuseUnwritableObjectName(input) {
|
|
921
|
+
const { kind, entry, name, prefix } = input;
|
|
922
|
+
throw unsupported(`${kind} "${name}" on "${entry.namespaceId}"."${entry.tableName}" has the prefix "${prefix}", but its name is not that prefix followed by the hash of its ${kind === "check" ? "expression" : "content"}, so it cannot be written in Prisma 8 PSL.`, `\`name:\` makes the PSL source derive the name from the prefix and that hash, and \`map:\` writes an exact name with no prefix, so neither reads back as this ${kind}.`, KEEP_SOURCE, {
|
|
923
|
+
namespaceId: entry.namespaceId,
|
|
924
|
+
table: entry.tableName,
|
|
925
|
+
name,
|
|
926
|
+
prefix
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Refuses a table whose checks differ from the derived ones where they overlap: a derived check the
|
|
931
|
+
* table lacks, or a check with a derived check's name but not its prefix and expression. The PSL
|
|
932
|
+
* source adds the derived checks itself, so they are never written.
|
|
933
|
+
*/
|
|
934
|
+
function refuseUnderivedChecks(entry, derived) {
|
|
935
|
+
const checks = new Map((entry.table.checks ?? []).map((check) => [check.name, check]));
|
|
936
|
+
for (const [name, expected] of derived) {
|
|
937
|
+
const check = checks.get(name);
|
|
938
|
+
if (check?.prefix === expected.prefix && check.expression === expected.expression) continue;
|
|
939
|
+
throw unsupported(`table "${entry.namespaceId}"."${entry.tableName}" ${check === void 0 ? "lacks" : "changes"} the check "${name}" the PSL source derives, so it cannot be written in Prisma 8 PSL.`, "The PSL source derives a membership check for each column of a managed table typed by an enum, and an element-not-null check for each list column whose elements are not nullable.", KEEP_SOURCE, {
|
|
940
|
+
namespaceId: entry.namespaceId,
|
|
941
|
+
table: entry.tableName,
|
|
942
|
+
name
|
|
943
|
+
});
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Refuses index options PSL cannot write: `options:` takes string values under identifier keys,
|
|
948
|
+
* and requires a `type`.
|
|
949
|
+
*/
|
|
950
|
+
function refuseUnwritableIndexOptions(entry, index) {
|
|
951
|
+
const meta = {
|
|
952
|
+
namespaceId: entry.namespaceId,
|
|
953
|
+
table: entry.tableName,
|
|
954
|
+
index: index.name
|
|
955
|
+
};
|
|
956
|
+
if (index.options !== void 0 && index.type === void 0) throw unsupported(`index "${index.name}" on "${entry.namespaceId}"."${entry.tableName}" has options but no type, which cannot be written in Prisma 8 PSL.`, "The PSL source reads `options:` on an index only together with `type:`.", "Give the index a type, or keep authoring this contract in its current source.", meta);
|
|
957
|
+
for (const [key, value] of Object.entries(index.options ?? {})) {
|
|
958
|
+
refuseUnwritableName("index option", key);
|
|
959
|
+
if (typeof value === "string") continue;
|
|
960
|
+
throw unsupported(`index "${index.name}" on "${entry.namespaceId}"."${entry.tableName}" has option "${key}" whose value is not a string, which cannot be written in Prisma 8 PSL.`, "The PSL `options:` argument takes string values only, and reads every value back as a string.", "Write the option value as a string, or keep authoring this contract in its current source.", {
|
|
961
|
+
...meta,
|
|
962
|
+
key
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
function describeSqlTextOwner(owner) {
|
|
967
|
+
if (owner.kind === "default") return {
|
|
968
|
+
subject: `default of column ${owner.coordinate}`,
|
|
969
|
+
meta: { coordinate: owner.coordinate }
|
|
970
|
+
};
|
|
971
|
+
const { kind, namespaceId, table, name } = owner;
|
|
972
|
+
return {
|
|
973
|
+
subject: `${kind} "${name}" on "${namespaceId}"."${table}"`,
|
|
974
|
+
meta: kind === "policy" ? {
|
|
975
|
+
namespaceId,
|
|
976
|
+
table,
|
|
977
|
+
policy: name
|
|
978
|
+
} : {
|
|
979
|
+
namespaceId,
|
|
980
|
+
table,
|
|
981
|
+
name
|
|
982
|
+
}
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
/** Refuses an index, check, policy or column default whose SQL a `sql` literal cannot write back unchanged, because reading the literal canonicalizes it into different text. */
|
|
986
|
+
function refuseSqlTextThatDoesNotReadBack(input) {
|
|
987
|
+
if (sqlTextsReadBack(input.texts)) return;
|
|
988
|
+
const { subject, meta } = describeSqlTextOwner(input);
|
|
989
|
+
throw unsupported(`${subject} holds SQL that a sql literal cannot write back unchanged, so it cannot be written in Prisma 8 PSL.`, "A sql literal is canonicalized when it is read: indentation shared by every line, blank lines at the start or end, a carriage return and a whitespace-only line are removed, so this text would read back as different SQL.", "Write the SQL in that canonical form in the contract's source, or keep authoring this contract in its current source.", meta);
|
|
990
|
+
}
|
|
991
|
+
function refuseToOneRelationWithoutForeignKey(modelName, fieldName) {
|
|
992
|
+
throw unsupported(`relation "${modelName}.${fieldName}" has no foreign key in storage, which Prisma 8 PSL cannot express.`, "A to-one relation is authored as `@relation(fields:…, references:…)`, which always lowers to a foreign key.", "Declare a foreign key for the relation, or keep authoring this contract in its current source.", {
|
|
993
|
+
model: modelName,
|
|
994
|
+
field: fieldName
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
/**
|
|
998
|
+
* A foreign key backed by a primary key or unique constraint that only starts with its columns is written as the relation's `index: "<name>"`, which needs the key's name; the contract states none.
|
|
999
|
+
*/
|
|
1000
|
+
function refuseUnnamedForeignKeyBacking(modelName, fieldName) {
|
|
1001
|
+
throw unsupported(`relation "${modelName}.${fieldName}" is backed by a key with no name, which its @relation cannot name.`, "The key's first columns are the foreign key's, but it has more columns, so a relation that names nothing would get its own backing index instead.", "Give the key a name, or keep authoring this contract in its current source.", {
|
|
1002
|
+
model: modelName,
|
|
1003
|
+
field: fieldName
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
/**
|
|
1007
|
+
* A foreign key no relation travels has no PSL form: the PSL source derives every foreign key from
|
|
1008
|
+
* a `@relation`, so this one would be lost.
|
|
1009
|
+
*/
|
|
1010
|
+
function refuseUntravelledForeignKeys(entry, variant, travelled) {
|
|
1011
|
+
for (const fk of entry.table.foreignKeys) {
|
|
1012
|
+
if (travelled.has(fk) || isVariantLinkForeignKey(fk, variant)) continue;
|
|
1013
|
+
if (variant?.singleTable === true && !fk.source.columns.every((c) => entry.ownColumns.has(c))) continue;
|
|
1014
|
+
throw unsupported(`table "${entry.namespaceId}"."${entry.tableName}" has a foreign key on (${fk.source.columns.join(", ")}) that no relation of model "${entry.name}" travels, which cannot be written in Prisma 8 PSL.`, "The PSL source derives every foreign key from a `@relation` field; a foreign key without one has no PSL form.", "Declare a relation over the foreign key, or keep authoring this contract in its current source.", {
|
|
1015
|
+
namespaceId: entry.namespaceId,
|
|
1016
|
+
table: entry.tableName,
|
|
1017
|
+
columns: fk.source.columns
|
|
1018
|
+
});
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
function refuseRelationToOtherContractSpace(input) {
|
|
1022
|
+
if (input.space === void 0) return;
|
|
1023
|
+
throw unsupported(`relation "${input.modelName}.${input.fieldName}" targets model "${input.targetModel}" in contract space "${input.space}", which contract print cannot write yet.`, "The printer writes relations between models of this contract only.", KEEP_SOURCE, {
|
|
1024
|
+
model: input.modelName,
|
|
1025
|
+
field: input.fieldName,
|
|
1026
|
+
space: input.space
|
|
1027
|
+
});
|
|
1028
|
+
}
|
|
1029
|
+
function refuseManyToManyWithoutJunctionRelation(modelName, fieldName) {
|
|
1030
|
+
throw unsupported(`many-to-many relation "${modelName}.${fieldName}" goes through a table whose model has no relation back to "${modelName}", so it cannot be written in Prisma 8 PSL.`, "PSL writes a many-to-many list field through the relations of the junction model, one to each side.", "Declare a model for the junction table with a relation to each side, or keep authoring this contract in its current source.", {
|
|
1031
|
+
model: modelName,
|
|
1032
|
+
field: fieldName
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
function refuseBackRelationWithoutOwningRelation(input) {
|
|
1036
|
+
throw unsupported(`relation "${input.modelName}.${input.fieldName}" has no foreign key of its own, and model "${input.targetModel}" has no relation back to "${input.modelName}" over the same columns, so it cannot be written in Prisma 8 PSL.`, "The PSL source reads a relation field without `fields:` and `references:` only as the other side of a relation field that has them.", `Declare the relation on "${input.targetModel}" that holds the foreign key, or keep authoring this contract in its current source.`, {
|
|
1037
|
+
model: input.modelName,
|
|
1038
|
+
field: input.fieldName
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
function refuseRelationWithoutJoin(modelName, fieldName) {
|
|
1042
|
+
throw unsupported(`relation "${modelName}.${fieldName}" names no fields to join on, which cannot be written in Prisma 8 PSL.`, "The PSL source reads every relation as a join between fields of the two models; a relation with no `on` part has no PSL form.", KEEP_SOURCE, {
|
|
1043
|
+
model: modelName,
|
|
1044
|
+
field: fieldName
|
|
1045
|
+
});
|
|
1046
|
+
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Refuses a namespace whose value sets differ from the ones the PSL source derives from the enum
|
|
1049
|
+
* and `native_enum` blocks the printer writes for it.
|
|
1050
|
+
*/
|
|
1051
|
+
function refuseUnderivedValueSets(input) {
|
|
1052
|
+
const { namespaceId } = input;
|
|
1053
|
+
for (const [name, values] of input.actual) {
|
|
1054
|
+
const derived = input.derived.get(name);
|
|
1055
|
+
if (derived !== void 0 && sameValues$1(derived, values)) continue;
|
|
1056
|
+
throw unsupported(`value set "${name}" in namespace "${namespaceId}" is not the value set of an enum or native enum of that name holding exactly its values, so it cannot be written in Prisma 8 PSL.`, "The PSL source derives each value set from an `enum` or `native_enum` block, named after the block and holding its members.", KEEP_SOURCE, {
|
|
1057
|
+
namespaceId,
|
|
1058
|
+
name
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
for (const name of input.derived.keys()) {
|
|
1062
|
+
if (input.actual.has(name)) continue;
|
|
1063
|
+
throw unsupported(`enum "${name}" in namespace "${namespaceId}" has no value set holding its members, which cannot be written in Prisma 8 PSL.`, "The PSL source derives a value set from every enum, so the file would read back with a value set this contract does not have.", KEEP_SOURCE, {
|
|
1064
|
+
namespaceId,
|
|
1065
|
+
name
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
function refuseEnumAndNativeEnumSharingName(namespaceId, name) {
|
|
1070
|
+
throw unsupported(`enum "${name}" and a native enum written under the same name both derive the value set "${name}" in namespace "${namespaceId}", which cannot be written in Prisma 8 PSL.`, "The PSL source refuses one name declared both as an enum and as a native enum.", KEEP_SOURCE, {
|
|
1071
|
+
namespaceId,
|
|
1072
|
+
name
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
function refuseNativeEnumWithoutValueSet(namespaceId, nativeEnum) {
|
|
1076
|
+
throw unsupported(`native enum "${nativeEnum.typeName}" in namespace "${namespaceId}" has no value set holding its members, which cannot be written in Prisma 8 PSL.`, "The PSL source derives a value set from every `native_enum` block, named after the block and holding its members, so the file would read back with a value set this contract does not have.", KEEP_SOURCE, {
|
|
1077
|
+
namespaceId,
|
|
1078
|
+
typeName: nativeEnum.typeName
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
function refuseNativeEnumControl(namespaceId, nativeEnum) {
|
|
1082
|
+
if (nativeEnum.control === void 0) return;
|
|
1083
|
+
throw unsupported(`native enum "${nativeEnum.typeName}" in namespace "${namespaceId}" carries its own control policy "${nativeEnum.control}", which cannot be written in Prisma 8 PSL.`, "A `native_enum` block has no control attribute.", "Drop the policy from the enum, or keep authoring this contract in its current source.", {
|
|
1084
|
+
namespaceId,
|
|
1085
|
+
typeName: nativeEnum.typeName,
|
|
1086
|
+
control: nativeEnum.control
|
|
1087
|
+
});
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* Refuses a storage or domain namespace the PSL source would not create again: one holding nothing
|
|
1091
|
+
* the printer writes. The PSL source creates the default namespace in both planes, a storage
|
|
1092
|
+
* namespace for every namespace block it writes into, and a domain namespace for each namespace
|
|
1093
|
+
* with models.
|
|
1094
|
+
*/
|
|
1095
|
+
function refuseUnwrittenNamespaces(input) {
|
|
1096
|
+
const { contract } = input;
|
|
1097
|
+
const storageNamespaces = /* @__PURE__ */ new Set([DEFAULT_NAMESPACE_ID, ...input.writtenStorageNamespaces]);
|
|
1098
|
+
const defaultDomain = contract.domain.namespaces[DEFAULT_NAMESPACE_ID];
|
|
1099
|
+
const domainNamespaces = new Set(input.models.map((entry) => entry.namespaceId));
|
|
1100
|
+
if (domainNamespaces.size === 0 || Object.keys(defaultDomain?.valueObjects ?? {}).length > 0 || Object.keys(defaultDomain?.enum ?? {}).length > 0) domainNamespaces.add(DEFAULT_NAMESPACE_ID);
|
|
1101
|
+
const planes = [{
|
|
1102
|
+
plane: "storage",
|
|
1103
|
+
expected: storageNamespaces,
|
|
1104
|
+
actual: Object.keys(contract.storage.namespaces)
|
|
1105
|
+
}, {
|
|
1106
|
+
plane: "domain",
|
|
1107
|
+
expected: domainNamespaces,
|
|
1108
|
+
actual: Object.keys(contract.domain.namespaces)
|
|
1109
|
+
}];
|
|
1110
|
+
for (const { plane, expected, actual } of planes) {
|
|
1111
|
+
for (const namespaceId of actual) {
|
|
1112
|
+
if (expected.has(namespaceId)) continue;
|
|
1113
|
+
throw unsupported(`${plane} namespace "${namespaceId}" holds nothing Prisma 8 PSL writes, so it would not read back.`, "The PSL source creates a namespace only for what is written in it.", "Remove the empty namespace, or keep authoring this contract in its current source.", {
|
|
1114
|
+
plane,
|
|
1115
|
+
namespaceId
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
for (const namespaceId of expected) {
|
|
1119
|
+
if (actual.includes(namespaceId)) continue;
|
|
1120
|
+
throw unsupported(`the contract has no ${plane} namespace "${namespaceId}", which the PSL source would create.`, "The PSL source always creates the default namespace, and a namespace for everything it writes.", KEEP_SOURCE, {
|
|
1121
|
+
plane,
|
|
1122
|
+
namespaceId
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* Refuses a namespace named `unbound` that is not the late-binding namespace: PSL writes the
|
|
1129
|
+
* late-binding namespace as `namespace unbound`, so a block of that name reads back as it.
|
|
1130
|
+
*/
|
|
1131
|
+
function refuseNamespaceNamedUnbound(namespaceId) {
|
|
1132
|
+
if (namespaceId !== UNBOUND_PSL_NAMESPACE_NAME) return;
|
|
1133
|
+
throw unsupported(`namespace "${namespaceId}" cannot be written in Prisma 8 PSL, because \`namespace ${UNBOUND_PSL_NAMESPACE_NAME}\` is how PSL writes the late-binding namespace.`, `The PSL source reads \`namespace ${UNBOUND_PSL_NAMESPACE_NAME}\` as the late-binding namespace "${UNBOUND_NAMESPACE_ID}", so everything in this namespace would move there.`, "Rename the namespace, or keep authoring this contract in its current source.", { namespaceId });
|
|
1134
|
+
}
|
|
1135
|
+
/** Refuses top-level `meta` entries: the PSL source reads back an empty `meta`. */
|
|
1136
|
+
function refuseContractMeta(contract) {
|
|
1137
|
+
const keys = Object.keys(contract.meta);
|
|
1138
|
+
if (keys.length === 0) return;
|
|
1139
|
+
throw unsupported(`the contract carries meta entries (${keys.join(", ")}), which cannot be written in Prisma 8 PSL.`, "The PSL source writes no top-level meta, so the file would read back with an empty meta.", KEEP_SOURCE, { keys });
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
1142
|
+
* Refuses roots that differ from the ones the PSL source derives: one per model that is not a
|
|
1143
|
+
* variant, keyed by its table name, or by `<namespace>.<table>` when two such models share a table
|
|
1144
|
+
* name.
|
|
1145
|
+
*/
|
|
1146
|
+
function refuseUnderivedRoots(contract, models, variants) {
|
|
1147
|
+
const tableEntries = models.filter((entry) => variants.get(entry)?.singleTable !== true);
|
|
1148
|
+
const tableNameCounts = /* @__PURE__ */ new Map();
|
|
1149
|
+
for (const entry of tableEntries) tableNameCounts.set(entry.tableName, (tableNameCounts.get(entry.tableName) ?? 0) + 1);
|
|
1150
|
+
const derived = /* @__PURE__ */ new Map();
|
|
1151
|
+
for (const entry of tableEntries) {
|
|
1152
|
+
if (variants.get(entry) !== void 0) continue;
|
|
1153
|
+
const key = (tableNameCounts.get(entry.tableName) ?? 0) > 1 ? `${entry.namespaceId}.${entry.tableName}` : entry.tableName;
|
|
1154
|
+
derived.set(key, entry);
|
|
1155
|
+
}
|
|
1156
|
+
const refuse = (root) => unsupported(`root "${root}" is not a root the PSL source derives, so the contract's roots cannot be written in Prisma 8 PSL.`, "The PSL source derives one root per model that is not a variant, keyed by its table name.", KEEP_SOURCE, { root });
|
|
1157
|
+
for (const [root, reference] of Object.entries(contract.roots)) {
|
|
1158
|
+
const entry = derived.get(root);
|
|
1159
|
+
if (entry === void 0 || reference.space !== void 0 || reference.namespace !== entry.namespaceId || reference.model !== entry.name) throw refuse(root);
|
|
1160
|
+
}
|
|
1161
|
+
for (const root of derived.keys()) if (!Object.hasOwn(contract.roots, root)) throw refuse(root);
|
|
1162
|
+
}
|
|
1163
|
+
function refuseRlsWithoutModel(namespaceId, tableName) {
|
|
1164
|
+
throw unsupported(`table "${namespaceId}"."${tableName}" has row-level security enabled but no model, so it cannot be written in Prisma 8 PSL.`, "Row-level security is written as `@@rls` on the model stored in the table.", "Declare a model for the table, or keep authoring this contract in its current source.", {
|
|
1165
|
+
namespaceId,
|
|
1166
|
+
table: tableName
|
|
1167
|
+
});
|
|
1168
|
+
}
|
|
1169
|
+
function unwritablePolicy(policy, why, fix) {
|
|
1170
|
+
return unsupported(`policy "${policy.name}" on "${policy.namespaceId}"."${policy.tableName}" cannot be written in Prisma 8 PSL.`, why, fix, {
|
|
1171
|
+
namespaceId: policy.namespaceId,
|
|
1172
|
+
table: policy.tableName,
|
|
1173
|
+
name: policy.name
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
function refusePolicyWithoutModel(policy) {
|
|
1177
|
+
throw unwritablePolicy(policy, "A policy block names its table through the model stored there, and no model is stored in this table.", "Declare a model for the table, or keep authoring this contract in its current source.");
|
|
1178
|
+
}
|
|
1179
|
+
function refusePolicyWithoutRls(policy) {
|
|
1180
|
+
throw unwritablePolicy(policy, "The PSL source reads a policy only on a model that declares `@@rls`, and this table does not have row-level security enabled.", "Enable row-level security on the table, or keep authoring this contract in its current source.");
|
|
1181
|
+
}
|
|
1182
|
+
function refusePolicyNameNotDerived(policy) {
|
|
1183
|
+
throw unwritablePolicy(policy, "The PSL source names a wire-named policy by its block name and the hash of its content, and this name is not that.", KEEP_SOURCE);
|
|
1184
|
+
}
|
|
1185
|
+
/** Refuses a role outside the unbound namespace: the PSL source reads a `role` block only there. */
|
|
1186
|
+
function refuseRoleOutsideUnbound(namespaceId, name) {
|
|
1187
|
+
if (namespaceId === UNBOUND_NAMESPACE_ID) return;
|
|
1188
|
+
throw unsupported(`role "${name}" is declared in namespace "${namespaceId}", and Prisma 8 PSL declares a role only in the unbound namespace.`, "The PSL source reads a `role` block only inside `namespace unbound`, because roles belong to the whole database.", "Declare the role in the unbound namespace, or keep authoring this contract in its current source.", {
|
|
1189
|
+
namespaceId,
|
|
1190
|
+
name
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
const FILED_UNDER = {
|
|
1194
|
+
rls: "The PSL source files the row-level security setting written as `@@rls` under the name of the table.",
|
|
1195
|
+
role: "The PSL source files a role under the name its block is written with."
|
|
1196
|
+
};
|
|
1197
|
+
/** Refuses a row-level security setting or role filed under a key the PSL source would not use. */
|
|
1198
|
+
function refuseEntryFiledUnderAnotherName(input) {
|
|
1199
|
+
if (input.name === input.readsBackAs) return;
|
|
1200
|
+
throw unsupported(`namespace "${input.namespaceId}" has a "${input.kind}" entry "${input.name}" that would read back as "${input.readsBackAs}", so it cannot be written in Prisma 8 PSL.`, FILED_UNDER[input.kind], KEEP_SOURCE, {
|
|
1201
|
+
namespaceId: input.namespaceId,
|
|
1202
|
+
kind: input.kind,
|
|
1203
|
+
name: input.name
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
/** Refuses an entry that records a namespace other than the one it is stored in. */
|
|
1207
|
+
function refuseEntryInOtherNamespace(input) {
|
|
1208
|
+
if (input.recordedNamespaceId === input.namespaceId) return;
|
|
1209
|
+
throw unsupported(`the "${input.kind}" entry "${input.name}" is stored in namespace "${input.namespaceId}" but records namespace "${input.recordedNamespaceId}", so it cannot be written in Prisma 8 PSL.`, "The PSL source records the namespace a block is written in, so the entry would read back with the namespace it is stored in.", "The contract source produced an entry that disagrees with its namespace. Fix the entry if the source is a TypeScript contract; otherwise report the bug to the source that produced it.", {
|
|
1210
|
+
namespaceId: input.namespaceId,
|
|
1211
|
+
kind: input.kind,
|
|
1212
|
+
name: input.name
|
|
1213
|
+
});
|
|
1214
|
+
}
|
|
1215
|
+
function refuseNameThePslSourceLoses(kind, name) {
|
|
1216
|
+
if (name !== NAME_THE_PSL_SOURCE_LOSES) return;
|
|
1217
|
+
throw unsupported(`${kind} "${name}" cannot be written in Prisma 8 PSL, because the PSL source loses this name when it reads it.`, "The PSL source keeps names as keys of plain objects, where this name sets the prototype instead of adding a key.", "Rename it, or keep authoring this contract in its current source.", {
|
|
1218
|
+
kind,
|
|
1219
|
+
name
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
/**
|
|
1223
|
+
* Refuses a table or column named `__proto__`, which the printer would write inside `@@map` or
|
|
1224
|
+
* `@map` and the PSL source loses when it reads it.
|
|
1225
|
+
*/
|
|
1226
|
+
function refuseUnwritableMappedName(kind, name) {
|
|
1227
|
+
refuseNameThePslSourceLoses(kind, name);
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Refuses a name the printer writes where PSL reads an identifier: a namespace, model, field, value
|
|
1231
|
+
* object, enum, enum member, native enum, named type, policy, role or index option key.
|
|
1232
|
+
*/
|
|
1233
|
+
function refuseUnwritableName(kind, name) {
|
|
1234
|
+
refuseNameThePslSourceLoses(kind, name);
|
|
1235
|
+
if (isPslIdentifier(name)) return;
|
|
1236
|
+
throw unsupported(`${kind} "${name}" is not a PSL identifier, so it cannot be written in Prisma 8 PSL.`, "PSL writes this name as an identifier: a letter or underscore, then letters, ASCII digits, underscores or hyphens, other than the number words `NaN` and `Infinity`.", "Rename it to an identifier, or keep authoring this contract in its current source.", {
|
|
1237
|
+
kind,
|
|
1238
|
+
name
|
|
1239
|
+
});
|
|
1240
|
+
}
|
|
1241
|
+
/** The storage entry kinds the printer writes; any other kind is refused, whichever component defines it. */
|
|
1242
|
+
const PRINTED_ENTRY_KINDS = /* @__PURE__ */ new Set([
|
|
1243
|
+
"table",
|
|
1244
|
+
"valueSet",
|
|
1245
|
+
"native_enum",
|
|
1246
|
+
"rls",
|
|
1247
|
+
"policy",
|
|
1248
|
+
"role"
|
|
1249
|
+
]);
|
|
1250
|
+
function refuseUnprintedEntryKinds(namespaceId, entries) {
|
|
1251
|
+
for (const [kind, entities] of Object.entries(entries)) {
|
|
1252
|
+
if (PRINTED_ENTRY_KINDS.has(kind)) continue;
|
|
1253
|
+
const names = Object.keys(entities ?? {});
|
|
1254
|
+
if (names.length === 0) continue;
|
|
1255
|
+
throw unsupported(`namespace "${namespaceId}" declares ${names.length} "${kind}" ${names.length === 1 ? "entity" : "entities"} (${names.join(", ")}), which the Postgres printer cannot write.`, "The printer writes tables, value sets, native enums, row-level security settings, policies and roles, and no other entity kind.", KEEP_SOURCE, {
|
|
1256
|
+
namespaceId,
|
|
1257
|
+
kind,
|
|
1258
|
+
names
|
|
1259
|
+
});
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
/** The name of the column's data type without parameters. */
|
|
1263
|
+
function baseTypeName(column, dataTypeLookup, coordinate) {
|
|
1264
|
+
const dataType = dataTypeLookup.get(column.dataType);
|
|
1265
|
+
if (dataType === void 0 || !isSqlDataType(dataType)) return refuseColumnWithoutPslType(column, coordinate);
|
|
1266
|
+
return unquotedSqlBaseName(dataType, dataTypeParams(dataType, column.typeParams));
|
|
1267
|
+
}
|
|
1268
|
+
/** A type argument as PSL writes it: a number as written, a string between quotes. */
|
|
1269
|
+
function typeArgumentText(value, coordinate) {
|
|
1270
|
+
return pslTypeArgumentText(value) ?? refuseUnwritableTypeArgument(String(value), coordinate);
|
|
1271
|
+
}
|
|
1272
|
+
function typeCall(path, args) {
|
|
1273
|
+
const name = path.join(".");
|
|
1274
|
+
const isNamespaced = path.length > 1;
|
|
1275
|
+
if (args.length === 0 && !isNamespaced) return {
|
|
1276
|
+
kind: "dataType",
|
|
1277
|
+
typeName: name
|
|
1278
|
+
};
|
|
1279
|
+
return {
|
|
1280
|
+
kind: "dataType",
|
|
1281
|
+
typeName: name,
|
|
1282
|
+
typeConstructor: {
|
|
1283
|
+
kind: "typeConstructor",
|
|
1284
|
+
path,
|
|
1285
|
+
args: args.map(positionalArg),
|
|
1286
|
+
span: SYNTHETIC_SPAN
|
|
1287
|
+
}
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
/**
|
|
1291
|
+
* The call to the constructor marked `inferred` for the column's data type, the one `contract
|
|
1292
|
+
* infer` writes, when it produces exactly the column's codec and type parameters.
|
|
1293
|
+
*/
|
|
1294
|
+
function inferredConstructorCall(column, inferredConstructors) {
|
|
1295
|
+
const marked = inferredConstructors.get(column.dataType);
|
|
1296
|
+
const args = marked && authoringTypeConstructorArguments(marked.descriptor, column);
|
|
1297
|
+
return marked && args && {
|
|
1298
|
+
path: marked.path,
|
|
1299
|
+
args
|
|
1300
|
+
};
|
|
1301
|
+
}
|
|
1302
|
+
/**
|
|
1303
|
+
* The PSL type position for a storage column: a call to a type constructor the configured stack
|
|
1304
|
+
* contributes that produces exactly the column's codec, native type and type parameters. The
|
|
1305
|
+
* constructor `contract infer` writes for the column's data type comes first; otherwise
|
|
1306
|
+
* the first one in the stack that produces them, such as `DateTime` for a `timestamptz` column read
|
|
1307
|
+
* as a `Temporal.Instant`, or `pgvector.Vector(3)`. An enum-typed column takes the
|
|
1308
|
+
* `pg.enum(<Block>)` constructor, named after the value set the column points at; a column typed by
|
|
1309
|
+
* a domain enum takes that enum's name. A column no PSL type reads back is refused.
|
|
1310
|
+
*/
|
|
1311
|
+
function buildColumnType(input) {
|
|
1312
|
+
const { column, inferredConstructors, authoringTypes, enumBlockNames, coordinate } = input;
|
|
1313
|
+
const baseName = baseTypeName(column, input.dataTypeLookup, coordinate);
|
|
1314
|
+
const enumBlockName = column.valueSet?.entityName ?? enumBlockNames.get(baseName);
|
|
1315
|
+
if (column.codecId === "pg/enum@1" && enumBlockName !== void 0) return {
|
|
1316
|
+
kind: "enum",
|
|
1317
|
+
typeName: enumBlockName,
|
|
1318
|
+
typeConstructor: {
|
|
1319
|
+
kind: "typeConstructor",
|
|
1320
|
+
path: ["pg", "enum"],
|
|
1321
|
+
args: [positionalArg(column.valueSet !== void 0 && column.valueSet.namespaceId !== input.namespaceId ? `${column.valueSet.namespaceId}.${enumBlockName}` : enumBlockName)],
|
|
1322
|
+
span: SYNTHETIC_SPAN
|
|
1323
|
+
}
|
|
1324
|
+
};
|
|
1325
|
+
const domainEnumName = column.valueSet?.entityName;
|
|
1326
|
+
if (domainEnumName !== void 0) return {
|
|
1327
|
+
kind: "enum",
|
|
1328
|
+
typeName: domainEnumName
|
|
1329
|
+
};
|
|
1330
|
+
const call = inferredConstructorCall(column, inferredConstructors) ?? findAuthoringTypeConstructorCall(authoringTypes, column);
|
|
1331
|
+
if (call !== void 0) return typeCall(call.path, call.args.map((value) => typeArgumentText(value, coordinate)));
|
|
1332
|
+
refuseColumnWithoutPslType(column, coordinate);
|
|
1333
|
+
}
|
|
1334
|
+
/**
|
|
1335
|
+
* The data type a value-object member's codec represents, after checking the member's type
|
|
1336
|
+
* parameters against it. A member has no column of its own.
|
|
1337
|
+
*/
|
|
1338
|
+
function dataTypeOfMember(type, coordinate, context) {
|
|
1339
|
+
const { codecId } = type;
|
|
1340
|
+
const descriptor = context.codecLookup.descriptorFor(codecId);
|
|
1341
|
+
if (descriptor === void 0) refuseMemberCodecWithoutNativeType(codecId, coordinate);
|
|
1342
|
+
const dataType = context.dataTypes.lookup.get(descriptor.dataType);
|
|
1343
|
+
if (dataType === void 0 || !isSqlDataType(dataType)) refuseMemberCodecWithoutNativeType(codecId, coordinate);
|
|
1344
|
+
const typeParams = resolvedTypeParams(type, void 0);
|
|
1345
|
+
if (typeParams === void 0) {
|
|
1346
|
+
if (requiredParamKeys(dataType).length > 0) refuseMemberCodecNeedingTypeParameters(codecId, coordinate);
|
|
1347
|
+
return dataType.id;
|
|
1348
|
+
}
|
|
1349
|
+
validateCodecTypeParams(descriptor, {
|
|
1350
|
+
codecId,
|
|
1351
|
+
typeParams: blindCast(typeParams)
|
|
1352
|
+
});
|
|
1353
|
+
return dataType.id;
|
|
1354
|
+
}
|
|
1355
|
+
/** The PSL type position of a value-object member: a value object or an enum by name, or a scalar as a column would print. */
|
|
1356
|
+
function buildMemberType(input) {
|
|
1357
|
+
const { field, coordinate } = input;
|
|
1358
|
+
refuseUnwritableFieldShape(field, coordinate);
|
|
1359
|
+
const { type } = field;
|
|
1360
|
+
if (type.kind === "valueObject") return {
|
|
1361
|
+
kind: "valueObject",
|
|
1362
|
+
typeName: type.name
|
|
1363
|
+
};
|
|
1364
|
+
refuseUnderivedMemberValueSet({
|
|
1365
|
+
field,
|
|
1366
|
+
type,
|
|
1367
|
+
coordinate,
|
|
1368
|
+
domainEnums: input.domainEnums
|
|
1369
|
+
});
|
|
1370
|
+
if (field.valueSet !== void 0) return {
|
|
1371
|
+
kind: "enum",
|
|
1372
|
+
typeName: field.valueSet.entityName
|
|
1373
|
+
};
|
|
1374
|
+
return buildColumnType({
|
|
1375
|
+
column: new StorageColumn({
|
|
1376
|
+
dataType: dataTypeOfMember(type, coordinate, input.context),
|
|
1377
|
+
codecId: type.codecId,
|
|
1378
|
+
nullable: field.nullable,
|
|
1379
|
+
...ifDefined("many", field.many),
|
|
1380
|
+
...ifDefined("typeParams", type.typeParams)
|
|
1381
|
+
}),
|
|
1382
|
+
inferredConstructors: input.inferredConstructors,
|
|
1383
|
+
authoringTypes: input.context.authoringContributions.type,
|
|
1384
|
+
dataTypeLookup: input.context.dataTypes.lookup,
|
|
1385
|
+
enumBlockNames: input.enumBlockNames,
|
|
1386
|
+
coordinate
|
|
1387
|
+
});
|
|
1388
|
+
}
|
|
1389
|
+
/** The `type` blocks of one namespace, one per value object the domain declares there. */
|
|
1390
|
+
function buildCompositeTypes(input) {
|
|
1391
|
+
refuseValueObjectsOutsideDefaultNamespace(input.contract, input.namespaceId);
|
|
1392
|
+
const valueObjects = input.contract.domain.namespaces[input.namespaceId]?.valueObjects ?? {};
|
|
1393
|
+
return Object.entries(valueObjects).map(([name, valueObject]) => {
|
|
1394
|
+
refuseUnwritableName("value object", name);
|
|
1395
|
+
return {
|
|
1396
|
+
kind: "compositeType",
|
|
1397
|
+
name,
|
|
1398
|
+
fields: Object.entries(valueObject.fields).map(([fieldName, field]) => {
|
|
1399
|
+
refuseUnwritableName("field", fieldName);
|
|
1400
|
+
const { typeName, typeConstructor } = buildMemberType({
|
|
1401
|
+
field,
|
|
1402
|
+
coordinate: `"${input.namespaceId}".${name}.${fieldName}`,
|
|
1403
|
+
inferredConstructors: input.inferredConstructors,
|
|
1404
|
+
context: input.context,
|
|
1405
|
+
enumBlockNames: input.enumBlockNames,
|
|
1406
|
+
domainEnums: input.domainEnums
|
|
1407
|
+
});
|
|
1408
|
+
return {
|
|
1409
|
+
kind: "field",
|
|
1410
|
+
name: fieldName,
|
|
1411
|
+
typeName,
|
|
1412
|
+
...ifDefined("typeConstructor", typeConstructor),
|
|
1413
|
+
optional: field.nullable,
|
|
1414
|
+
list: !!field.many,
|
|
1415
|
+
elementOptional: !!field.many && field.many.elementNullable,
|
|
1416
|
+
attributes: [],
|
|
1417
|
+
span: SYNTHETIC_SPAN
|
|
1418
|
+
};
|
|
1419
|
+
}),
|
|
1420
|
+
attributes: [],
|
|
1421
|
+
span: SYNTHETIC_SPAN
|
|
1422
|
+
};
|
|
1423
|
+
});
|
|
1424
|
+
}
|
|
1425
|
+
/** The document's `types { … }` block, one declaration per named storage type. */
|
|
1426
|
+
function buildTypesBlock(contract, inferredConstructors, context) {
|
|
1427
|
+
const declarations = [];
|
|
1428
|
+
for (const [name, instance] of Object.entries(contract.storage.types ?? {})) {
|
|
1429
|
+
refuseUnwritableName("named type", name);
|
|
1430
|
+
const { typeName, typeConstructor } = buildColumnType({
|
|
1431
|
+
column: new StorageColumn({
|
|
1432
|
+
dataType: instance.dataType,
|
|
1433
|
+
codecId: instance.codecId,
|
|
1434
|
+
nullable: false,
|
|
1435
|
+
...ifDefined("typeParams", instance.typeParams)
|
|
1436
|
+
}),
|
|
1437
|
+
inferredConstructors,
|
|
1438
|
+
authoringTypes: context.authoringContributions.type,
|
|
1439
|
+
dataTypeLookup: context.dataTypes.lookup,
|
|
1440
|
+
enumBlockNames: /* @__PURE__ */ new Map(),
|
|
1441
|
+
coordinate: `types.${name}`
|
|
1442
|
+
});
|
|
1443
|
+
declarations.push({
|
|
1444
|
+
kind: "namedType",
|
|
1445
|
+
name,
|
|
1446
|
+
...typeConstructor === void 0 ? { baseType: typeName } : { typeConstructor },
|
|
1447
|
+
attributes: [],
|
|
1448
|
+
span: SYNTHETIC_SPAN
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
return declarations.length === 0 ? void 0 : {
|
|
1452
|
+
kind: "types",
|
|
1453
|
+
declarations,
|
|
1454
|
+
span: SYNTHETIC_SPAN
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
/**
|
|
1458
|
+
* One `enum <name> { … }` block per domain enum, each member written as
|
|
1459
|
+
* `Name = <value>` under `@@type`. The PSL source reads a member value as JSON,
|
|
1460
|
+
* so the value is written as JSON text.
|
|
1461
|
+
*/
|
|
1462
|
+
function buildDomainEnumBlocks(enums) {
|
|
1463
|
+
return Object.entries(enums).map(([name, domainEnum]) => {
|
|
1464
|
+
refuseUnwritableName("enum", name);
|
|
1465
|
+
return {
|
|
1466
|
+
kind: "enum",
|
|
1467
|
+
keyword: "enum",
|
|
1468
|
+
name,
|
|
1469
|
+
parameters: Object.fromEntries(domainEnum.members.map((member) => {
|
|
1470
|
+
refuseUnwritableName("enum member", member.name);
|
|
1471
|
+
return [member.name, {
|
|
1472
|
+
expression: JSON.stringify(member.value),
|
|
1473
|
+
span: SYNTHETIC_SPAN
|
|
1474
|
+
}];
|
|
1475
|
+
})),
|
|
1476
|
+
blockAttributes: [{
|
|
1477
|
+
name: "type",
|
|
1478
|
+
args: [{
|
|
1479
|
+
kind: "positional",
|
|
1480
|
+
value: `"${escapePslString(domainEnum.codecId)}"`,
|
|
1481
|
+
span: SYNTHETIC_SPAN
|
|
1482
|
+
}],
|
|
1483
|
+
span: SYNTHETIC_SPAN
|
|
1484
|
+
}],
|
|
1485
|
+
span: SYNTHETIC_SPAN
|
|
1486
|
+
};
|
|
1487
|
+
});
|
|
1488
|
+
}
|
|
1489
|
+
function sameValues(left, right) {
|
|
1490
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* Builds one `native_enum` block per enum type a namespace declares.
|
|
1494
|
+
*
|
|
1495
|
+
* A contract keys a native enum by its type name and keys the value set it
|
|
1496
|
+
* derives by the name the schema gave the enum, and the PSL source derives
|
|
1497
|
+
* that value set from the block, named after the block. So the block is named
|
|
1498
|
+
* after the enum's value set: the value set a column typed by the enum names;
|
|
1499
|
+
* else, for an enum no column refers to, the unclaimed value set with the
|
|
1500
|
+
* enum's own name that holds exactly its members, or else the first unclaimed
|
|
1501
|
+
* one that does. An enum with no such value set is refused. `@@map` carries
|
|
1502
|
+
* the type name whenever it differs from the block name.
|
|
1503
|
+
*/
|
|
1504
|
+
function buildNativeEnumBlocksForNamespace(input) {
|
|
1505
|
+
const valueSetNamesByTypeName = /* @__PURE__ */ new Map();
|
|
1506
|
+
for (const column of input.columns) {
|
|
1507
|
+
const valueSetName = column.valueSet?.entityName;
|
|
1508
|
+
const typeName = column.typeParams?.["typeName"];
|
|
1509
|
+
if (valueSetName === void 0 || typeof typeName !== "string") continue;
|
|
1510
|
+
valueSetNamesByTypeName.set(typeName, valueSetName);
|
|
1511
|
+
}
|
|
1512
|
+
const claimed = new Set(valueSetNamesByTypeName.values());
|
|
1513
|
+
const unreferenced = [];
|
|
1514
|
+
const nameByEntry = /* @__PURE__ */ new Map();
|
|
1515
|
+
for (const [entryName, nativeEnum] of input.nativeEnums) {
|
|
1516
|
+
refuseNativeEnumControl(input.namespaceId, nativeEnum);
|
|
1517
|
+
const { typeName } = nativeEnum;
|
|
1518
|
+
const fromColumn = valueSetNamesByTypeName.get(typeName) ?? valueSetNamesByTypeName.get(`${input.namespaceId}.${typeName}`);
|
|
1519
|
+
if (fromColumn === void 0) {
|
|
1520
|
+
unreferenced.push({
|
|
1521
|
+
entryName,
|
|
1522
|
+
nativeEnum
|
|
1523
|
+
});
|
|
1524
|
+
continue;
|
|
1525
|
+
}
|
|
1526
|
+
nameByEntry.set(entryName, fromColumn);
|
|
1527
|
+
}
|
|
1528
|
+
for (const { entryName, nativeEnum } of unreferenced) {
|
|
1529
|
+
const candidates = [...input.valueSets].filter(([name, values]) => !claimed.has(name) && sameValues(values, nativeEnum.members)).map(([name]) => name);
|
|
1530
|
+
const chosen = candidates.find((name) => name === entryName) ?? candidates[0];
|
|
1531
|
+
if (chosen === void 0) refuseNativeEnumWithoutValueSet(input.namespaceId, nativeEnum);
|
|
1532
|
+
claimed.add(chosen);
|
|
1533
|
+
nameByEntry.set(entryName, chosen);
|
|
1534
|
+
}
|
|
1535
|
+
const blocks = [];
|
|
1536
|
+
const blockNamesByTypeName = /* @__PURE__ */ new Map();
|
|
1537
|
+
const derivedValueSets = /* @__PURE__ */ new Map();
|
|
1538
|
+
for (const [entryName, nativeEnum] of input.nativeEnums) {
|
|
1539
|
+
const { typeName } = nativeEnum;
|
|
1540
|
+
const blockName = nameByEntry.get(entryName) ?? typeName;
|
|
1541
|
+
refuseUnwritableName("native enum", blockName);
|
|
1542
|
+
blocks.push(buildNativeEnumBlock(blockName, typeName, nativeEnum.members));
|
|
1543
|
+
blockNamesByTypeName.set(typeName, blockName);
|
|
1544
|
+
blockNamesByTypeName.set(`${input.namespaceId}.${typeName}`, blockName);
|
|
1545
|
+
derivedValueSets.set(blockName, nativeEnum.members);
|
|
1546
|
+
}
|
|
1547
|
+
return {
|
|
1548
|
+
blocks,
|
|
1549
|
+
blockNamesByTypeName,
|
|
1550
|
+
derivedValueSets
|
|
1551
|
+
};
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* The checks the PSL source derives itself for a table, keyed by name, so
|
|
1555
|
+
* they are not also written as `@@check`. A table that is not managed derives
|
|
1556
|
+
* none. A managed one derives a membership check for each column typed by a
|
|
1557
|
+
* domain enum and an element-not-null check for each list column whose
|
|
1558
|
+
* elements are not nullable.
|
|
1559
|
+
*/
|
|
1560
|
+
function derivedChecks(input) {
|
|
1561
|
+
const checks = /* @__PURE__ */ new Map();
|
|
1562
|
+
if (!input.managed) return checks;
|
|
1563
|
+
for (const [columnName, column] of Object.entries(input.table.columns)) {
|
|
1564
|
+
const enumValues = column.codecId === "pg/enum@1" || column.valueSet === void 0 ? void 0 : input.domainEnumValues.get(column.valueSet.entityName);
|
|
1565
|
+
const memberValues = enumValues?.filter((value) => typeof value === "string" || typeof value === "number");
|
|
1566
|
+
for (const candidate of postgresRenderCheckExpressions({
|
|
1567
|
+
tableName: input.tableName,
|
|
1568
|
+
columnName,
|
|
1569
|
+
many: column.many,
|
|
1570
|
+
memberValues: memberValues?.length === enumValues?.length ? memberValues : void 0
|
|
1571
|
+
})) {
|
|
1572
|
+
const prefix = composeCheckWirePrefix(input.tableName, columnName, candidate.kind);
|
|
1573
|
+
checks.set(formatWireName(prefix, computeCheckContentHash(candidate.expression)), {
|
|
1574
|
+
prefix,
|
|
1575
|
+
expression: candidate.expression
|
|
1576
|
+
});
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
return checks;
|
|
1580
|
+
}
|
|
1581
|
+
/**
|
|
1582
|
+
* Whether a table object belongs to this model when several models share the
|
|
1583
|
+
* table: a single-table variant owns what lies within its own columns, and the
|
|
1584
|
+
* base owns the rest.
|
|
1585
|
+
*/
|
|
1586
|
+
function ownsTableObject(entry, variant, singleTableVariants, columns) {
|
|
1587
|
+
if (variant?.singleTable === true) return columns?.every((column) => entry.ownColumns.has(column)) === true;
|
|
1588
|
+
return !singleTableVariants.some((other) => columns?.every((column) => other.ownColumns.has(column)) === true);
|
|
1589
|
+
}
|
|
1590
|
+
/**
|
|
1591
|
+
* How a check or index is named in PSL: `name:` with its prefix when the name
|
|
1592
|
+
* is that prefix and the hash of its content, which the PSL source derives
|
|
1593
|
+
* again; `map:` when it has no prefix. A prefix whose name is anything else is
|
|
1594
|
+
* refused, because neither form reads back as it.
|
|
1595
|
+
*/
|
|
1596
|
+
function attributeNaming(input) {
|
|
1597
|
+
const { kind, entry, name, prefix } = input;
|
|
1598
|
+
if (prefix === void 0) return { kind: "exact" };
|
|
1599
|
+
if (formatWireName(prefix, input.contentHash()) === name) return {
|
|
1600
|
+
kind: "wire",
|
|
1601
|
+
prefix
|
|
1602
|
+
};
|
|
1603
|
+
refuseUnwritableObjectName({
|
|
1604
|
+
kind,
|
|
1605
|
+
entry,
|
|
1606
|
+
name,
|
|
1607
|
+
prefix
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
/**
|
|
1611
|
+
* The `@@` attributes of one model: its polymorphism, its keys, checks and indexes, its control
|
|
1612
|
+
* policy, `@@rls` and `@@map`. A table object several models share goes on the model that owns it.
|
|
1613
|
+
*/
|
|
1614
|
+
function buildModelAttributes(input) {
|
|
1615
|
+
const { entry, variant, singleTableVariants, derivedChecksByName } = input;
|
|
1616
|
+
const attributes = [];
|
|
1617
|
+
const fieldNameOf = (column) => entry.fieldNamesByColumn.get(column) ?? column;
|
|
1618
|
+
const owns = (columns) => ownsTableObject(entry, variant, singleTableVariants, columns);
|
|
1619
|
+
if (entry.model.discriminator !== void 0) attributes.push(buildAttribute("model", "discriminator", [positionalArg(entry.model.discriminator.field)]));
|
|
1620
|
+
if (variant !== void 0) attributes.push(buildAttribute("model", "base", [positionalArg(variant.base.namespaceId === entry.namespaceId ? variant.base.name : `${pslNamespaceName(variant.base.namespaceId)}.${variant.base.name}`), positionalArg(`"${escapePslString(variant.value)}"`)]));
|
|
1621
|
+
const primaryKeyColumns = variant === void 0 ? entry.table.primaryKey?.columns ?? [] : [];
|
|
1622
|
+
if (primaryKeyColumns.length > 1) attributes.push(buildModelConstraintAttribute("id", primaryKeyColumns.map(fieldNameOf), entry.table.primaryKey?.name));
|
|
1623
|
+
for (const unique of entry.table.uniques) {
|
|
1624
|
+
if (!owns(unique.columns)) continue;
|
|
1625
|
+
attributes.push(buildModelConstraintAttribute("unique", unique.columns.map(fieldNameOf), unique.name));
|
|
1626
|
+
}
|
|
1627
|
+
for (const check of entry.table.checks ?? []) {
|
|
1628
|
+
if (derivedChecksByName.has(check.name) || !owns(void 0)) continue;
|
|
1629
|
+
refuseSqlTextThatDoesNotReadBack({
|
|
1630
|
+
kind: "check",
|
|
1631
|
+
namespaceId: entry.namespaceId,
|
|
1632
|
+
table: entry.tableName,
|
|
1633
|
+
name: check.name,
|
|
1634
|
+
texts: [check.expression]
|
|
1635
|
+
});
|
|
1636
|
+
attributes.push(buildCheckAttribute(check, attributeNaming({
|
|
1637
|
+
kind: "check",
|
|
1638
|
+
entry,
|
|
1639
|
+
name: check.name,
|
|
1640
|
+
prefix: check.prefix,
|
|
1641
|
+
contentHash: () => computeCheckContentHash(check.expression)
|
|
1642
|
+
})));
|
|
1643
|
+
}
|
|
1644
|
+
for (const index of entry.table.indexes) {
|
|
1645
|
+
if (!owns(index.columns)) continue;
|
|
1646
|
+
const naming = attributeNaming({
|
|
1647
|
+
kind: "index",
|
|
1648
|
+
entry,
|
|
1649
|
+
name: index.name,
|
|
1650
|
+
prefix: index.prefix,
|
|
1651
|
+
contentHash: () => computeIndexContentHash(index)
|
|
1652
|
+
});
|
|
1653
|
+
refuseSqlTextThatDoesNotReadBack({
|
|
1654
|
+
kind: "index",
|
|
1655
|
+
namespaceId: entry.namespaceId,
|
|
1656
|
+
table: entry.tableName,
|
|
1657
|
+
name: index.name,
|
|
1658
|
+
texts: [index.expression, index.where]
|
|
1659
|
+
});
|
|
1660
|
+
const fullText = fullTextIndexDefinitionOf(index);
|
|
1661
|
+
if (fullText !== void 0) {
|
|
1662
|
+
attributes.push(buildFullTextIndexAttribute(index, fullText, fieldNameOf, naming));
|
|
1663
|
+
continue;
|
|
1664
|
+
}
|
|
1665
|
+
refuseUnwritableIndexOptions(entry, index);
|
|
1666
|
+
attributes.push(buildIndexAttribute(index, index.columns?.map(fieldNameOf), naming));
|
|
1667
|
+
}
|
|
1668
|
+
if (entry.table.control !== void 0 && variant?.singleTable !== true) attributes.push(buildAttribute("model", "control", [positionalArg(entry.table.control)]));
|
|
1669
|
+
if (input.rlsEnabled && variant?.singleTable !== true) attributes.push(buildAttribute("model", "rls", []));
|
|
1670
|
+
const mapName = pslModelMapName(entry.name, entry.tableName);
|
|
1671
|
+
if (mapName !== void 0 && variant?.singleTable !== true) attributes.push(buildMapAttribute("model", mapName));
|
|
1672
|
+
return attributes;
|
|
1673
|
+
}
|
|
1674
|
+
const PSL_REFERENTIAL_ACTIONS = {
|
|
1675
|
+
noAction: "NoAction",
|
|
1676
|
+
restrict: "Restrict",
|
|
1677
|
+
cascade: "Cascade",
|
|
1678
|
+
setNull: "SetNull",
|
|
1679
|
+
setDefault: "SetDefault"
|
|
1680
|
+
};
|
|
1681
|
+
function isReferenceRelation(relation) {
|
|
1682
|
+
return "on" in relation && relation.on !== void 0;
|
|
1683
|
+
}
|
|
1684
|
+
function collectRelations(models) {
|
|
1685
|
+
const entries = [];
|
|
1686
|
+
for (const owner of models) for (const [fieldName, relation] of Object.entries(owner.model.relations)) {
|
|
1687
|
+
if (!isReferenceRelation(relation)) refuseRelationWithoutJoin(owner.name, fieldName);
|
|
1688
|
+
entries.push({
|
|
1689
|
+
owner,
|
|
1690
|
+
fieldName,
|
|
1691
|
+
relation,
|
|
1692
|
+
targetCoordinate: crossReferenceCoordinate(relation.to)
|
|
1693
|
+
});
|
|
1694
|
+
}
|
|
1695
|
+
return entries;
|
|
1696
|
+
}
|
|
1697
|
+
/** A relation whose local fields carry the foreign key — the side `@relation(fields:…)` goes on. */
|
|
1698
|
+
function isOwningRelation(entry) {
|
|
1699
|
+
return entry.relation.cardinality === "N:1";
|
|
1700
|
+
}
|
|
1701
|
+
function relationKey(entry) {
|
|
1702
|
+
return JSON.stringify([
|
|
1703
|
+
entry.owner.namespaceId,
|
|
1704
|
+
entry.owner.name,
|
|
1705
|
+
entry.fieldName
|
|
1706
|
+
]);
|
|
1707
|
+
}
|
|
1708
|
+
/** The relation name a pair is pinned with when the model pair carries more than one relation. */
|
|
1709
|
+
function relationName(entry) {
|
|
1710
|
+
return `${entry.owner.name}_${entry.fieldName}`;
|
|
1711
|
+
}
|
|
1712
|
+
function columnsIn(model, fieldNames) {
|
|
1713
|
+
return fieldNames.map((fieldName) => model.storage.fields[fieldName]?.column ?? fieldName);
|
|
1714
|
+
}
|
|
1715
|
+
function columnsOf(entry, fieldNames) {
|
|
1716
|
+
return columnsIn(entry.owner, fieldNames);
|
|
1717
|
+
}
|
|
1718
|
+
function sameColumns(a, b) {
|
|
1719
|
+
return a.length === b.length && a.every((value, index) => value === b[index]);
|
|
1720
|
+
}
|
|
1721
|
+
/** The foreign key that backs an owning relation. */
|
|
1722
|
+
function foreignKeyFor(entry, target) {
|
|
1723
|
+
const localColumns = columnsOf(entry, entry.relation.on.localFields);
|
|
1724
|
+
const targetColumns = columnsIn(target, entry.relation.on.targetFields);
|
|
1725
|
+
return entry.owner.table.foreignKeys.find((fk) => fk.target.spaceId === void 0 && fk.target.tableName === target.tableName && fk.target.namespaceId === target.namespaceId && sameColumns(fk.source.columns, localColumns) && sameColumns(fk.target.columns, targetColumns));
|
|
1726
|
+
}
|
|
1727
|
+
/**
|
|
1728
|
+
* The owning relation on `target` that pairs with a back-relation `entry`: the
|
|
1729
|
+
* one pointing back at `entry`'s model over the same columns. The
|
|
1730
|
+
* back-relation's target fields name fields of the target model, so they are
|
|
1731
|
+
* resolved to columns through the candidate's own model, not through the
|
|
1732
|
+
* back-relation's.
|
|
1733
|
+
*/
|
|
1734
|
+
function owningPartner(entry, relationsByModel) {
|
|
1735
|
+
const ownerCoordinate = modelCoordinate(entry.owner.namespaceId, entry.owner.name);
|
|
1736
|
+
return relationsByModel.get(entry.targetCoordinate)?.find((candidate) => isOwningRelation(candidate) && candidate.targetCoordinate === ownerCoordinate && sameColumns(columnsOf(candidate, candidate.relation.on.localFields), columnsIn(candidate.owner, entry.relation.on.targetFields)));
|
|
1737
|
+
}
|
|
1738
|
+
/**
|
|
1739
|
+
* The junction-side relation that points back at the parent of a many-to-many
|
|
1740
|
+
* relation — the one whose columns are the junction's parent columns.
|
|
1741
|
+
*/
|
|
1742
|
+
function junctionParentRelation(entry, relationsByModel) {
|
|
1743
|
+
const through = entry.relation.through;
|
|
1744
|
+
if (through === void 0) return void 0;
|
|
1745
|
+
const ownerCoordinate = modelCoordinate(entry.owner.namespaceId, entry.owner.name);
|
|
1746
|
+
for (const [, relations] of relationsByModel) for (const candidate of relations) {
|
|
1747
|
+
if (candidate.owner.tableName !== through.table || candidate.owner.namespaceId !== through.namespaceId || candidate.targetCoordinate !== ownerCoordinate || !isOwningRelation(candidate)) continue;
|
|
1748
|
+
if (sameColumns(columnsOf(candidate, candidate.relation.on.localFields), through.parentColumns)) return candidate;
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
/**
|
|
1752
|
+
* The `index` argument of an owning relation. Every index the contract carries is written as its own `@@index`, and `contract emit` derives a backing index for a relation and drops it again beside an identical index or a key on its columns. So the argument is `false` for a foreign key nothing backs, the written name of an index the derived one would not match, and absent otherwise.
|
|
1753
|
+
*/
|
|
1754
|
+
function relationIndexArgument(entry, foreignKey) {
|
|
1755
|
+
const { owner } = entry;
|
|
1756
|
+
const backing = foreignKey.index;
|
|
1757
|
+
if (backing === void 0) return "false";
|
|
1758
|
+
const { table } = owner;
|
|
1759
|
+
const columns = foreignKey.source.columns;
|
|
1760
|
+
const derived = defaultForeignKeyIndex(owner.tableName, columns, {
|
|
1761
|
+
indexes: table.indexes.map(indexInputOf),
|
|
1762
|
+
uniques: table.uniques,
|
|
1763
|
+
primaryKey: table.primaryKey
|
|
1764
|
+
});
|
|
1765
|
+
if (derived !== void 0 && JSON.stringify(derived) === JSON.stringify(backing)) return;
|
|
1766
|
+
const name = backingObjectName(table, backing);
|
|
1767
|
+
if (name === void 0) refuseUnnamedForeignKeyBacking(owner.name, entry.fieldName);
|
|
1768
|
+
return `"${escapePslString(name)}"`;
|
|
1769
|
+
}
|
|
1770
|
+
function indexInputOf(index) {
|
|
1771
|
+
const shape = {
|
|
1772
|
+
naming: parseNaming(index.name, index.prefix),
|
|
1773
|
+
where: index.where,
|
|
1774
|
+
unique: index.unique,
|
|
1775
|
+
type: index.type,
|
|
1776
|
+
options: index.options
|
|
1777
|
+
};
|
|
1778
|
+
return index.expression !== void 0 ? {
|
|
1779
|
+
...shape,
|
|
1780
|
+
expression: index.expression
|
|
1781
|
+
} : {
|
|
1782
|
+
...shape,
|
|
1783
|
+
columns: index.columns ?? []
|
|
1784
|
+
};
|
|
1785
|
+
}
|
|
1786
|
+
/** The name the printed source gives what backs a foreign key: the written name of an index, unless another index shares it, or the name of the primary key or of the unique constraint with the stored columns. */
|
|
1787
|
+
function backingObjectName(table, backing) {
|
|
1788
|
+
if ("name" in backing) {
|
|
1789
|
+
const index = table.indexes.find((candidate) => candidate.name === backing.name);
|
|
1790
|
+
if (index === void 0) return backing.name;
|
|
1791
|
+
const written = index.prefix ?? index.name;
|
|
1792
|
+
return table.indexes.some((other) => other !== index && (other.prefix ?? other.name) === written) ? index.name : written;
|
|
1793
|
+
}
|
|
1794
|
+
if ("primaryKey" in backing) return table.primaryKey?.name;
|
|
1795
|
+
return table.uniques.find((unique) => sameColumns(unique.columns, backing.unique))?.name;
|
|
1796
|
+
}
|
|
1797
|
+
/** The PSL field one relation is written as. */
|
|
1798
|
+
function buildRelationField(input) {
|
|
1799
|
+
const { entry, target, name } = input;
|
|
1800
|
+
const { relation } = entry;
|
|
1801
|
+
const typeNamespaceId = target.namespaceId === entry.owner.namespaceId ? void 0 : pslNamespaceName(target.namespaceId);
|
|
1802
|
+
const args = [];
|
|
1803
|
+
if (name !== void 0) args.push(namedArg("name", `"${escapePslString(name)}"`));
|
|
1804
|
+
if (relation.cardinality === "N:1" && input.ownerIsSingleTableVariant) {
|
|
1805
|
+
args.push(namedArg("fields", `[${relation.on.localFields.join(", ")}]`));
|
|
1806
|
+
args.push(namedArg("references", `[${relation.on.targetFields.join(", ")}]`));
|
|
1807
|
+
} else if (relation.cardinality === "N:1") {
|
|
1808
|
+
const foreignKey = foreignKeyFor(entry, target);
|
|
1809
|
+
if (foreignKey === void 0) refuseToOneRelationWithoutForeignKey(entry.owner.name, entry.fieldName);
|
|
1810
|
+
args.push(namedArg("fields", `[${relation.on.localFields.join(", ")}]`));
|
|
1811
|
+
args.push(namedArg("references", `[${relation.on.targetFields.join(", ")}]`));
|
|
1812
|
+
if (foreignKey.onDelete !== void 0) args.push(namedArg("onDelete", PSL_REFERENTIAL_ACTIONS[foreignKey.onDelete]));
|
|
1813
|
+
if (foreignKey.onUpdate !== void 0) args.push(namedArg("onUpdate", PSL_REFERENTIAL_ACTIONS[foreignKey.onUpdate]));
|
|
1814
|
+
if (foreignKey.name !== void 0) args.push(namedArg("map", `"${escapePslString(foreignKey.name)}"`));
|
|
1815
|
+
const indexArgument = relationIndexArgument(entry, foreignKey);
|
|
1816
|
+
if (indexArgument !== void 0) args.push(namedArg("index", indexArgument));
|
|
1817
|
+
}
|
|
1818
|
+
const list = relation.cardinality === "1:N" || relation.cardinality === "N:M";
|
|
1819
|
+
const optional = !list && (relation.cardinality === "1:1" || relation.cardinality === "N:1") && relation.nullable === true;
|
|
1820
|
+
return {
|
|
1821
|
+
kind: "field",
|
|
1822
|
+
name: entry.fieldName,
|
|
1823
|
+
typeName: target.name,
|
|
1824
|
+
...ifDefined("typeNamespaceId", typeNamespaceId),
|
|
1825
|
+
optional,
|
|
1826
|
+
list,
|
|
1827
|
+
attributes: args.length > 0 ? [buildAttribute("field", "relation", args)] : [],
|
|
1828
|
+
span: SYNTHETIC_SPAN
|
|
1829
|
+
};
|
|
1830
|
+
}
|
|
1831
|
+
/** The relations of each model, keyed by the model's coordinate. */
|
|
1832
|
+
function relationsByModel(relations) {
|
|
1833
|
+
const byModel = /* @__PURE__ */ new Map();
|
|
1834
|
+
for (const entry of relations) {
|
|
1835
|
+
const key = modelCoordinate(entry.owner.namespaceId, entry.owner.name);
|
|
1836
|
+
const bucket = byModel.get(key) ?? [];
|
|
1837
|
+
bucket.push(entry);
|
|
1838
|
+
byModel.set(key, bucket);
|
|
1839
|
+
}
|
|
1840
|
+
return byModel;
|
|
1841
|
+
}
|
|
1842
|
+
/**
|
|
1843
|
+
* The relation names to pin. A pair needs one when either of its models
|
|
1844
|
+
* carries more than one relation to the other; a many-to-many list field
|
|
1845
|
+
* additionally pins the junction-side relation it travels through, so that
|
|
1846
|
+
* relation is named too.
|
|
1847
|
+
*/
|
|
1848
|
+
function resolvePinnedRelations(relations, relationsByModel) {
|
|
1849
|
+
const pairCounts = /* @__PURE__ */ new Map();
|
|
1850
|
+
for (const entry of relations) {
|
|
1851
|
+
const key = JSON.stringify([modelCoordinate(entry.owner.namespaceId, entry.owner.name), entry.targetCoordinate]);
|
|
1852
|
+
pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1);
|
|
1853
|
+
}
|
|
1854
|
+
const ambiguous = (entry) => {
|
|
1855
|
+
const ownerCoordinate = modelCoordinate(entry.owner.namespaceId, entry.owner.name);
|
|
1856
|
+
const forward = pairCounts.get(JSON.stringify([ownerCoordinate, entry.targetCoordinate])) ?? 0;
|
|
1857
|
+
const backward = pairCounts.get(JSON.stringify([entry.targetCoordinate, ownerCoordinate])) ?? 0;
|
|
1858
|
+
return forward > 1 || backward > 1;
|
|
1859
|
+
};
|
|
1860
|
+
const pinned = /* @__PURE__ */ new Set();
|
|
1861
|
+
for (const entry of relations) {
|
|
1862
|
+
if (!ambiguous(entry)) continue;
|
|
1863
|
+
const owning = isOwningRelation(entry) ? entry : entry.relation.cardinality === "N:M" ? junctionParentRelation(entry, relationsByModel) : owningPartner(entry, relationsByModel);
|
|
1864
|
+
if (owning !== void 0) pinned.add(relationKey(owning));
|
|
1865
|
+
}
|
|
1866
|
+
return pinned;
|
|
1867
|
+
}
|
|
1868
|
+
/**
|
|
1869
|
+
* Relation fields in the order their foreign keys appear in storage, so the
|
|
1870
|
+
* `foreignKeys` the PSL source derives come back in the same order. A relation
|
|
1871
|
+
* that owns no foreign key keeps its place at the end.
|
|
1872
|
+
*/
|
|
1873
|
+
function orderedByForeignKey(entry, relations) {
|
|
1874
|
+
const positions = /* @__PURE__ */ new Map();
|
|
1875
|
+
for (const relation of relations) {
|
|
1876
|
+
const target = relation.relation.on.localFields.map((fieldName) => relation.owner.storage.fields[fieldName]?.column ?? fieldName);
|
|
1877
|
+
const position = entry.table.foreignKeys.findIndex((fk) => fk.source.columns.length === target.length && fk.source.columns.every((column, index) => column === target[index]));
|
|
1878
|
+
positions.set(relation, isOwningRelation(relation) && position >= 0 ? position : relations.length);
|
|
1879
|
+
}
|
|
1880
|
+
return [...relations].sort((a, b) => (positions.get(a) ?? 0) - (positions.get(b) ?? 0));
|
|
1881
|
+
}
|
|
1882
|
+
/**
|
|
1883
|
+
* The relation fields of one model, in the order of its foreign keys. Each foreign key an owning
|
|
1884
|
+
* relation travels is added to `travelledForeignKeys`.
|
|
1885
|
+
*/
|
|
1886
|
+
function buildRelationFields(input) {
|
|
1887
|
+
const fields = [];
|
|
1888
|
+
for (const modelRelation of orderedByForeignKey(input.entry, input.relations)) {
|
|
1889
|
+
refuseUnwritableName("field", modelRelation.fieldName);
|
|
1890
|
+
const target = relationTarget(modelRelation, input.modelsByCoordinate);
|
|
1891
|
+
const junctionRelation = modelRelation.relation.cardinality === "N:M" ? junctionParentRelation(modelRelation, input.relationsByModel) : void 0;
|
|
1892
|
+
if (modelRelation.relation.cardinality === "N:M" && junctionRelation === void 0) refuseManyToManyWithoutJunctionRelation(modelRelation.owner.name, modelRelation.fieldName);
|
|
1893
|
+
const owning = isOwningRelation(modelRelation) ? modelRelation : modelRelation.relation.cardinality === "N:M" ? junctionRelation : owningPartner(modelRelation, input.relationsByModel);
|
|
1894
|
+
if (owning === void 0) refuseBackRelationWithoutOwningRelation({
|
|
1895
|
+
modelName: modelRelation.owner.name,
|
|
1896
|
+
fieldName: modelRelation.fieldName,
|
|
1897
|
+
targetModel: target.name
|
|
1898
|
+
});
|
|
1899
|
+
const name = input.pinned.has(relationKey(owning)) ? relationName(owning) : void 0;
|
|
1900
|
+
if (isOwningRelation(modelRelation)) {
|
|
1901
|
+
const foreignKey = foreignKeyFor(modelRelation, target);
|
|
1902
|
+
if (foreignKey !== void 0) input.travelledForeignKeys.add(foreignKey);
|
|
1903
|
+
}
|
|
1904
|
+
fields.push(buildRelationField({
|
|
1905
|
+
entry: modelRelation,
|
|
1906
|
+
target,
|
|
1907
|
+
name,
|
|
1908
|
+
ownerIsSingleTableVariant: input.variant?.singleTable === true
|
|
1909
|
+
}));
|
|
1910
|
+
}
|
|
1911
|
+
return fields;
|
|
1912
|
+
}
|
|
1913
|
+
/**
|
|
1914
|
+
* The model a relation points at. A relation into another contract space is
|
|
1915
|
+
* refused: the printer does not write one yet.
|
|
1916
|
+
*/
|
|
1917
|
+
function relationTarget(entry, modelsByCoordinate) {
|
|
1918
|
+
const { to } = entry.relation;
|
|
1919
|
+
refuseRelationToOtherContractSpace({
|
|
1920
|
+
modelName: entry.owner.name,
|
|
1921
|
+
fieldName: entry.fieldName,
|
|
1922
|
+
targetModel: to.model,
|
|
1923
|
+
space: to.space
|
|
1924
|
+
});
|
|
1925
|
+
const target = modelsByCoordinate.get(entry.targetCoordinate);
|
|
1926
|
+
assertDefined(target, `relation "${entry.owner.name}.${entry.fieldName}" targets model "${to.namespace}.${to.model}", which the contract does not declare`);
|
|
1927
|
+
return target;
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* The storage tables of one namespace that have row-level security enabled,
|
|
1931
|
+
* each written as `@@rls` on its model. The PSL source files each one under
|
|
1932
|
+
* its table name, in the namespace of its model.
|
|
1933
|
+
*/
|
|
1934
|
+
function rlsEnabledTables(namespaceId, entries) {
|
|
1935
|
+
const tables = /* @__PURE__ */ new Set();
|
|
1936
|
+
for (const [name, entity] of Object.entries(entries ?? {})) {
|
|
1937
|
+
invariant(entity instanceof PostgresRlsEnablement, `"rls" entry "${name}" in namespace "${namespaceId}" is not a row-level security setting`);
|
|
1938
|
+
refuseEntryInOtherNamespace({
|
|
1939
|
+
namespaceId,
|
|
1940
|
+
kind: "rls",
|
|
1941
|
+
name,
|
|
1942
|
+
recordedNamespaceId: entity.namespaceId
|
|
1943
|
+
});
|
|
1944
|
+
refuseEntryFiledUnderAnotherName({
|
|
1945
|
+
namespaceId,
|
|
1946
|
+
kind: "rls",
|
|
1947
|
+
name,
|
|
1948
|
+
readsBackAs: entity.tableName
|
|
1949
|
+
});
|
|
1950
|
+
tables.add(entity.tableName);
|
|
1951
|
+
}
|
|
1952
|
+
return tables;
|
|
1953
|
+
}
|
|
1954
|
+
/**
|
|
1955
|
+
* One `role <name> {}` block per role. The PSL source reads a role block only
|
|
1956
|
+
* inside `namespace unbound`, and files it under its name.
|
|
1957
|
+
*/
|
|
1958
|
+
function buildRoleBlocks(namespaceId, entries) {
|
|
1959
|
+
return Object.entries(entries ?? {}).map(([name, entity]) => {
|
|
1960
|
+
invariant(entity instanceof PostgresRole, `"role" entry "${name}" in namespace "${namespaceId}" is not a role`);
|
|
1961
|
+
refuseRoleOutsideUnbound(namespaceId, name);
|
|
1962
|
+
refuseEntryInOtherNamespace({
|
|
1963
|
+
namespaceId,
|
|
1964
|
+
kind: "role",
|
|
1965
|
+
name,
|
|
1966
|
+
recordedNamespaceId: entity.namespaceId
|
|
1967
|
+
});
|
|
1968
|
+
refuseEntryFiledUnderAnotherName({
|
|
1969
|
+
namespaceId,
|
|
1970
|
+
kind: "role",
|
|
1971
|
+
name,
|
|
1972
|
+
readsBackAs: entity.name
|
|
1973
|
+
});
|
|
1974
|
+
refuseUnwritableName("role", entity.name);
|
|
1975
|
+
return {
|
|
1976
|
+
kind: "role",
|
|
1977
|
+
keyword: "role",
|
|
1978
|
+
name: entity.name,
|
|
1979
|
+
parameters: {},
|
|
1980
|
+
blockAttributes: [],
|
|
1981
|
+
span: SYNTHETIC_SPAN
|
|
1982
|
+
};
|
|
1983
|
+
});
|
|
1984
|
+
}
|
|
1985
|
+
/**
|
|
1986
|
+
* Whether the PSL source, reading a policy block named `head`, derives this
|
|
1987
|
+
* policy's name: the block name with the hash of the policy's content for a
|
|
1988
|
+
* wire-named policy, or the `@@map` name for an exact one.
|
|
1989
|
+
*/
|
|
1990
|
+
function policyNameReadsBack(head, policy) {
|
|
1991
|
+
if (policy.prefix === void 0) return true;
|
|
1992
|
+
const hash = computeContentHash({
|
|
1993
|
+
...policy.using === void 0 ? {} : { using: policy.using },
|
|
1994
|
+
...policy.withCheck === void 0 ? {} : { withCheck: policy.withCheck },
|
|
1995
|
+
roles: policy.roles,
|
|
1996
|
+
operation: policy.operation,
|
|
1997
|
+
permissive: policy.permissive
|
|
1998
|
+
});
|
|
1999
|
+
return policy.prefix === head && policy.name === formatWireName(head, hash);
|
|
2000
|
+
}
|
|
2001
|
+
/**
|
|
2002
|
+
* One `policy_<operation>` block per policy, named by its entry key, which is
|
|
2003
|
+
* the block head it was authored under. A policy with an exact name also
|
|
2004
|
+
* prints `@@map` with that name.
|
|
2005
|
+
*/
|
|
2006
|
+
function buildPolicyBlocks(input) {
|
|
2007
|
+
return Object.entries(input.entries ?? {}).map(([head, policy]) => {
|
|
2008
|
+
invariant(policy instanceof PostgresRlsPolicy, `"policy" entry "${head}" in namespace "${input.namespaceId}" is not a policy`);
|
|
2009
|
+
refuseUnwritableName("policy", head);
|
|
2010
|
+
refuseEntryInOtherNamespace({
|
|
2011
|
+
namespaceId: input.namespaceId,
|
|
2012
|
+
kind: "policy",
|
|
2013
|
+
name: head,
|
|
2014
|
+
recordedNamespaceId: policy.namespaceId
|
|
2015
|
+
});
|
|
2016
|
+
const modelName = input.modelNameForTable(policy.tableName);
|
|
2017
|
+
if (modelName === void 0) refusePolicyWithoutModel(policy);
|
|
2018
|
+
if (!input.rlsTables.has(policy.tableName)) refusePolicyWithoutRls(policy);
|
|
2019
|
+
if (!policyNameReadsBack(head, policy)) refusePolicyNameNotDerived(policy);
|
|
2020
|
+
for (const role of policy.roles) refuseUnwritableName("role", role);
|
|
2021
|
+
refuseSqlTextThatDoesNotReadBack({
|
|
2022
|
+
kind: "policy",
|
|
2023
|
+
namespaceId: policy.namespaceId,
|
|
2024
|
+
table: policy.tableName,
|
|
2025
|
+
name: policy.name,
|
|
2026
|
+
texts: [policy.using, policy.withCheck]
|
|
2027
|
+
});
|
|
2028
|
+
return {
|
|
2029
|
+
kind: "policy",
|
|
2030
|
+
keyword: POLICY_BLOCK_KEYWORDS[policy.operation],
|
|
2031
|
+
name: head,
|
|
2032
|
+
parameters: {
|
|
2033
|
+
target: {
|
|
2034
|
+
expression: modelName,
|
|
2035
|
+
span: SYNTHETIC_SPAN
|
|
2036
|
+
},
|
|
2037
|
+
roles: {
|
|
2038
|
+
expression: `[${policy.roles.join(", ")}]`,
|
|
2039
|
+
span: SYNTHETIC_SPAN
|
|
2040
|
+
},
|
|
2041
|
+
...policy.using !== void 0 ? { using: {
|
|
2042
|
+
expression: printSqlExpressionLiteral(policy.using),
|
|
2043
|
+
span: SYNTHETIC_SPAN
|
|
2044
|
+
} } : {},
|
|
2045
|
+
...policy.withCheck !== void 0 ? { withCheck: {
|
|
2046
|
+
expression: printSqlExpressionLiteral(policy.withCheck),
|
|
2047
|
+
span: SYNTHETIC_SPAN
|
|
2048
|
+
} } : {},
|
|
2049
|
+
...policy.permissive ? {} : { permissive: {
|
|
2050
|
+
expression: "false",
|
|
2051
|
+
span: SYNTHETIC_SPAN
|
|
2052
|
+
} }
|
|
2053
|
+
},
|
|
2054
|
+
blockAttributes: policy.prefix === void 0 ? [{
|
|
2055
|
+
name: "map",
|
|
2056
|
+
args: [{
|
|
2057
|
+
kind: "positional",
|
|
2058
|
+
value: `"${escapePslString(policy.name)}"`,
|
|
2059
|
+
span: SYNTHETIC_SPAN
|
|
2060
|
+
}],
|
|
2061
|
+
span: SYNTHETIC_SPAN
|
|
2062
|
+
}] : [],
|
|
2063
|
+
span: SYNTHETIC_SPAN
|
|
2064
|
+
};
|
|
2065
|
+
});
|
|
2066
|
+
}
|
|
2067
|
+
/**
|
|
2068
|
+
* The `@default(…)` attribute for a storage column, or `undefined` when the column carries no
|
|
2069
|
+
* default.
|
|
2070
|
+
*
|
|
2071
|
+
* A literal prints as the PSL literal the data type of the column's codec reads back, through the
|
|
2072
|
+
* stack's data types, with the mapping `contract infer` uses. An enum column's default is a member
|
|
2073
|
+
* name, which reads as text; a domain enum's literal prints as the member name that carries it.
|
|
2074
|
+
* `now()` and `autoincrement()` print by name; every other function default prints as a `sql`
|
|
2075
|
+
* tagged literal.
|
|
2076
|
+
*
|
|
2077
|
+
* A literal is refused when the column's codec has no data type in the stack, or when no PSL
|
|
2078
|
+
* literal of that data type reads back as the stored value. A function default is refused when a
|
|
2079
|
+
* `sql` literal cannot write its text back unchanged.
|
|
2080
|
+
*/
|
|
2081
|
+
function buildColumnDefault(input) {
|
|
2082
|
+
const columnDefault = input.column.default;
|
|
2083
|
+
if (columnDefault === void 0) return;
|
|
2084
|
+
const coordinate = `"${input.namespaceId}"."${input.tableName}"."${input.columnName}"`;
|
|
2085
|
+
if (input.domainEnum !== void 0 && columnDefault.kind === "literal") {
|
|
2086
|
+
const memberName = input.domainEnum.members.find((member) => member.value === columnDefault.value)?.name;
|
|
2087
|
+
if (memberName === void 0) refuseDefaultOutsideEnum({
|
|
2088
|
+
coordinate,
|
|
2089
|
+
value: columnDefault.value,
|
|
2090
|
+
pslTypeName: input.pslTypeName
|
|
2091
|
+
});
|
|
2092
|
+
return buildAttribute("field", "default", [positionalArg(memberName)]);
|
|
2093
|
+
}
|
|
2094
|
+
if (columnDefault.kind === "function") refuseSqlTextThatDoesNotReadBack({
|
|
2095
|
+
kind: "default",
|
|
2096
|
+
coordinate,
|
|
2097
|
+
texts: [columnDefault.expression]
|
|
2098
|
+
});
|
|
2099
|
+
const { context } = input;
|
|
2100
|
+
const result = mapDefault(columnDefault, {
|
|
2101
|
+
dataTypes: context.dataTypes,
|
|
2102
|
+
columnCodec: context.codecLookup.descriptorFor(input.isEnum ? PG_TEXT_CODEC_ID : input.column.codecId),
|
|
2103
|
+
typeParams: resolvedTypeParams(input.column, input.namedTypes),
|
|
2104
|
+
list: input.column.many !== false
|
|
2105
|
+
});
|
|
2106
|
+
if (result === void 0) refuseUnwritableLiteralDefault({
|
|
2107
|
+
coordinate,
|
|
2108
|
+
written: columnDefault.kind === "literal" ? JSON.stringify(columnDefault.value) : columnDefault.expression,
|
|
2109
|
+
pslTypeName: input.pslTypeName
|
|
2110
|
+
});
|
|
2111
|
+
return parseDefaultAttributeString(result.attribute);
|
|
2112
|
+
}
|
|
2113
|
+
function toPslArgument(argument) {
|
|
2114
|
+
return argument.kind === "positional" ? positionalArg(argument.value) : namedArg(argument.name, argument.value);
|
|
2115
|
+
}
|
|
2116
|
+
/**
|
|
2117
|
+
* How one column's execution generators are written in PSL: as the call of the field preset of the stack that writes the column's codec with them, or else a create-only generator as the `@default(<fn>(...))` call of the default function that declares `printArguments` for it. A column neither writes is refused, with the preset's reason when a preset writes its codec and generators.
|
|
2118
|
+
*/
|
|
2119
|
+
function buildExecutionDefault(input) {
|
|
2120
|
+
const { executionDefault, codecId, pslType, list, typeParams, coordinate, context } = input;
|
|
2121
|
+
const onCreateId = executionDefault.onCreate?.id;
|
|
2122
|
+
const onUpdateId = executionDefault.onUpdate?.id;
|
|
2123
|
+
const phases = {
|
|
2124
|
+
coordinate,
|
|
2125
|
+
onCreate: onCreateId,
|
|
2126
|
+
onUpdate: onUpdateId
|
|
2127
|
+
};
|
|
2128
|
+
const choice = fieldPresetCallFor({
|
|
2129
|
+
fieldPresetsByCodecAndGenerator: context.fieldPresetsByCodecAndGenerator,
|
|
2130
|
+
column: {
|
|
2131
|
+
codecId,
|
|
2132
|
+
pslType,
|
|
2133
|
+
list,
|
|
2134
|
+
typeParams,
|
|
2135
|
+
generators: executionDefault
|
|
2136
|
+
}
|
|
2137
|
+
});
|
|
2138
|
+
if (choice.kind === "call") return {
|
|
2139
|
+
kind: "preset",
|
|
2140
|
+
path: choice.preset.path,
|
|
2141
|
+
args: choice.arguments.map(toPslArgument)
|
|
2142
|
+
};
|
|
2143
|
+
const call = onCreateId === void 0 || onUpdateId !== void 0 ? void 0 : defaultFunctionCallFor(context.defaultFunctionPrintersByGenerator, onCreateId, executionDefault.onCreate?.params);
|
|
2144
|
+
if (call !== void 0) return {
|
|
2145
|
+
kind: "attribute",
|
|
2146
|
+
attribute: buildAttribute("field", "default", [positionalArg(call)])
|
|
2147
|
+
};
|
|
2148
|
+
switch (choice.kind) {
|
|
2149
|
+
case "cannotWrite":
|
|
2150
|
+
if (choice.reason.kind === "phasesNotWrittenTogether") return refuseGeneratorsNoPresetWritesTogether(phases);
|
|
2151
|
+
return refuseUnwritablePresetCall({
|
|
2152
|
+
coordinate,
|
|
2153
|
+
preset: choice.preset.path.join("."),
|
|
2154
|
+
reason: choice.reason
|
|
2155
|
+
});
|
|
2156
|
+
case "readsBackDifferently": return refusePresetCallReadingBackDifferently({
|
|
2157
|
+
coordinate,
|
|
2158
|
+
preset: choice.preset.path.join("."),
|
|
2159
|
+
differences: choice.differences
|
|
2160
|
+
});
|
|
2161
|
+
case "noPreset":
|
|
2162
|
+
if (onUpdateId !== void 0) return refuseGeneratorOnUpdate(phases);
|
|
2163
|
+
return refuseGeneratorWithoutPslFunction({
|
|
2164
|
+
...phases,
|
|
2165
|
+
registeredBy: onCreateId !== void 0 && context.componentIdsByGenerator.has(onCreateId) ? { componentId: context.componentIdsByGenerator.get(onCreateId) } : void 0
|
|
2166
|
+
});
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
/** The generated values of the contract, keyed by the column they fill. */
|
|
2170
|
+
function executionDefaultsByColumn(contract) {
|
|
2171
|
+
const byColumn = /* @__PURE__ */ new Map();
|
|
2172
|
+
for (const entry of contract.execution?.mutations.defaults ?? []) byColumn.set(JSON.stringify([
|
|
2173
|
+
entry.ref.namespace,
|
|
2174
|
+
entry.ref.entry,
|
|
2175
|
+
entry.ref.field
|
|
2176
|
+
]), entry);
|
|
2177
|
+
return byColumn;
|
|
2178
|
+
}
|
|
2179
|
+
function scalarFieldAttributes(input) {
|
|
2180
|
+
const attributes = [];
|
|
2181
|
+
if (input.isSingleColumnId) attributes.push(buildAttribute("field", "id", input.primaryKeyName === void 0 ? [] : [namedArg("map", `"${escapePslString(input.primaryKeyName)}"`)]));
|
|
2182
|
+
const columnDefault = input.generatedDefault ?? buildColumnDefault({
|
|
2183
|
+
column: input.column,
|
|
2184
|
+
pslTypeName: input.pslTypeName,
|
|
2185
|
+
isEnum: input.isEnum,
|
|
2186
|
+
domainEnum: input.domainEnum,
|
|
2187
|
+
namespaceId: input.namespaceId,
|
|
2188
|
+
tableName: input.tableName,
|
|
2189
|
+
columnName: input.columnName,
|
|
2190
|
+
context: input.context,
|
|
2191
|
+
namedTypes: input.namedTypes
|
|
2192
|
+
});
|
|
2193
|
+
if (columnDefault !== void 0) attributes.push(columnDefault);
|
|
2194
|
+
const mapName = pslFieldMapName(input.fieldName, input.columnName);
|
|
2195
|
+
if (mapName !== void 0) attributes.push(buildMapAttribute("field", mapName));
|
|
2196
|
+
return attributes;
|
|
2197
|
+
}
|
|
2198
|
+
/**
|
|
2199
|
+
* The scalar and value-object fields of one model, one per column its storage names.
|
|
2200
|
+
*/
|
|
2201
|
+
function buildScalarFields(input) {
|
|
2202
|
+
const { entry, variant, enums, domainEnums, inferredConstructors, context, executionDefaults } = input;
|
|
2203
|
+
const primaryKeyColumns = variant === void 0 ? entry.table.primaryKey?.columns ?? [] : [];
|
|
2204
|
+
const fields = [];
|
|
2205
|
+
for (const [fieldName, fieldStorage] of Object.entries(entry.storage.fields)) {
|
|
2206
|
+
const columnName = fieldStorage.column;
|
|
2207
|
+
const coordinate = `"${entry.namespaceId}"."${entry.tableName}"."${columnName}"`;
|
|
2208
|
+
const column = entry.table.columns[columnName];
|
|
2209
|
+
const field = entry.model.fields[fieldName];
|
|
2210
|
+
assertDefined(column, `column ${coordinate} is not declared by its table`);
|
|
2211
|
+
if (field === void 0) refuseStorageOfUndeclaredField({
|
|
2212
|
+
entry,
|
|
2213
|
+
fieldName,
|
|
2214
|
+
coordinate
|
|
2215
|
+
});
|
|
2216
|
+
refuseUnwritableName("field", fieldName);
|
|
2217
|
+
refuseUnwritableMappedName("column", columnName);
|
|
2218
|
+
refuseUnwritableFieldShape(field, coordinate);
|
|
2219
|
+
refuseColumnControl(column, coordinate);
|
|
2220
|
+
refuseFieldColumnMismatch({
|
|
2221
|
+
field,
|
|
2222
|
+
column,
|
|
2223
|
+
coordinate,
|
|
2224
|
+
modelName: entry.name,
|
|
2225
|
+
singleTableVariant: variant?.singleTable === true,
|
|
2226
|
+
domainEnumNames: input.defaultDomainEnumNames,
|
|
2227
|
+
namedTypes: input.namedTypes
|
|
2228
|
+
});
|
|
2229
|
+
if (column.typeRef !== void 0) refuseColumnDifferingFromNamedType({
|
|
2230
|
+
column,
|
|
2231
|
+
typeRef: column.typeRef,
|
|
2232
|
+
namedType: input.namedTypes[column.typeRef],
|
|
2233
|
+
coordinate
|
|
2234
|
+
});
|
|
2235
|
+
const columnType = column.typeRef !== void 0 ? {
|
|
2236
|
+
kind: "namedType",
|
|
2237
|
+
typeName: column.typeRef
|
|
2238
|
+
} : field.type.kind === "valueObject" ? {
|
|
2239
|
+
kind: "valueObject",
|
|
2240
|
+
typeName: field.type.name
|
|
2241
|
+
} : buildColumnType({
|
|
2242
|
+
column,
|
|
2243
|
+
inferredConstructors,
|
|
2244
|
+
authoringTypes: context.authoringContributions.type,
|
|
2245
|
+
dataTypeLookup: context.dataTypes.lookup,
|
|
2246
|
+
enumBlockNames: enums.blockNamesByTypeName,
|
|
2247
|
+
coordinate,
|
|
2248
|
+
namespaceId: entry.namespaceId
|
|
2249
|
+
});
|
|
2250
|
+
let { typeName, typeConstructor } = columnType;
|
|
2251
|
+
const execution = executionDefaults.get(JSON.stringify([
|
|
2252
|
+
entry.namespaceId,
|
|
2253
|
+
entry.tableName,
|
|
2254
|
+
columnName
|
|
2255
|
+
]));
|
|
2256
|
+
let generatedDefault;
|
|
2257
|
+
if (execution !== void 0) {
|
|
2258
|
+
const built = buildExecutionDefault({
|
|
2259
|
+
executionDefault: execution,
|
|
2260
|
+
codecId: column.codecId,
|
|
2261
|
+
pslType: columnType,
|
|
2262
|
+
list: !!field.many,
|
|
2263
|
+
typeParams: column.typeParams,
|
|
2264
|
+
coordinate,
|
|
2265
|
+
context
|
|
2266
|
+
});
|
|
2267
|
+
if (built.kind === "preset") {
|
|
2268
|
+
typeName = built.path.join(".");
|
|
2269
|
+
typeConstructor = {
|
|
2270
|
+
kind: "typeConstructor",
|
|
2271
|
+
path: built.path,
|
|
2272
|
+
args: built.args,
|
|
2273
|
+
span: SYNTHETIC_SPAN
|
|
2274
|
+
};
|
|
2275
|
+
} else if (column.default !== void 0) refuseGeneratorWithDatabaseDefault({
|
|
2276
|
+
coordinate,
|
|
2277
|
+
onCreate: execution.onCreate?.id
|
|
2278
|
+
});
|
|
2279
|
+
else generatedDefault = built.attribute;
|
|
2280
|
+
}
|
|
2281
|
+
fields.push({
|
|
2282
|
+
kind: "field",
|
|
2283
|
+
name: fieldName,
|
|
2284
|
+
typeName,
|
|
2285
|
+
...ifDefined("typeConstructor", typeConstructor),
|
|
2286
|
+
optional: field.nullable,
|
|
2287
|
+
list: !!field.many,
|
|
2288
|
+
elementOptional: !!field.many && field.many.elementNullable,
|
|
2289
|
+
attributes: scalarFieldAttributes({
|
|
2290
|
+
column,
|
|
2291
|
+
fieldName,
|
|
2292
|
+
namespaceId: entry.namespaceId,
|
|
2293
|
+
tableName: entry.tableName,
|
|
2294
|
+
columnName,
|
|
2295
|
+
isSingleColumnId: primaryKeyColumns.length === 1 && primaryKeyColumns[0] === columnName,
|
|
2296
|
+
primaryKeyName: entry.table.primaryKey?.name,
|
|
2297
|
+
pslTypeName: columnType.typeName,
|
|
2298
|
+
isEnum: column.codecId === PG_ENUM_CODEC_ID,
|
|
2299
|
+
domainEnum: column.codecId === "pg/enum@1" || column.valueSet === void 0 ? void 0 : domainEnums[column.valueSet.entityName],
|
|
2300
|
+
generatedDefault,
|
|
2301
|
+
context,
|
|
2302
|
+
namedTypes: input.namedTypes
|
|
2303
|
+
}),
|
|
2304
|
+
span: SYNTHETIC_SPAN
|
|
2305
|
+
});
|
|
2306
|
+
}
|
|
2307
|
+
return fields;
|
|
2308
|
+
}
|
|
2309
|
+
/** The native enums of one namespace, keyed as the contract keys them. */
|
|
2310
|
+
function nativeEnumsOf(namespaceId, entries) {
|
|
2311
|
+
const nativeEnums = /* @__PURE__ */ new Map();
|
|
2312
|
+
for (const [name, entity] of Object.entries(entries["native_enum"] ?? {})) {
|
|
2313
|
+
invariant(PostgresNativeEnum.is(entity), `"native_enum" entry "${name}" in namespace "${namespaceId}" is not a native enum`);
|
|
2314
|
+
nativeEnums.set(name, entity);
|
|
2315
|
+
}
|
|
2316
|
+
return nativeEnums;
|
|
2317
|
+
}
|
|
2318
|
+
/** The value sets the PSL source derives for a namespace from the enum blocks written for it. */
|
|
2319
|
+
function derivedValueSetsOf(namespaceId, enums, defaultDomainEnums) {
|
|
2320
|
+
const derived = new Map(enums.derivedValueSets);
|
|
2321
|
+
if (namespaceId !== "public") return derived;
|
|
2322
|
+
for (const [name, domainEnum] of Object.entries(defaultDomainEnums)) {
|
|
2323
|
+
if (derived.has(name)) refuseEnumAndNativeEnumSharingName(namespaceId, name);
|
|
2324
|
+
derived.set(name, domainEnum.members.map((member) => member.value));
|
|
2325
|
+
}
|
|
2326
|
+
return derived;
|
|
2327
|
+
}
|
|
2328
|
+
/** One model of a namespace, with its fields and attributes. */
|
|
2329
|
+
function buildModel(all, entry, enums, rlsTables) {
|
|
2330
|
+
const { models, variants, relationsByModel, byCoordinate } = all;
|
|
2331
|
+
refuseUnwritableName("model", entry.name);
|
|
2332
|
+
refuseModelOwner(entry);
|
|
2333
|
+
const variant = variants.get(entry);
|
|
2334
|
+
if (variant !== void 0 && !variant.singleTable) refuseUnderivedVariantLink(entry, variant);
|
|
2335
|
+
const singleTableVariants = models.filter((other) => other !== entry && variants.get(other)?.singleTable === true && variants.get(other)?.base === entry);
|
|
2336
|
+
const travelledForeignKeys = /* @__PURE__ */ new Set();
|
|
2337
|
+
const fields = [...buildScalarFields({
|
|
2338
|
+
entry,
|
|
2339
|
+
variant,
|
|
2340
|
+
enums,
|
|
2341
|
+
domainEnums: all.contract.domain.namespaces[entry.namespaceId]?.enum ?? {},
|
|
2342
|
+
inferredConstructors: all.inferredConstructors,
|
|
2343
|
+
context: all.context,
|
|
2344
|
+
executionDefaults: all.executionDefaults,
|
|
2345
|
+
defaultDomainEnumNames: new Set(Object.keys(all.defaultDomainEnums)),
|
|
2346
|
+
namedTypes: all.contract.storage.types ?? {}
|
|
2347
|
+
}), ...buildRelationFields({
|
|
2348
|
+
entry,
|
|
2349
|
+
variant,
|
|
2350
|
+
relations: relationsByModel.get(modelCoordinate(entry.namespaceId, entry.name)) ?? [],
|
|
2351
|
+
relationsByModel,
|
|
2352
|
+
modelsByCoordinate: byCoordinate,
|
|
2353
|
+
pinned: all.pinned,
|
|
2354
|
+
travelledForeignKeys
|
|
2355
|
+
})];
|
|
2356
|
+
if (variant?.singleTable !== true) for (const other of singleTableVariants) for (const relation of relationsByModel.get(modelCoordinate(entry.namespaceId, other.name)) ?? []) {
|
|
2357
|
+
const target = byCoordinate.get(relation.targetCoordinate);
|
|
2358
|
+
const fk = target === void 0 ? void 0 : foreignKeyFor(relation, target);
|
|
2359
|
+
if (fk !== void 0) travelledForeignKeys.add(fk);
|
|
2360
|
+
}
|
|
2361
|
+
refuseUntravelledForeignKeys(entry, variant, travelledForeignKeys);
|
|
2362
|
+
const checks = derivedChecks({
|
|
2363
|
+
table: entry.table,
|
|
2364
|
+
tableName: entry.tableName,
|
|
2365
|
+
managed: effectiveControlPolicy(entry.table.control, all.contract.defaultControlPolicy) === "managed",
|
|
2366
|
+
domainEnumValues: all.domainEnumValues
|
|
2367
|
+
});
|
|
2368
|
+
if (variant?.singleTable !== true) refuseUnderivedChecks(entry, checks);
|
|
2369
|
+
return {
|
|
2370
|
+
kind: "model",
|
|
2371
|
+
name: entry.name,
|
|
2372
|
+
fields,
|
|
2373
|
+
attributes: buildModelAttributes({
|
|
2374
|
+
entry,
|
|
2375
|
+
variant,
|
|
2376
|
+
singleTableVariants,
|
|
2377
|
+
derivedChecksByName: checks,
|
|
2378
|
+
rlsEnabled: rlsTables.has(entry.tableName)
|
|
2379
|
+
}),
|
|
2380
|
+
span: SYNTHETIC_SPAN
|
|
2381
|
+
};
|
|
2382
|
+
}
|
|
2383
|
+
/**
|
|
2384
|
+
* The namespace block of one storage namespace: its models, value objects, enum blocks, roles and
|
|
2385
|
+
* policies. `undefined` when the namespace holds none of them.
|
|
2386
|
+
*/
|
|
2387
|
+
function buildNamespace(all, namespaceId, namespace) {
|
|
2388
|
+
const { contract, models, variants } = all;
|
|
2389
|
+
refuseUnprintedEntryKinds(namespaceId, namespace.entries);
|
|
2390
|
+
const valueSets = new Map(Object.entries(namespace.entries.valueSet ?? {}).map(([name, valueSet]) => [name, valueSet.values]));
|
|
2391
|
+
const enums = buildNativeEnumBlocksForNamespace({
|
|
2392
|
+
namespaceId,
|
|
2393
|
+
nativeEnums: nativeEnumsOf(namespaceId, namespace.entries),
|
|
2394
|
+
valueSets,
|
|
2395
|
+
columns: models.filter((entry) => entry.namespaceId === namespaceId).flatMap((entry) => Object.values(entry.table.columns))
|
|
2396
|
+
});
|
|
2397
|
+
refuseUnderivedValueSets({
|
|
2398
|
+
namespaceId,
|
|
2399
|
+
actual: valueSets,
|
|
2400
|
+
derived: derivedValueSetsOf(namespaceId, enums, all.defaultDomainEnums)
|
|
2401
|
+
});
|
|
2402
|
+
const rlsTables = rlsEnabledTables(namespaceId, namespace.entries["rls"]);
|
|
2403
|
+
const namespaceModels = models.filter((entry) => entry.namespaceId === namespaceId).map((entry) => buildModel(all, entry, enums, rlsTables));
|
|
2404
|
+
const compositeTypes = buildCompositeTypes({
|
|
2405
|
+
contract,
|
|
2406
|
+
namespaceId,
|
|
2407
|
+
inferredConstructors: all.inferredConstructors,
|
|
2408
|
+
context: all.context,
|
|
2409
|
+
enumBlockNames: enums.blockNamesByTypeName,
|
|
2410
|
+
domainEnums: all.defaultDomainEnums
|
|
2411
|
+
});
|
|
2412
|
+
const modelNameForTable = (tableName) => models.find((entry) => entry.namespaceId === namespaceId && entry.tableName === tableName && variants.get(entry)?.singleTable !== true)?.name;
|
|
2413
|
+
for (const tableName of rlsTables) if (modelNameForTable(tableName) === void 0) refuseRlsWithoutModel(namespaceId, tableName);
|
|
2414
|
+
const blocks = [
|
|
2415
|
+
...enums.blocks,
|
|
2416
|
+
...buildRoleBlocks(namespaceId, namespace.entries["role"]),
|
|
2417
|
+
...buildPolicyBlocks({
|
|
2418
|
+
namespaceId,
|
|
2419
|
+
entries: namespace.entries["policy"],
|
|
2420
|
+
modelNameForTable,
|
|
2421
|
+
rlsTables
|
|
2422
|
+
})
|
|
2423
|
+
];
|
|
2424
|
+
if (namespaceModels.length === 0 && blocks.length === 0 && compositeTypes.length === 0) return;
|
|
2425
|
+
refuseNamespaceNamedUnbound(namespaceId);
|
|
2426
|
+
const name = pslNamespaceName(namespaceId);
|
|
2427
|
+
refuseUnwritableName("namespace", name);
|
|
2428
|
+
return makePslNamespace({
|
|
2429
|
+
kind: "namespace",
|
|
2430
|
+
name,
|
|
2431
|
+
entries: makePslNamespaceEntries(namespaceModels, compositeTypes, blocks),
|
|
2432
|
+
span: SYNTHETIC_SPAN
|
|
2433
|
+
});
|
|
2434
|
+
}
|
|
2435
|
+
function refuseUnwritableTableNames(contract) {
|
|
2436
|
+
for (const domainNamespace of Object.values(contract.domain.namespaces)) for (const model of Object.values(domainNamespace.models)) refuseUnwritableMappedName("table", blindCast(model.storage).table);
|
|
2437
|
+
}
|
|
2438
|
+
/**
|
|
2439
|
+
* Builds the Prisma 8 PSL document a Postgres contract was, or would have been, authored as: every
|
|
2440
|
+
* model with its columns, keys, indexes and relations, every value object, every named type and
|
|
2441
|
+
* every native enum, in the namespace block that carries it.
|
|
2442
|
+
*
|
|
2443
|
+
* Read back by the PSL contract source with the same stack, the document yields the contract it was
|
|
2444
|
+
* built from. Anything the language cannot carry is refused by name. `contract` must be one the
|
|
2445
|
+
* Postgres contract serializer accepted: its structure is asserted, not checked again.
|
|
2446
|
+
*/
|
|
2447
|
+
function buildPostgresPslContract(contract, context) {
|
|
2448
|
+
refuseUnwritableTableNames(contract);
|
|
2449
|
+
const models = indexContractModels(contract);
|
|
2450
|
+
refuseDuplicateModelNames(models);
|
|
2451
|
+
const byCoordinate = modelsByCoordinate(models);
|
|
2452
|
+
const relations = collectRelations(models);
|
|
2453
|
+
const byModel = relationsByModel(relations);
|
|
2454
|
+
const defaultDomainEnums = contract.domain.namespaces["public"]?.enum ?? {};
|
|
2455
|
+
const all = {
|
|
2456
|
+
contract,
|
|
2457
|
+
context,
|
|
2458
|
+
inferredConstructors: inferredTypeConstructors({
|
|
2459
|
+
authoringTypes: context.authoringContributions.type,
|
|
2460
|
+
codecLookup: context.codecLookup,
|
|
2461
|
+
dataTypeLookup: context.dataTypes.lookup
|
|
2462
|
+
}),
|
|
2463
|
+
models,
|
|
2464
|
+
byCoordinate,
|
|
2465
|
+
variants: new Map(models.map((entry) => [entry, variantInfo(entry, byCoordinate)])),
|
|
2466
|
+
relationsByModel: byModel,
|
|
2467
|
+
pinned: resolvePinnedRelations(relations, byModel),
|
|
2468
|
+
executionDefaults: executionDefaultsByColumn(contract),
|
|
2469
|
+
defaultDomainEnums,
|
|
2470
|
+
domainEnumValues: new Map(Object.entries(defaultDomainEnums).map(([name, domainEnum]) => [name, domainEnum.members.map((member) => member.value)]))
|
|
2471
|
+
};
|
|
2472
|
+
const namespaces = [];
|
|
2473
|
+
refuseEnumsOutsideDefaultNamespace(contract);
|
|
2474
|
+
const topLevelEnums = buildDomainEnumBlocks(defaultDomainEnums);
|
|
2475
|
+
if (topLevelEnums.length > 0) namespaces.push(makePslNamespace({
|
|
2476
|
+
kind: "namespace",
|
|
2477
|
+
name: UNSPECIFIED_PSL_NAMESPACE_ID,
|
|
2478
|
+
entries: makePslNamespaceEntries([], [], topLevelEnums),
|
|
2479
|
+
span: SYNTHETIC_SPAN
|
|
2480
|
+
}));
|
|
2481
|
+
const writtenStorageNamespaces = /* @__PURE__ */ new Set();
|
|
2482
|
+
for (const [namespaceId, namespace] of Object.entries(contract.storage.namespaces)) {
|
|
2483
|
+
const built = buildNamespace(all, namespaceId, namespace);
|
|
2484
|
+
if (built === void 0) continue;
|
|
2485
|
+
writtenStorageNamespaces.add(namespaceId);
|
|
2486
|
+
namespaces.push(built);
|
|
2487
|
+
}
|
|
2488
|
+
refuseUnmodelledTablesAndColumns(contract, models, all.variants);
|
|
2489
|
+
refuseUnwrittenNamespaces({
|
|
2490
|
+
contract,
|
|
2491
|
+
models,
|
|
2492
|
+
writtenStorageNamespaces
|
|
2493
|
+
});
|
|
2494
|
+
refuseContractMeta(contract);
|
|
2495
|
+
refuseUnderivedRoots(contract, models, all.variants);
|
|
2496
|
+
return {
|
|
2497
|
+
kind: "document",
|
|
2498
|
+
sourceId: "<contract>",
|
|
2499
|
+
namespaces,
|
|
2500
|
+
...ifDefined("types", buildTypesBlock(contract, all.inferredConstructors, context)),
|
|
2501
|
+
span: SYNTHETIC_SPAN
|
|
2502
|
+
};
|
|
2503
|
+
}
|
|
2504
|
+
function createPostgresTargetDescriptor() {
|
|
2505
|
+
setFallbackTemporal(Temporal);
|
|
2506
|
+
return {
|
|
2507
|
+
...postgresTargetDescriptorMeta,
|
|
2508
|
+
contractSerializer: new PostgresContractSerializer(),
|
|
2509
|
+
schemaVerifier: new PostgresSchemaVerifier(),
|
|
2510
|
+
inferPslContract(schema, context, describedContracts) {
|
|
2511
|
+
PostgresDatabaseSchemaNode.assert(schema);
|
|
2512
|
+
return inferPostgresPslContract(schema, context, describedContracts);
|
|
2513
|
+
},
|
|
2514
|
+
buildPslContract(contract, context) {
|
|
2515
|
+
return buildPostgresPslContract(contract, context);
|
|
2516
|
+
},
|
|
2517
|
+
diffSchema(input) {
|
|
2518
|
+
return diffPostgresSchema(input);
|
|
2519
|
+
},
|
|
2520
|
+
classifySubjectGranularity: postgresDiffSubjectGranularity,
|
|
2521
|
+
classifyEntityKind: postgresDiffSubjectEntityKind,
|
|
2522
|
+
migrations: {
|
|
2523
|
+
createPlanner(adapter) {
|
|
2524
|
+
return createPostgresMigrationPlanner(adapter);
|
|
2525
|
+
},
|
|
2526
|
+
createRunner(family) {
|
|
2527
|
+
return blindCast(createPostgresMigrationRunner(family));
|
|
2528
|
+
},
|
|
2529
|
+
contractToSchema(contract, frameworkComponents) {
|
|
2530
|
+
return postgresContractToSchema(contract, frameworkComponents);
|
|
2531
|
+
}
|
|
2532
|
+
},
|
|
2533
|
+
create() {
|
|
2534
|
+
return {
|
|
2535
|
+
familyId: "sql",
|
|
2536
|
+
targetId: "postgres"
|
|
2537
|
+
};
|
|
2538
|
+
},
|
|
2539
|
+
/**
|
|
2540
|
+
* Direct method for SQL-specific usage.
|
|
2541
|
+
* @deprecated Use migrations.createPlanner() for CLI compatibility.
|
|
2542
|
+
*/
|
|
2543
|
+
createPlanner(adapter) {
|
|
2544
|
+
return createPostgresMigrationPlanner(adapter);
|
|
2545
|
+
},
|
|
2546
|
+
/**
|
|
2547
|
+
* Direct method for SQL-specific usage.
|
|
2548
|
+
* @deprecated Use migrations.createRunner() for CLI compatibility.
|
|
2549
|
+
*/
|
|
2550
|
+
createRunner(family) {
|
|
2551
|
+
return createPostgresMigrationRunner(family);
|
|
2552
|
+
}
|
|
2553
|
+
};
|
|
2554
|
+
}
|
|
2555
|
+
const postgresTargetDescriptor = createPostgresTargetDescriptor();
|
|
2556
|
+
//#endregion
|
|
4
2557
|
export { decodePostgresListText, postgresTargetDescriptor as default, parsePostgresListText, postgresNativeAuthoringTypes, postgresNowGeneratorControlDescriptors, postgresPslTypeConstructors, postgresScalarAuthoringTypes };
|
|
2558
|
+
|
|
2559
|
+
//# sourceMappingURL=target__control.mjs.map
|