@prisma/orm-target-postgres 8.0.0-rc.12-dev.14 → 8.0.0-rc.12-dev.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/adapter__control.mjs +1 -1
  2. package/dist/adapter__runtime.mjs +1 -1
  3. package/dist/{authoring-gAs7Qz2A-BCHfYhEb.mjs → authoring-CSC0-DjI-CA5cgVmB.mjs} +55 -35
  4. package/dist/authoring-CSC0-DjI-CA5cgVmB.mjs.map +1 -0
  5. package/dist/control-CX9tMnuS.mjs +2350 -0
  6. package/dist/control-CX9tMnuS.mjs.map +1 -0
  7. package/dist/{descriptor-meta-BRzQLmGR-DZdNDAF6.mjs → descriptor-meta--zYVau3w-D-q8Cvf0.mjs} +3 -3
  8. package/dist/{descriptor-meta-BRzQLmGR-DZdNDAF6.mjs.map → descriptor-meta--zYVau3w-D-q8Cvf0.mjs.map} +1 -1
  9. package/dist/{errors-BcF1S3mV.d.mts → errors-1AjGQf6h.d.mts} +2 -2
  10. package/dist/{errors-BcF1S3mV.d.mts.map → errors-1AjGQf6h.d.mts.map} +1 -1
  11. package/dist/{infer-psl-contract-B9Hs0kKm-Cp7_uC0O.mjs → infer-psl-contract-DEHd6IMV-D1FmIxJC.mjs} +281 -277
  12. package/dist/infer-psl-contract-DEHd6IMV-D1FmIxJC.mjs.map +1 -0
  13. package/dist/migration-PTHAY9Cv.mjs.map +1 -1
  14. package/dist/{planner-CN7-lNRC-CN5OYpcD.mjs → planner-BAhxnFCn-0tAyr8zp.mjs} +3 -3
  15. package/dist/{planner-CN7-lNRC-CN5OYpcD.mjs.map → planner-BAhxnFCn-0tAyr8zp.mjs.map} +1 -1
  16. package/dist/{planner-produced-postgres-migration-Y5yqsSV--CyoG8l1n.mjs → planner-produced-postgres-migration-Ceuww3Cw-CMC3g395.mjs} +3 -3
  17. package/dist/{planner-produced-postgres-migration-Y5yqsSV--CyoG8l1n.mjs.map → planner-produced-postgres-migration-Ceuww3Cw-CMC3g395.mjs.map} +1 -1
  18. package/dist/{postgres-contract-view-CL1U38XC-CNK0yKEU.mjs → postgres-contract-view-BTNJukLn-QzZysnih.mjs} +3 -3
  19. package/dist/{postgres-contract-view-CL1U38XC-CNK0yKEU.mjs.map → postgres-contract-view-BTNJukLn-QzZysnih.mjs.map} +1 -1
  20. package/dist/{postgres-migration-C0CAQVCb-Blv2u1yN.mjs → postgres-migration-4s6yFwMP-lBYUEAjj.mjs} +3 -3
  21. package/dist/{postgres-migration-C0CAQVCb-Blv2u1yN.mjs.map → postgres-migration-4s6yFwMP-lBYUEAjj.mjs.map} +1 -1
  22. package/dist/{prisma7-binding-4hwKqLeu.mjs → prisma7-binding-aUk4pSUA.mjs} +4 -4
  23. package/dist/{prisma7-binding-4hwKqLeu.mjs.map → prisma7-binding-aUk4pSUA.mjs.map} +1 -1
  24. package/dist/target.d.mts +1 -1
  25. package/dist/target.mjs +7 -7
  26. package/dist/target__control.mjs +2 -2
  27. package/dist/target__errors.d.mts +1 -1
  28. package/dist/target__migration.mjs +1 -1
  29. package/dist/target__pack.mjs +1 -1
  30. package/dist/target__planner-produced-postgres-migration.mjs +1 -1
  31. package/dist/target__planner.mjs +1 -1
  32. package/dist/target__prisma7-binding.mjs +1 -1
  33. package/dist/target__runtime.mjs +2 -2
  34. package/dist/target__runtime.mjs.map +1 -1
  35. package/package.json +9 -9
  36. package/dist/authoring-gAs7Qz2A-BCHfYhEb.mjs.map +0 -1
  37. package/dist/control-DfIG6CQ9.mjs +0 -470
  38. package/dist/control-DfIG6CQ9.mjs.map +0 -1
  39. package/dist/infer-psl-contract-B9Hs0kKm-Cp7_uC0O.mjs.map +0 -1
@@ -0,0 +1,2350 @@
1
+ import { C as PG_TIMESTAMPTZ_DATE_CODEC_ID, D as PG_TIMESTAMP_TEMPORAL_CODEC_ID, E as PG_TIMESTAMP_STRING_CODEC_ID, S as PG_TEXT_CODEC_ID, T as PG_TIMESTAMPTZ_TEMPORAL_CODEC_ID, s as PG_ENUM_CODEC_ID, w as PG_TIMESTAMPTZ_STRING_CODEC_ID } from "./codec-ids-Cb0yO-IS--e0P2rfI.mjs";
2
+ import { i as isPostgresCodecDescriptor } from "./codec-descriptor-BfoHQP3R-CMRVT-F6.mjs";
3
+ import { s as postgresError } from "./errors-DYyzTYzE-39CV_aMo.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 { i as PostgresRlsPolicy, n as PostgresRlsEnablement, o as PostgresRole } from "./postgres-schema-MIh_qSUu-gKCH4OhS.mjs";
7
+ import { n as postgresResolveDefault } from "./default-normalizer-Coo-llj4-6YPzp_F9.mjs";
8
+ import { n as computeContentHash } from "./canonicalize-CrN3u_xM-D4MrOqcB.mjs";
9
+ import { m as postgresNowGeneratorIdFor, r as POLICY_BLOCK_KEYWORDS } from "./authoring-CSC0-DjI-CA5cgVmB.mjs";
10
+ import { t as postgresRenderCheckExpressions } from "./check-expressions-DLCs-SXx-itMQrUsX.mjs";
11
+ import { t as postgresTargetDescriptorMeta } from "./descriptor-meta--zYVau3w-D-q8Cvf0.mjs";
12
+ import { a as postgresDiffSubjectGranularity, i as postgresDiffSubjectEntityKind } from "./postgres-table-schema-node-BBkitBQh-DT1T5VWU.mjs";
13
+ import { t as PostgresDatabaseSchemaNode } from "./postgres-role-schema-node-B8Z5i5D--PObwlU2Z.mjs";
14
+ import { r as renderDefaultLiteral } from "./planner-ddl-builders-BncbM2oU-DR8NvtdY.mjs";
15
+ import { n as contractToPostgresDatabaseSchemaNode, r as diffPostgresSchema } from "./diff-database-schema--xSPI5GK-B3mQXFbC.mjs";
16
+ import { t as PostgresContractSerializer } from "./postgres-contract-view-BTNJukLn-QzZysnih.mjs";
17
+ import { t as createPostgresMigrationPlanner } from "./planner-BAhxnFCn-0tAyr8zp.mjs";
18
+ import { a as buildMapAttribute, d as inferPostgresPslContract, f as namedArg, i as buildIndexAttribute, m as positionalArg, n as buildAttribute, o as buildModelConstraintAttribute, p as parseDefaultAttributeString, r as buildCheckAttribute, s as buildNativeEnumBlock, t as SYNTHETIC_SPAN, u as createPostgresTypeMap } from "./infer-psl-contract-DEHd6IMV-D1FmIxJC.mjs";
19
+ import { escapePslString } from "@prisma/orm-family-sql/relational-core/ast";
20
+ import { blindCast } from "@prisma/orm-framework/utils/casts";
21
+ import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
22
+ import { StorageColumn } from "@prisma/orm-family-sql/contract/types";
23
+ import { ifDefined } from "@prisma/orm-framework/utils/defined";
24
+ import { composeCheckWirePrefix, computeCheckContentHash, computeIndexContentHash, formatWireName } from "@prisma/orm-family-sql/schema-ir/naming";
25
+ import { assertDefined, invariant } from "@prisma/orm-framework/utils/assertions";
26
+ import { APP_SPACE_ID } from "@prisma/orm-framework/components/control";
27
+ import { buildNativeTypeExpander, runnerFailure, runnerSuccess } from "@prisma/orm-family-sql/family/control";
28
+ import { findAuthoringTypeConstructorCall } from "@prisma/orm-framework/components/authoring";
29
+ import { NAME_THE_PSL_SOURCE_LOSES, isPslIdentifier } from "@prisma/orm-framework/psl-parser";
30
+ import { InternalError } from "@prisma/orm-framework/utils/internal-error";
31
+ import { notOk, ok, okVoid } from "@prisma/orm-framework/utils/result";
32
+ import { SqlSchemaVerifierBase } from "@prisma/orm-family-sql/family/ir";
33
+ import { UNBOUND_PSL_NAMESPACE_NAME, UNSPECIFIED_PSL_NAMESPACE_ID, makePslNamespace, makePslNamespaceEntries } from "@prisma/orm-framework/components/psl-ast";
34
+ import { mapDefault } from "@prisma/orm-family-sql/family/psl-build";
35
+ import { effectiveControlPolicy } from "@prisma/orm-framework/contract/types";
36
+ import { SqlQueryError } from "@prisma/orm-family-sql/errors";
37
+ import { canonicalizeJson } from "@prisma/orm-framework/components/utils";
38
+ import { pslFieldMapName, pslModelMapName } from "@prisma/orm-family-sql/contract-psl/map-names";
39
+ //#region ../../../3-targets/3-targets/postgres/dist/control.mjs
40
+ const LOCK_DOMAIN = "prisma_8.contract.marker";
41
+ /**
42
+ * Deep clones and freezes a record object to prevent mutation.
43
+ * Recursively clones nested objects and arrays to ensure complete isolation.
44
+ */
45
+ function cloneAndFreezeRecord(value) {
46
+ const cloned = {};
47
+ for (const [key, val] of Object.entries(value)) if (val === null || val === void 0) cloned[key] = val;
48
+ else if (Array.isArray(val)) cloned[key] = Object.freeze([...val]);
49
+ else if (typeof val === "object") cloned[key] = cloneAndFreezeRecord(blindCast(val));
50
+ else cloned[key] = val;
51
+ return blindCast(Object.freeze(cloned));
52
+ }
53
+ function createPostgresMigrationRunner(family) {
54
+ return new PostgresMigrationRunner(family);
55
+ }
56
+ var PostgresMigrationRunner = class {
57
+ family;
58
+ constructor(family) {
59
+ this.family = family;
60
+ }
61
+ /**
62
+ * Body of the migration runner without transaction management. The
63
+ * caller ({@link PostgresMigrationRunner.execute}) owns the
64
+ * `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.
65
+ */
66
+ async executeOnConnection(options) {
67
+ const schema = options.schemaName ?? Object.keys(options.destinationContract.storage.namespaces).find((id) => id !== UNBOUND_NAMESPACE_ID) ?? UNBOUND_NAMESPACE_ID;
68
+ const driver = options.driver;
69
+ 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: {
70
+ space: options.space,
71
+ planSpaceId: options.plan.spaceId
72
+ } });
73
+ const space = options.plan.spaceId;
74
+ const lockKey = `${LOCK_DOMAIN}:${schema}:${space}`;
75
+ const planOps = blindCast(await Promise.all(options.plan.operations));
76
+ const destinationCheck = this.ensurePlanMatchesDestinationContract(options.plan.destination, options.destinationContract);
77
+ if (!destinationCheck.ok) return destinationCheck;
78
+ const policyCheck = this.enforcePolicyCompatibility(options.policy, planOps);
79
+ if (!policyCheck.ok) return policyCheck;
80
+ await this.acquireLock(driver, lockKey);
81
+ const ensureResult = await this.ensureControlTables(driver, options.destinationContract);
82
+ if (!ensureResult.ok) return ensureResult;
83
+ const existingMarker = await this.family.readMarker({
84
+ driver,
85
+ space
86
+ });
87
+ const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);
88
+ if (!markerCheck.ok) return markerCheck;
89
+ const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);
90
+ const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;
91
+ const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;
92
+ let applyValue;
93
+ if (skipOperations) applyValue = {
94
+ operationsExecuted: 0,
95
+ executedOperations: []
96
+ };
97
+ else {
98
+ const applyResult = await this.applyPlan(driver, options, planOps);
99
+ if (!applyResult.ok) return applyResult;
100
+ applyValue = applyResult.value;
101
+ }
102
+ if (space === APP_SPACE_ID) {
103
+ const schemaNode = await this.family.introspect({
104
+ driver,
105
+ contract: options.destinationContract
106
+ });
107
+ const schemaVerifyResult = this.family.verifySchema({
108
+ contract: options.destinationContract,
109
+ schema: schemaNode,
110
+ strict: options.strictVerification ?? true,
111
+ frameworkComponents: options.frameworkComponents
112
+ });
113
+ if (!schemaVerifyResult.ok) return runnerFailure("MIGRATION.SCHEMA_VERIFY_FAILED", schemaVerifyResult.summary, {
114
+ why: "The resulting database schema does not satisfy the destination contract.",
115
+ meta: { issues: schemaVerifyResult.schema.issues }
116
+ });
117
+ }
118
+ const incomingInvariants = options.plan.providedInvariants ?? [];
119
+ const existingInvariants = new Set(existingMarker?.invariants ?? []);
120
+ const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));
121
+ if (!(isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting)) {
122
+ const markerResult = await this.upsertMarker(driver, options, existingMarker, space);
123
+ if (!markerResult.ok) return markerResult;
124
+ await this.recordLedgerEntries(driver, options, applyValue.executedOperations, planOps.length);
125
+ }
126
+ return runnerSuccess({
127
+ operationsPlanned: planOps.length,
128
+ operationsExecuted: applyValue.operationsExecuted
129
+ });
130
+ }
131
+ async execute(options) {
132
+ const driver = options.driver;
133
+ const perSpaceOptions = options.perSpaceOptions;
134
+ if (perSpaceOptions.length === 0) return ok({ perSpaceResults: [] });
135
+ await this.beginTransaction(driver);
136
+ let committed = false;
137
+ try {
138
+ const perSpaceResults = [];
139
+ for (const spaceOptions of perSpaceOptions) {
140
+ const space = spaceOptions.space ?? spaceOptions.plan.spaceId;
141
+ const result = await this.executeOnConnection({
142
+ ...spaceOptions,
143
+ driver,
144
+ space
145
+ });
146
+ if (!result.ok) return notOk({
147
+ ...result.failure,
148
+ failingSpace: space
149
+ });
150
+ perSpaceResults.push({
151
+ space,
152
+ value: result.value
153
+ });
154
+ }
155
+ await this.commitTransaction(driver);
156
+ committed = true;
157
+ return ok({ perSpaceResults });
158
+ } finally {
159
+ if (!committed) await this.rollbackTransaction(driver);
160
+ }
161
+ }
162
+ async applyPlan(driver, options, ops) {
163
+ const checks = options.executionChecks;
164
+ const runPrechecks = checks?.prechecks !== false;
165
+ const runPostchecks = checks?.postchecks !== false;
166
+ const runIdempotency = checks?.idempotencyChecks !== false;
167
+ let operationsExecuted = 0;
168
+ const executedOperations = [];
169
+ for (const operation of ops) {
170
+ options.callbacks?.onOperationStart?.(operation);
171
+ try {
172
+ if (runPostchecks && runIdempotency) {
173
+ if (await this.expectationsAreSatisfied(driver, operation.postcheck)) {
174
+ executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));
175
+ continue;
176
+ }
177
+ }
178
+ if (runPrechecks) {
179
+ const precheckResult = await this.runExpectationSteps(driver, operation.precheck, operation, "precheck");
180
+ if (!precheckResult.ok) return precheckResult;
181
+ }
182
+ const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);
183
+ if (!executeResult.ok) return executeResult;
184
+ if (runPostchecks) {
185
+ const postcheckResult = await this.runExpectationSteps(driver, operation.postcheck, operation, "postcheck");
186
+ if (!postcheckResult.ok) return postcheckResult;
187
+ }
188
+ executedOperations.push(operation);
189
+ operationsExecuted += 1;
190
+ } finally {
191
+ options.callbacks?.onOperationComplete?.(operation);
192
+ }
193
+ }
194
+ return ok({
195
+ operationsExecuted,
196
+ executedOperations
197
+ });
198
+ }
199
+ async ensureControlTables(driver, contract) {
200
+ const lowererContext = { contract };
201
+ const [schemaQuery, ...tableQueries] = this.family.bootstrapControlTableQueries();
202
+ if (schemaQuery === void 0) throw new InternalError("Postgres control-table bootstrap must include CREATE SCHEMA");
203
+ await this.executeStatement(driver, await this.family.lowerAst(schemaQuery, lowererContext));
204
+ const legacyDetection = await this.detectLegacyMarkerShape(driver);
205
+ if (!legacyDetection.ok) return legacyDetection;
206
+ for (const query of tableQueries) await this.executeStatement(driver, await this.family.lowerAst(query, lowererContext));
207
+ return okVoid();
208
+ }
209
+ async detectLegacyMarkerShape(driver) {
210
+ const result = await driver.query(`select column_name
211
+ from information_schema.columns
212
+ where table_schema = 'prisma_contract'
213
+ and table_name = 'marker'`);
214
+ if (result.rows.length === 0) return okVoid();
215
+ const columns = new Set(result.rows.map((row) => row.column_name));
216
+ if (columns.has("space")) return okVoid();
217
+ return runnerFailure("MIGRATION.LEGACY_MARKER_SHAPE", "Legacy marker-table shape detected on prisma_contract.marker (no `space` column). Prisma 8 is in pre-1.0; the previous transitional auto-migration to the per-space-row schema has been removed. Drop `prisma_contract.marker` and re-run `dbInit` to reinitialise from a clean baseline.", { meta: {
218
+ table: "prisma_contract.marker",
219
+ columns: [...columns].sort()
220
+ } });
221
+ }
222
+ async runExpectationSteps(driver, steps, operation, phase) {
223
+ for (const step of steps) {
224
+ const result = await driver.query(step.sql, step.params ?? []);
225
+ if (!this.stepResultIsTrue(result.rows)) return runnerFailure(phase === "precheck" ? "MIGRATION.PRECHECK_FAILED" : "MIGRATION.POSTCHECK_FAILED", `Operation ${operation.id} failed during ${phase}: ${step.description}`, { meta: {
226
+ operationId: operation.id,
227
+ phase,
228
+ stepDescription: step.description
229
+ } });
230
+ }
231
+ return okVoid();
232
+ }
233
+ async runExecuteSteps(driver, steps, operation) {
234
+ for (const step of steps) try {
235
+ await driver.query(step.sql, step.params ?? []);
236
+ } catch (error) {
237
+ if (SqlQueryError.is(error)) return runnerFailure("MIGRATION.EXECUTION_FAILED", `Operation ${operation.id} failed during execution: ${step.description}`, {
238
+ why: error.message,
239
+ meta: {
240
+ operationId: operation.id,
241
+ stepDescription: step.description,
242
+ sql: step.sql,
243
+ sqlState: error.sqlState,
244
+ constraint: error.constraint,
245
+ table: error.table,
246
+ column: error.column,
247
+ detail: error.detail
248
+ }
249
+ });
250
+ throw error;
251
+ }
252
+ return okVoid();
253
+ }
254
+ stepResultIsTrue(rows) {
255
+ if (!rows || rows.length === 0) return false;
256
+ const firstRow = rows[0];
257
+ const firstValue = firstRow ? Object.values(firstRow)[0] : void 0;
258
+ if (typeof firstValue === "boolean") return firstValue;
259
+ if (typeof firstValue === "number") return firstValue !== 0;
260
+ if (typeof firstValue === "string") {
261
+ const lower = firstValue.toLowerCase();
262
+ if (lower === "t" || lower === "true" || lower === "1") return true;
263
+ if (lower === "f" || lower === "false" || lower === "0") return false;
264
+ return firstValue.length > 0;
265
+ }
266
+ return Boolean(firstValue);
267
+ }
268
+ async expectationsAreSatisfied(driver, steps) {
269
+ if (steps.length === 0) return false;
270
+ for (const step of steps) {
271
+ const result = await driver.query(step.sql, step.params ?? []);
272
+ if (!this.stepResultIsTrue(result.rows)) return false;
273
+ }
274
+ return true;
275
+ }
276
+ createPostcheckPreSatisfiedSkipRecord(operation) {
277
+ const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : void 0;
278
+ const runnerMeta = Object.freeze({
279
+ skipped: true,
280
+ reason: "postcheck_pre_satisfied"
281
+ });
282
+ const mergedMeta = Object.freeze({
283
+ ...clonedMeta ?? {},
284
+ runner: runnerMeta
285
+ });
286
+ const frozenPostcheck = Object.freeze([...operation.postcheck]);
287
+ return Object.freeze({
288
+ id: operation.id,
289
+ label: operation.label,
290
+ ...ifDefined("summary", operation.summary),
291
+ operationClass: operation.operationClass,
292
+ target: operation.target,
293
+ precheck: Object.freeze([]),
294
+ execute: Object.freeze([]),
295
+ postcheck: frozenPostcheck,
296
+ ...ifDefined("meta", operation.meta || mergedMeta ? mergedMeta : void 0)
297
+ });
298
+ }
299
+ markerMatchesDestination(marker, plan) {
300
+ if (!marker) return false;
301
+ if (marker.storageHash !== plan.destination.storageHash) return false;
302
+ if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) return false;
303
+ return true;
304
+ }
305
+ enforcePolicyCompatibility(policy, operations) {
306
+ const allowedClasses = new Set(policy.allowedOperationClasses);
307
+ 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.`, {
308
+ why: `Policy only allows: ${policy.allowedOperationClasses.join(", ")}.`,
309
+ meta: {
310
+ operationId: operation.id,
311
+ operationClass: operation.operationClass,
312
+ allowedClasses: policy.allowedOperationClasses
313
+ }
314
+ });
315
+ return okVoid();
316
+ }
317
+ ensureMarkerCompatibility(marker, plan) {
318
+ const origin = plan.origin ?? null;
319
+ if (!origin) return okVoid();
320
+ if (!marker) return runnerFailure("MIGRATION.MARKER_ORIGIN_MISMATCH", `Missing contract marker: expected origin storage hash ${origin.storageHash}.`, { meta: { expectedOriginStorageHash: origin.storageHash } });
321
+ if (marker.storageHash !== origin.storageHash) return runnerFailure("MIGRATION.MARKER_ORIGIN_MISMATCH", `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`, { meta: {
322
+ markerStorageHash: marker.storageHash,
323
+ expectedOriginStorageHash: origin.storageHash
324
+ } });
325
+ 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: {
326
+ markerProfileHash: marker.profileHash,
327
+ expectedOriginProfileHash: origin.profileHash
328
+ } });
329
+ return okVoid();
330
+ }
331
+ ensurePlanMatchesDestinationContract(destination, contract) {
332
+ 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: {
333
+ planStorageHash: destination.storageHash,
334
+ contractStorageHash: contract.storage.storageHash
335
+ } });
336
+ 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: {
337
+ planProfileHash: destination.profileHash,
338
+ contractProfileHash: contract.profileHash
339
+ } });
340
+ return okVoid();
341
+ }
342
+ async upsertMarker(driver, options, existingMarker, space) {
343
+ const destination = {
344
+ storageHash: options.plan.destination.storageHash,
345
+ profileHash: options.plan.destination.profileHash ?? options.destinationContract.profileHash ?? options.plan.destination.storageHash,
346
+ invariants: options.plan.providedInvariants ?? []
347
+ };
348
+ if (!existingMarker) {
349
+ await this.family.initMarker({
350
+ driver,
351
+ space,
352
+ destination
353
+ });
354
+ return okVoid();
355
+ }
356
+ if (!await this.family.updateMarker({
357
+ driver,
358
+ space,
359
+ expectedFrom: existingMarker.storageHash,
360
+ destination
361
+ })) return runnerFailure("MIGRATION.MARKER_CAS_FAILURE", "Marker was modified by another process during migration execution.", { meta: {
362
+ space,
363
+ expectedStorageHash: existingMarker.storageHash,
364
+ destinationStorageHash: options.plan.destination.storageHash
365
+ } });
366
+ return okVoid();
367
+ }
368
+ async recordLedgerEntries(driver, options, executedOperations, planOpsLength) {
369
+ const space = options.plan.spaceId;
370
+ const edges = options.migrationEdges;
371
+ const totalEdgeOps = edges.reduce((sum, edge) => sum + edge.operationCount, 0);
372
+ if (totalEdgeOps !== planOpsLength) throw new InternalError(`Ledger write: plan.operations length (${planOpsLength}) does not match sum of migrationEdges operationCount (${totalEdgeOps})`);
373
+ let offset = 0;
374
+ for (const edge of edges) {
375
+ const edgeOps = executedOperations.slice(offset, offset + edge.operationCount);
376
+ offset += edge.operationCount;
377
+ await this.family.writeLedgerEntry({
378
+ driver,
379
+ space,
380
+ entry: {
381
+ edgeId: `${edge.from}->${edge.to}`,
382
+ from: edge.from,
383
+ to: edge.to,
384
+ migrationName: edge.dirName,
385
+ migrationHash: edge.migrationHash,
386
+ operations: edgeOps,
387
+ ...ifDefined("destinationContractJson", edge.destinationContractJson)
388
+ }
389
+ });
390
+ }
391
+ }
392
+ async acquireLock(driver, key) {
393
+ await driver.query("select pg_advisory_xact_lock(hashtext($1))", [key]);
394
+ }
395
+ async beginTransaction(driver) {
396
+ await driver.query("BEGIN");
397
+ }
398
+ async commitTransaction(driver) {
399
+ await driver.query("COMMIT");
400
+ }
401
+ async rollbackTransaction(driver) {
402
+ await driver.query("ROLLBACK");
403
+ }
404
+ async executeStatement(driver, statement) {
405
+ await driver.query(statement.sql, statement.params);
406
+ }
407
+ };
408
+ /**
409
+ * Postgres target `SchemaVerifier` concretion. Plugs into the
410
+ * SQL-shared verification surface; production verification today still
411
+ * routes through the family verify verdict (`verifySqlSchemaByDiff` over
412
+ * `diffPostgresSchema`), which carries options (codec hooks,
413
+ * normalizers, framework components) that the framework-level
414
+ * `SchemaVerifyOptions` shape does not yet surface.
415
+ *
416
+ * The hooks return the empty list pending the call-site migration that
417
+ * routes the existing verifier behaviour through the SPI — at that
418
+ * point `verifyCommonSqlSchema` will likely lift onto the family base
419
+ * (mirroring `verifyCommonMongoSchema`) and `verifyTargetExtensions`
420
+ * will house Postgres-only kinds (functions, RLS policies in a future
421
+ * project).
422
+ */
423
+ var PostgresSchemaVerifier = class extends SqlSchemaVerifierBase {
424
+ verifyCommonSqlSchema(_options) {
425
+ return [];
426
+ }
427
+ verifyTargetExtensions(_options) {
428
+ return [];
429
+ }
430
+ };
431
+ /** The name a contract namespace is written under in PSL. */
432
+ function pslNamespaceName(namespaceId) {
433
+ return namespaceId === UNBOUND_NAMESPACE_ID ? UNBOUND_PSL_NAMESPACE_NAME : namespaceId;
434
+ }
435
+ function modelCoordinate(namespaceId, modelName) {
436
+ return JSON.stringify([namespaceId, modelName]);
437
+ }
438
+ /**
439
+ * Every domain model of the contract, in declaration order, with its storage table. Contract
440
+ * validation has checked that each model's table exists, in the namespace of the model.
441
+ */
442
+ function indexContractModels(contract) {
443
+ const entries = [];
444
+ for (const [namespaceId, domainNamespace] of Object.entries(contract.domain.namespaces)) for (const [name, model] of Object.entries(domainNamespace.models)) {
445
+ const storage = blindCast(model.storage);
446
+ const table = contract.storage.namespaces[storage.namespaceId]?.entries.table?.[storage.table];
447
+ assertDefined(table, `model "${namespaceId}.${name}" is stored in table "${storage.namespaceId}"."${storage.table}", which the storage does not declare`);
448
+ const fields = Object.entries(storage.fields);
449
+ entries.push({
450
+ namespaceId: storage.namespaceId,
451
+ name,
452
+ tableName: storage.table,
453
+ storage,
454
+ model,
455
+ table,
456
+ fieldNamesByColumn: new Map(fields.map(([fieldName, field]) => [field.column, fieldName])),
457
+ ownColumns: new Set(fields.map(([, field]) => field.column))
458
+ });
459
+ }
460
+ return entries;
461
+ }
462
+ /** Models keyed by their `(namespace, model)` coordinate. */
463
+ function modelsByCoordinate(entries) {
464
+ return new Map(entries.map((entry) => [modelCoordinate(entry.namespaceId, entry.name), entry]));
465
+ }
466
+ /** A cross reference's coordinate; one into another contract space never matches a model of this contract. */
467
+ function crossReferenceCoordinate(reference) {
468
+ return reference.space === void 0 ? modelCoordinate(reference.namespace, reference.model) : JSON.stringify([
469
+ reference.space,
470
+ reference.namespace,
471
+ reference.model
472
+ ]);
473
+ }
474
+ /** The base a variant model extends, with the discriminator value it is stored under. */
475
+ function variantInfo(entry, byCoordinate) {
476
+ if (entry.model.base === void 0) return void 0;
477
+ const base = byCoordinate.get(crossReferenceCoordinate(entry.model.base));
478
+ const value = base?.model.variants?.[entry.name]?.value;
479
+ assertDefined(base, `model "${entry.namespaceId}.${entry.name}" extends a base the contract does not declare`);
480
+ assertDefined(value, `model "${entry.namespaceId}.${entry.name}" extends base "${base.name}", which does not list it as a variant`);
481
+ return {
482
+ base,
483
+ value,
484
+ singleTable: base.namespaceId === entry.namespaceId && base.tableName === entry.tableName
485
+ };
486
+ }
487
+ /** The columns the PSL source adds to a multi-table variant's table: its base's primary key. */
488
+ function variantLinkColumns(entry, variant) {
489
+ if (variant === void 0 || variant.singleTable) return [];
490
+ return (variant.base.table.primaryKey?.columns ?? []).filter((column) => !entry.ownColumns.has(column));
491
+ }
492
+ /**
493
+ * The foreign key the PSL source synthesizes from a multi-table variant to its base: unnamed, over
494
+ * the base's primary key columns, cascading on delete.
495
+ */
496
+ function isVariantLinkForeignKey(fk, variant) {
497
+ if (variant === void 0 || variant.singleTable) return false;
498
+ const baseKey = canonicalizeJson(variant.base.table.primaryKey?.columns ?? []);
499
+ 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;
500
+ }
501
+ const KEEP_SOURCE = "Keep authoring this contract in its current source.";
502
+ function unsupported(message, why, fix, meta) {
503
+ return postgresError("CONTRACT.PRINT_UNSUPPORTED", `contract print: ${message}`, {
504
+ why,
505
+ fix,
506
+ meta
507
+ });
508
+ }
509
+ function sameJson(left, right) {
510
+ return canonicalizeJson(left) === canonicalizeJson(right);
511
+ }
512
+ function sameValues$1(left, right) {
513
+ return left.length === right.length && left.every((value, index) => value === right[index]);
514
+ }
515
+ function refuseColumnWithoutPslType(column, coordinate) {
516
+ throw unsupported(`column ${coordinate} has native type "${column.nativeType}" 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 native 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.", {
517
+ coordinate,
518
+ nativeType: column.nativeType,
519
+ codecId: column.codecId
520
+ });
521
+ }
522
+ /**
523
+ * Refuses a string type argument the PSL source would read back differently: it reads a string
524
+ * argument between its quotes as written, with no escapes.
525
+ */
526
+ function refuseUnwritableTypeArgument(value, coordinate) {
527
+ if (escapePslString(value) === value) return;
528
+ 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, {
529
+ coordinate,
530
+ argument: value
531
+ });
532
+ }
533
+ function refuseDefaultOutsideEnum(input) {
534
+ 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.", {
535
+ coordinate: input.coordinate,
536
+ pslTypeName: input.pslTypeName
537
+ });
538
+ }
539
+ function refuseUnwritableLiteralDefault(input) {
540
+ 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.", {
541
+ coordinate: input.coordinate,
542
+ pslTypeName: input.pslTypeName
543
+ });
544
+ }
545
+ function refuseNowGeneratorPairedWithAnother(phases) {
546
+ throw unsupported(`column ${phases.coordinate} takes the wall-clock-now generator in one phase and "${phases.other}" in the other, which cannot be written in Prisma 8 PSL.`, "The temporal preset a now generator is authored through writes each phase as `now`, so the other generator would be dropped from the written file.", KEEP_SOURCE, {
547
+ coordinate: phases.coordinate,
548
+ onCreate: phases.onCreate,
549
+ onUpdate: phases.onUpdate
550
+ });
551
+ }
552
+ function refuseGeneratorOnUpdate(phases) {
553
+ 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 temporal preset, which takes the wall-clock-now generator.", KEEP_SOURCE, {
554
+ coordinate: phases.coordinate,
555
+ onCreate: phases.onCreate,
556
+ onUpdate: phases.onUpdate
557
+ });
558
+ }
559
+ function refuseGeneratorWithoutPslFunction(phases) {
560
+ throw unsupported(`column ${phases.coordinate} is generated by "${phases.onCreate}", and the printer knows no PSL default function that produces it.`, "The printer writes each generator as the PSL default function of the Postgres adapter that produces it, and no such function produces this generator.", KEEP_SOURCE, {
561
+ coordinate: phases.coordinate,
562
+ onCreate: phases.onCreate,
563
+ onUpdate: phases.onUpdate
564
+ });
565
+ }
566
+ function refuseGeneratorWithDatabaseDefault(input) {
567
+ 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.", {
568
+ coordinate: input.coordinate,
569
+ onCreate: input.onCreate
570
+ });
571
+ }
572
+ /** Refuses a generated value the printer did not write with the field of its column. */
573
+ function refuseUnwrittenExecutionDefaults(contract, written) {
574
+ for (const entry of contract.execution?.mutations.defaults ?? []) {
575
+ if (written.has(entry)) continue;
576
+ const coordinate = `"${entry.ref.namespace}"."${entry.ref.entry}"."${entry.ref.field}"`;
577
+ throw unsupported(`a generated value names column ${coordinate}, which no field is stored in, so it cannot be written in Prisma 8 PSL.`, "PSL writes a generated value on the field stored in its column.", KEEP_SOURCE, { coordinate });
578
+ }
579
+ }
580
+ /**
581
+ * The value-set references the PSL source gives a field typed by a domain enum and its column: the
582
+ * column names the enum's value set, and a field that is not a list names the enum, both in the
583
+ * default namespace. A field with no domain enum has neither.
584
+ */
585
+ function derivedValueSetRefs(enumName, list) {
586
+ if (enumName === void 0) return {
587
+ field: void 0,
588
+ column: void 0
589
+ };
590
+ const common = {
591
+ namespaceId: DEFAULT_NAMESPACE_ID,
592
+ entityName: enumName
593
+ };
594
+ return {
595
+ field: list ? void 0 : {
596
+ plane: "domain",
597
+ entityKind: "enum",
598
+ ...common
599
+ },
600
+ column: {
601
+ plane: "storage",
602
+ entityKind: "valueSet",
603
+ ...common
604
+ }
605
+ };
606
+ }
607
+ /**
608
+ * Refuses a field whose column the PSL source would not derive from it: PSL writes the field once,
609
+ * and the PSL source derives the column's nullability, list marker, codec and type parameters from
610
+ * what is written.
611
+ */
612
+ function refuseFieldColumnMismatch(input) {
613
+ const { field, column, coordinate } = input;
614
+ const fix = "Make the field and its column agree, or keep authoring this contract in its current source.";
615
+ 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 });
616
+ 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 });
617
+ if ((field.type.kind === "scalar" && field.many === true) !== (column.many === true)) throw unsupported(`field ${coordinate} is ${field.many === true ? "a list" : "not a list"} but its column is ${column.many === true ? "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 });
618
+ if (field.type.kind === "scalar" && (field.type.codecId !== column.codecId || !sameJson(field.type.typeParams, column.typeParams))) 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.", fix, { coordinate });
619
+ if (field.type.kind !== "scalar" || column.codecId === "pg/enum@1") return;
620
+ const enumName = column.valueSet?.entityName;
621
+ const derived = derivedValueSetRefs(enumName, field.many === true);
622
+ if (!sameJson(field.valueSet, derived.field) || !sameJson(column.valueSet, derived.column) || 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 a field that is not a list at the enum.", fix, { coordinate });
623
+ }
624
+ /**
625
+ * Refuses a field PSL has no form for: one whose type is a union of types, or one that is a
626
+ * dictionary. Runs for model fields and value-object fields alike.
627
+ */
628
+ function refuseUnwritableFieldShape(field, coordinate) {
629
+ 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.", {
630
+ coordinate,
631
+ kind: field.type.kind
632
+ });
633
+ if (field.dict !== true) return;
634
+ 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 });
635
+ }
636
+ /**
637
+ * Refuses a value-object field with type parameters or a value set: the PSL source keeps only the
638
+ * codec of a value-object field's type, so either would be lost.
639
+ */
640
+ function refuseValueObjectFieldPartsTheSourceDrops(field, coordinate) {
641
+ if (Object.keys(field.type.typeParams ?? {}).length === 0 && field.valueSet === void 0) return;
642
+ throw unsupported(`value-object field ${coordinate} carries type parameters or a value set, which cannot be written in Prisma 8 PSL.`, "The PSL source keeps only the codec of a value-object field's type, so its type parameters and value set would be lost.", KEEP_SOURCE, { coordinate });
643
+ }
644
+ function refuseValueObjectFieldCodecWithoutNativeType(codecId, coordinate) {
645
+ throw unsupported(`field ${coordinate} uses codec "${codecId}", which no Postgres codec in the configured stack names a native type for.`, "A value-object field has no storage column, so its PSL type is derived from the native type its codec names.", KEEP_SOURCE, {
646
+ coordinate,
647
+ codecId
648
+ });
649
+ }
650
+ function refuseValueObjectFieldCodecNeedingTypeParameters(codecId, coordinate) {
651
+ throw unsupported(`field ${coordinate} uses codec "${codecId}", which names a native type only from type parameters, and the PSL source keeps none on a value-object field.`, "The PSL source keeps only the codec of a value-object field's type, so a codec that needs type parameters cannot be written there.", KEEP_SOURCE, {
652
+ coordinate,
653
+ codecId
654
+ });
655
+ }
656
+ /** Refuses a model field its storage does not store in a column. */
657
+ function refuseFieldsWithoutColumn(entry) {
658
+ const storedFieldNames = new Set(Object.keys(entry.storage.fields));
659
+ for (const fieldName of Object.keys(entry.model.fields)) {
660
+ if (storedFieldNames.has(fieldName)) continue;
661
+ throw unsupported(`field "${entry.namespaceId}.${entry.name}.${fieldName}" is stored in no column, so it cannot be written in Prisma 8 PSL.`, "PSL declares a scalar or value-object field together with the column it is stored in.", "The contract source produced a field without storage. Fix the field if the source is a TypeScript contract; otherwise report the bug to the source that produced it.", {
662
+ namespaceId: entry.namespaceId,
663
+ modelName: entry.name,
664
+ field: fieldName
665
+ });
666
+ }
667
+ }
668
+ /** Refuses a column a model stores under a field name the model does not declare. */
669
+ function refuseStorageOfUndeclaredField(input) {
670
+ const { entry, fieldName } = input;
671
+ 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.", {
672
+ namespaceId: entry.namespaceId,
673
+ modelName: entry.name,
674
+ field: fieldName
675
+ });
676
+ }
677
+ /**
678
+ * Refuses a column typed by a named type when the contract declares no such type, or when the
679
+ * column's native type or codec is not the named type's. PSL writes the column as the name of the
680
+ * type, and the PSL source copies both from the named type.
681
+ */
682
+ function refuseColumnDifferingFromNamedType(input) {
683
+ const { column, typeRef, namedType, coordinate } = input;
684
+ if (namedType?.nativeType === column.nativeType && namedType.codecId === column.codecId) return;
685
+ 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 native 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 native type and codec of that named type.", "Make the column and its named type agree, or keep authoring this contract in its current source.", {
686
+ coordinate,
687
+ typeRef
688
+ });
689
+ }
690
+ function refuseColumnControl(column, coordinate) {
691
+ if (column.control === void 0) return;
692
+ 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.", {
693
+ coordinate,
694
+ control: column.control
695
+ });
696
+ }
697
+ /** Refuses a storage table no model is stored in, and a column no field or variant link stores. */
698
+ function refuseUnmodelledTablesAndColumns(contract, models, variants) {
699
+ const tableKey = (namespaceId, tableName) => JSON.stringify([namespaceId, tableName]);
700
+ const coveredColumns = /* @__PURE__ */ new Map();
701
+ for (const entry of models) {
702
+ const key = tableKey(entry.namespaceId, entry.tableName);
703
+ const columns = coveredColumns.get(key) ?? /* @__PURE__ */ new Set();
704
+ for (const column of entry.ownColumns) columns.add(column);
705
+ for (const column of variantLinkColumns(entry, variants.get(entry))) columns.add(column);
706
+ coveredColumns.set(key, columns);
707
+ }
708
+ for (const [namespaceId, namespace] of Object.entries(contract.storage.namespaces)) for (const [tableName, table] of Object.entries(namespace.entries.table ?? {})) {
709
+ const covered = coveredColumns.get(tableKey(namespaceId, tableName));
710
+ 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.", {
711
+ namespaceId,
712
+ table: tableName
713
+ });
714
+ for (const column of Object.keys(table.columns)) {
715
+ if (covered.has(column)) continue;
716
+ 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.", {
717
+ namespaceId,
718
+ table: tableName,
719
+ column
720
+ });
721
+ }
722
+ }
723
+ }
724
+ function refuseModelOwner(entry) {
725
+ if (entry.model.owner === void 0) return;
726
+ 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, {
727
+ namespaceId: entry.namespaceId,
728
+ modelName: entry.name,
729
+ owner: entry.model.owner
730
+ });
731
+ }
732
+ /**
733
+ * Refuses a multi-table variant whose link to its base differs from the one the PSL source derives:
734
+ * the base's primary key columns copied into the variant's table as its unnamed primary key, and
735
+ * the link foreign key.
736
+ */
737
+ function refuseUnderivedVariantLink(entry, variant) {
738
+ const baseKey = variant.base.table.primaryKey?.columns ?? [];
739
+ const derivedKey = baseKey.length === 0 ? void 0 : { columns: baseKey };
740
+ const linkColumnsMatch = variantLinkColumns(entry, variant).every((column) => {
741
+ const base = variant.base.table.columns[column];
742
+ const expected = base === void 0 ? void 0 : new StorageColumn({
743
+ nativeType: base.nativeType,
744
+ codecId: base.codecId,
745
+ nullable: false,
746
+ ...ifDefined("typeParams", base.typeParams),
747
+ ...ifDefined("typeRef", base.typeRef)
748
+ });
749
+ return sameJson(entry.table.columns[column], expected);
750
+ });
751
+ const linkForeignKeys = entry.table.foreignKeys.filter((fk) => isVariantLinkForeignKey(fk, variant));
752
+ if (linkColumnsMatch && sameJson(entry.table.primaryKey, derivedKey) && linkForeignKeys.length === (baseKey.length === 0 ? 0 : 1)) return;
753
+ 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, {
754
+ namespaceId: entry.namespaceId,
755
+ modelName: entry.name
756
+ });
757
+ }
758
+ /**
759
+ * The PSL source groups relations by bare model name, so two models with the same name in
760
+ * different namespaces would get each other's relations.
761
+ */
762
+ function refuseDuplicateModelNames(models) {
763
+ const namespacesByName = /* @__PURE__ */ new Map();
764
+ for (const entry of models) {
765
+ const namespaces = namespacesByName.get(entry.name) ?? [];
766
+ namespaces.push(entry.namespaceId);
767
+ namespacesByName.set(entry.name, namespaces);
768
+ }
769
+ for (const [name, namespaces] of namespacesByName) {
770
+ if (namespaces.length <= 1) continue;
771
+ 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.", {
772
+ modelName: name,
773
+ namespaces
774
+ });
775
+ }
776
+ }
777
+ /**
778
+ * A PSL `enum` block is declared at the top level and lands in the default namespace, so only the
779
+ * default namespace's domain enums have a PSL form.
780
+ */
781
+ function refuseEnumsOutsideDefaultNamespace(contract) {
782
+ for (const [namespaceId, domainNamespace] of Object.entries(contract.domain.namespaces)) {
783
+ const names = Object.keys(domainNamespace.enum ?? {});
784
+ if (namespaceId === "public" || names.length === 0) continue;
785
+ 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.", {
786
+ namespaceId,
787
+ names
788
+ });
789
+ }
790
+ }
791
+ /** The PSL source reads every `type` block into the default namespace. */
792
+ function refuseValueObjectsOutsideDefaultNamespace(contract, namespaceId) {
793
+ const names = Object.keys(contract.domain.namespaces[namespaceId]?.valueObjects ?? {});
794
+ if (namespaceId === "public" || names.length === 0) return;
795
+ 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.", {
796
+ namespaceId,
797
+ names
798
+ });
799
+ }
800
+ /**
801
+ * Refuses a check or index whose name is neither its prefix followed by the hash of its content,
802
+ * which `name:` derives, nor free of a prefix, which `map:` needs.
803
+ */
804
+ function refuseUnwritableObjectName(input) {
805
+ const { kind, entry, name, prefix } = input;
806
+ 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, {
807
+ namespaceId: entry.namespaceId,
808
+ table: entry.tableName,
809
+ name,
810
+ prefix
811
+ });
812
+ }
813
+ /**
814
+ * Refuses a table whose checks differ from the derived ones where they overlap: a derived check the
815
+ * table lacks, or a check with a derived check's name but not its prefix and expression. The PSL
816
+ * source adds the derived checks itself, so they are never written.
817
+ */
818
+ function refuseUnderivedChecks(entry, derived) {
819
+ const checks = new Map((entry.table.checks ?? []).map((check) => [check.name, check]));
820
+ for (const [name, expected] of derived) {
821
+ const check = checks.get(name);
822
+ if (check?.prefix === expected.prefix && check.expression === expected.expression) continue;
823
+ 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, unless the column waives it with `@noCheck`.", KEEP_SOURCE, {
824
+ namespaceId: entry.namespaceId,
825
+ table: entry.tableName,
826
+ name
827
+ });
828
+ }
829
+ }
830
+ /**
831
+ * Refuses index options PSL cannot write: `options:` takes string values under identifier keys,
832
+ * and requires a `type`.
833
+ */
834
+ function refuseUnwritableIndexOptions(entry, index) {
835
+ const meta = {
836
+ namespaceId: entry.namespaceId,
837
+ table: entry.tableName,
838
+ index: index.name
839
+ };
840
+ 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);
841
+ for (const [key, value] of Object.entries(index.options ?? {})) {
842
+ refuseUnwritableName("index option", key);
843
+ if (typeof value === "string") continue;
844
+ 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.", {
845
+ ...meta,
846
+ key
847
+ });
848
+ }
849
+ }
850
+ function refuseToOneRelationWithoutForeignKey(modelName, fieldName) {
851
+ 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.", {
852
+ model: modelName,
853
+ field: fieldName
854
+ });
855
+ }
856
+ /**
857
+ * A foreign key no relation travels has no PSL form: the PSL source derives every foreign key from
858
+ * a `@relation`, so this one would be lost.
859
+ */
860
+ function refuseUntravelledForeignKeys(entry, variant, travelled) {
861
+ for (const fk of entry.table.foreignKeys) {
862
+ if (travelled.has(fk) || isVariantLinkForeignKey(fk, variant)) continue;
863
+ if (variant?.singleTable === true && !fk.source.columns.every((c) => entry.ownColumns.has(c))) continue;
864
+ 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.", {
865
+ namespaceId: entry.namespaceId,
866
+ table: entry.tableName,
867
+ columns: fk.source.columns
868
+ });
869
+ }
870
+ }
871
+ function refuseRelationToOtherContractSpace(input) {
872
+ if (input.space === void 0) return;
873
+ 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, {
874
+ model: input.modelName,
875
+ field: input.fieldName,
876
+ space: input.space
877
+ });
878
+ }
879
+ function refuseManyToManyWithoutJunctionRelation(modelName, fieldName) {
880
+ 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.", {
881
+ model: modelName,
882
+ field: fieldName
883
+ });
884
+ }
885
+ function refuseBackRelationWithoutOwningRelation(input) {
886
+ 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.`, {
887
+ model: input.modelName,
888
+ field: input.fieldName
889
+ });
890
+ }
891
+ function refuseRelationWithoutJoin(modelName, fieldName) {
892
+ 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, {
893
+ model: modelName,
894
+ field: fieldName
895
+ });
896
+ }
897
+ /**
898
+ * Refuses a namespace whose value sets differ from the ones the PSL source derives from the enum
899
+ * and `native_enum` blocks the printer writes for it.
900
+ */
901
+ function refuseUnderivedValueSets(input) {
902
+ const { namespaceId } = input;
903
+ for (const [name, values] of input.actual) {
904
+ const derived = input.derived.get(name);
905
+ if (derived !== void 0 && sameValues$1(derived, values)) continue;
906
+ 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, {
907
+ namespaceId,
908
+ name
909
+ });
910
+ }
911
+ for (const name of input.derived.keys()) {
912
+ if (input.actual.has(name)) continue;
913
+ 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, {
914
+ namespaceId,
915
+ name
916
+ });
917
+ }
918
+ }
919
+ function refuseEnumAndNativeEnumSharingName(namespaceId, name) {
920
+ 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, {
921
+ namespaceId,
922
+ name
923
+ });
924
+ }
925
+ function refuseNativeEnumWithoutValueSet(namespaceId, nativeEnum) {
926
+ 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, {
927
+ namespaceId,
928
+ typeName: nativeEnum.typeName
929
+ });
930
+ }
931
+ function refuseNativeEnumControl(namespaceId, nativeEnum) {
932
+ if (nativeEnum.control === void 0) return;
933
+ 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.", {
934
+ namespaceId,
935
+ typeName: nativeEnum.typeName,
936
+ control: nativeEnum.control
937
+ });
938
+ }
939
+ /**
940
+ * Refuses a storage or domain namespace the PSL source would not create again: one holding nothing
941
+ * the printer writes. The PSL source creates the default namespace in both planes, a storage
942
+ * namespace for every namespace block it writes into, and a domain namespace for each namespace
943
+ * with models.
944
+ */
945
+ function refuseUnwrittenNamespaces(input) {
946
+ const { contract } = input;
947
+ const storageNamespaces = /* @__PURE__ */ new Set([DEFAULT_NAMESPACE_ID, ...input.writtenStorageNamespaces]);
948
+ const defaultDomain = contract.domain.namespaces[DEFAULT_NAMESPACE_ID];
949
+ const domainNamespaces = new Set(input.models.map((entry) => entry.namespaceId));
950
+ if (domainNamespaces.size === 0 || Object.keys(defaultDomain?.valueObjects ?? {}).length > 0 || Object.keys(defaultDomain?.enum ?? {}).length > 0) domainNamespaces.add(DEFAULT_NAMESPACE_ID);
951
+ const planes = [{
952
+ plane: "storage",
953
+ expected: storageNamespaces,
954
+ actual: Object.keys(contract.storage.namespaces)
955
+ }, {
956
+ plane: "domain",
957
+ expected: domainNamespaces,
958
+ actual: Object.keys(contract.domain.namespaces)
959
+ }];
960
+ for (const { plane, expected, actual } of planes) {
961
+ for (const namespaceId of actual) {
962
+ if (expected.has(namespaceId)) continue;
963
+ 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.", {
964
+ plane,
965
+ namespaceId
966
+ });
967
+ }
968
+ for (const namespaceId of expected) {
969
+ if (actual.includes(namespaceId)) continue;
970
+ 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, {
971
+ plane,
972
+ namespaceId
973
+ });
974
+ }
975
+ }
976
+ }
977
+ /**
978
+ * Refuses a namespace named `unbound` that is not the late-binding namespace: PSL writes the
979
+ * late-binding namespace as `namespace unbound`, so a block of that name reads back as it.
980
+ */
981
+ function refuseNamespaceNamedUnbound(namespaceId) {
982
+ if (namespaceId !== UNBOUND_PSL_NAMESPACE_NAME) return;
983
+ 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 });
984
+ }
985
+ /** Refuses top-level `meta` entries: the PSL source reads back an empty `meta`. */
986
+ function refuseContractMeta(contract) {
987
+ const keys = Object.keys(contract.meta);
988
+ if (keys.length === 0) return;
989
+ 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 });
990
+ }
991
+ /**
992
+ * Refuses roots that differ from the ones the PSL source derives: one per model that is not a
993
+ * variant, keyed by its table name, or by `<namespace>.<table>` when two such models share a table
994
+ * name.
995
+ */
996
+ function refuseUnderivedRoots(contract, models, variants) {
997
+ const tableEntries = models.filter((entry) => variants.get(entry)?.singleTable !== true);
998
+ const tableNameCounts = /* @__PURE__ */ new Map();
999
+ for (const entry of tableEntries) tableNameCounts.set(entry.tableName, (tableNameCounts.get(entry.tableName) ?? 0) + 1);
1000
+ const derived = /* @__PURE__ */ new Map();
1001
+ for (const entry of tableEntries) {
1002
+ if (variants.get(entry) !== void 0) continue;
1003
+ const key = (tableNameCounts.get(entry.tableName) ?? 0) > 1 ? `${entry.namespaceId}.${entry.tableName}` : entry.tableName;
1004
+ derived.set(key, entry);
1005
+ }
1006
+ 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 });
1007
+ for (const [root, reference] of Object.entries(contract.roots)) {
1008
+ const entry = derived.get(root);
1009
+ if (entry === void 0 || reference.space !== void 0 || reference.namespace !== entry.namespaceId || reference.model !== entry.name) throw refuse(root);
1010
+ }
1011
+ for (const root of derived.keys()) if (!Object.hasOwn(contract.roots, root)) throw refuse(root);
1012
+ }
1013
+ function refuseRlsWithoutModel(namespaceId, tableName) {
1014
+ 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.", {
1015
+ namespaceId,
1016
+ table: tableName
1017
+ });
1018
+ }
1019
+ function unwritablePolicy(policy, why, fix) {
1020
+ return unsupported(`policy "${policy.name}" on "${policy.namespaceId}"."${policy.tableName}" cannot be written in Prisma 8 PSL.`, why, fix, {
1021
+ namespaceId: policy.namespaceId,
1022
+ table: policy.tableName,
1023
+ name: policy.name
1024
+ });
1025
+ }
1026
+ function refusePolicyWithoutModel(policy) {
1027
+ 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.");
1028
+ }
1029
+ function refusePolicyWithoutRls(policy) {
1030
+ 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.");
1031
+ }
1032
+ function refusePolicyNameNotDerived(policy) {
1033
+ 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);
1034
+ }
1035
+ /** Refuses a role outside the unbound namespace: the PSL source reads a `role` block only there. */
1036
+ function refuseRoleOutsideUnbound(namespaceId, name) {
1037
+ if (namespaceId === UNBOUND_NAMESPACE_ID) return;
1038
+ 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.", {
1039
+ namespaceId,
1040
+ name
1041
+ });
1042
+ }
1043
+ const FILED_UNDER = {
1044
+ rls: "The PSL source files the row-level security setting written as `@@rls` under the name of the table.",
1045
+ role: "The PSL source files a role under the name its block is written with."
1046
+ };
1047
+ /** Refuses a row-level security setting or role filed under a key the PSL source would not use. */
1048
+ function refuseEntryFiledUnderAnotherName(input) {
1049
+ if (input.name === input.readsBackAs) return;
1050
+ 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, {
1051
+ namespaceId: input.namespaceId,
1052
+ kind: input.kind,
1053
+ name: input.name
1054
+ });
1055
+ }
1056
+ /** Refuses an entry that records a namespace other than the one it is stored in. */
1057
+ function refuseEntryInOtherNamespace(input) {
1058
+ if (input.recordedNamespaceId === input.namespaceId) return;
1059
+ 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.", {
1060
+ namespaceId: input.namespaceId,
1061
+ kind: input.kind,
1062
+ name: input.name
1063
+ });
1064
+ }
1065
+ function refuseNameThePslSourceLoses(kind, name) {
1066
+ if (name !== NAME_THE_PSL_SOURCE_LOSES) return;
1067
+ 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.", {
1068
+ kind,
1069
+ name
1070
+ });
1071
+ }
1072
+ /**
1073
+ * Refuses a table or column named `__proto__`, which the printer would write inside `@@map` or
1074
+ * `@map` and the PSL source loses when it reads it.
1075
+ */
1076
+ function refuseUnwritableMappedName(kind, name) {
1077
+ refuseNameThePslSourceLoses(kind, name);
1078
+ }
1079
+ /**
1080
+ * Refuses a name the printer writes where PSL reads an identifier: a namespace, model, field, value
1081
+ * object, enum, enum member, native enum, named type, policy, role or index option key.
1082
+ */
1083
+ function refuseUnwritableName(kind, name) {
1084
+ refuseNameThePslSourceLoses(kind, name);
1085
+ if (isPslIdentifier(name)) return;
1086
+ 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.", {
1087
+ kind,
1088
+ name
1089
+ });
1090
+ }
1091
+ /** The storage entry kinds the printer writes; any other kind is refused, whichever component defines it. */
1092
+ const PRINTED_ENTRY_KINDS = /* @__PURE__ */ new Set([
1093
+ "table",
1094
+ "valueSet",
1095
+ "native_enum",
1096
+ "rls",
1097
+ "policy",
1098
+ "role"
1099
+ ]);
1100
+ function refuseUnprintedEntryKinds(namespaceId, entries) {
1101
+ for (const [kind, entities] of Object.entries(entries)) {
1102
+ if (PRINTED_ENTRY_KINDS.has(kind)) continue;
1103
+ const names = Object.keys(entities ?? {});
1104
+ if (names.length === 0) continue;
1105
+ 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, {
1106
+ namespaceId,
1107
+ kind,
1108
+ names
1109
+ });
1110
+ }
1111
+ }
1112
+ /**
1113
+ * The type arguments a native type takes, in the order the PSL type
1114
+ * constructor declares them.
1115
+ */
1116
+ const TYPE_PARAM_ORDER = [
1117
+ "length",
1118
+ "precision",
1119
+ "scale"
1120
+ ];
1121
+ /**
1122
+ * Re-composes the parenthesised native type the type map resolves
1123
+ * (`numeric(10,2)`) from a column's bare native type and its type parameters.
1124
+ */
1125
+ function nativeTypeText(column) {
1126
+ const args = TYPE_PARAM_ORDER.map((key) => column.typeParams?.[key]).filter((value) => typeof value === "number");
1127
+ return args.length === 0 ? column.nativeType : `${column.nativeType}(${args.join(", ")})`;
1128
+ }
1129
+ /** A type argument as PSL writes it: a number as written, a string between quotes. */
1130
+ function typeArgumentText(value, coordinate) {
1131
+ if (typeof value !== "string") return String(value);
1132
+ refuseUnwritableTypeArgument(value, coordinate);
1133
+ return `"${value}"`;
1134
+ }
1135
+ function typeCall(path, args) {
1136
+ const name = path.join(".");
1137
+ if (args.length === 0) return { typeName: name };
1138
+ return {
1139
+ typeName: name,
1140
+ typeConstructor: {
1141
+ kind: "typeConstructor",
1142
+ path,
1143
+ args: args.map(positionalArg),
1144
+ span: SYNTHETIC_SPAN
1145
+ }
1146
+ };
1147
+ }
1148
+ /**
1149
+ * The call to the type constructor the type map `contract infer` uses names for the column's native
1150
+ * type, when the stack's constructor of that name produces exactly the column's codec, native type
1151
+ * and type parameters.
1152
+ */
1153
+ function typeMapCall(column, typeMap, authoringTypes) {
1154
+ const resolution = typeMap.resolve(nativeTypeText(column));
1155
+ if ("unsupported" in resolution) return void 0;
1156
+ const { name } = resolution.pslType;
1157
+ const descriptor = authoringTypes[name];
1158
+ return descriptor === void 0 ? void 0 : findAuthoringTypeConstructorCall({ [name]: descriptor }, column);
1159
+ }
1160
+ /**
1161
+ * The PSL type position for a storage column: a call to a type constructor the configured stack
1162
+ * contributes that produces exactly the column's codec, native type and type parameters. The
1163
+ * constructor the type map `contract infer` uses names for the native type comes first; otherwise
1164
+ * the first one in the stack that produces them, such as `TimestamptzString(3)` for a `timestamptz`
1165
+ * column carried as text, or `pgvector.Vector(3)`. An enum-typed column takes the
1166
+ * `pg.enum(<Block>)` constructor, named after the value set the column points at; a column typed by
1167
+ * a domain enum takes that enum's name. A column no PSL type reads back is refused.
1168
+ */
1169
+ function buildColumnType(input) {
1170
+ const { column, typeMap, authoringTypes, enumBlockNames, coordinate } = input;
1171
+ const enumBlockName = column.valueSet?.entityName ?? enumBlockNames.get(column.nativeType);
1172
+ if (column.codecId === "pg/enum@1" && enumBlockName !== void 0) return {
1173
+ typeName: enumBlockName,
1174
+ typeConstructor: {
1175
+ kind: "typeConstructor",
1176
+ path: ["pg", "enum"],
1177
+ args: [positionalArg(enumBlockName)],
1178
+ span: SYNTHETIC_SPAN
1179
+ }
1180
+ };
1181
+ const domainEnumName = column.valueSet?.entityName;
1182
+ if (domainEnumName !== void 0) return { typeName: domainEnumName };
1183
+ const call = typeMapCall(column, typeMap, authoringTypes) ?? findAuthoringTypeConstructorCall(authoringTypes, column);
1184
+ if (call !== void 0) return typeCall(call.path, call.args.map((value) => typeArgumentText(value, coordinate)));
1185
+ refuseColumnWithoutPslType(column, coordinate);
1186
+ }
1187
+ /**
1188
+ * The native type the stack's codec names for a value-object field. The field has no column of its
1189
+ * own, and no type parameters, which the PSL source would not keep.
1190
+ */
1191
+ function nativeTypeOfValueObjectField(field, coordinate, context) {
1192
+ const { codecId } = field.type;
1193
+ const descriptor = context.codecLookup.descriptorFor?.(codecId);
1194
+ if (!isPostgresCodecDescriptor(descriptor)) refuseValueObjectFieldCodecWithoutNativeType(codecId, coordinate);
1195
+ try {
1196
+ return descriptor.nativeTypeFor({ codecId });
1197
+ } catch {
1198
+ refuseValueObjectFieldCodecNeedingTypeParameters(codecId, coordinate);
1199
+ }
1200
+ }
1201
+ /** The PSL type position of a domain field: a value object by name, or a scalar as a column would print. */
1202
+ function buildDomainFieldType(input) {
1203
+ const { field, coordinate } = input;
1204
+ refuseUnwritableFieldShape(field, coordinate);
1205
+ const { type } = field;
1206
+ if (type.kind === "valueObject") return { typeName: type.name };
1207
+ refuseValueObjectFieldPartsTheSourceDrops({
1208
+ ...field,
1209
+ type
1210
+ }, coordinate);
1211
+ return buildColumnType({
1212
+ column: new StorageColumn({
1213
+ nativeType: nativeTypeOfValueObjectField({
1214
+ ...field,
1215
+ type
1216
+ }, coordinate, input.context),
1217
+ codecId: type.codecId,
1218
+ nullable: field.nullable,
1219
+ ...ifDefined("many", field.many)
1220
+ }),
1221
+ typeMap: input.typeMap,
1222
+ authoringTypes: input.context.authoringContributions.type,
1223
+ enumBlockNames: input.enumBlockNames,
1224
+ coordinate
1225
+ });
1226
+ }
1227
+ /** The `type` blocks of one namespace, one per value object the domain declares there. */
1228
+ function buildCompositeTypes(input) {
1229
+ refuseValueObjectsOutsideDefaultNamespace(input.contract, input.namespaceId);
1230
+ const valueObjects = input.contract.domain.namespaces[input.namespaceId]?.valueObjects ?? {};
1231
+ return Object.entries(valueObjects).map(([name, valueObject]) => {
1232
+ refuseUnwritableName("value object", name);
1233
+ return {
1234
+ kind: "compositeType",
1235
+ name,
1236
+ fields: Object.entries(valueObject.fields).map(([fieldName, field]) => {
1237
+ refuseUnwritableName("field", fieldName);
1238
+ const { typeName, typeConstructor } = buildDomainFieldType({
1239
+ field,
1240
+ coordinate: `"${input.namespaceId}".${name}.${fieldName}`,
1241
+ typeMap: input.typeMap,
1242
+ context: input.context,
1243
+ enumBlockNames: input.enumBlockNames
1244
+ });
1245
+ return {
1246
+ kind: "field",
1247
+ name: fieldName,
1248
+ typeName,
1249
+ ...ifDefined("typeConstructor", typeConstructor),
1250
+ optional: field.nullable,
1251
+ list: field.many === true,
1252
+ attributes: [],
1253
+ span: SYNTHETIC_SPAN
1254
+ };
1255
+ }),
1256
+ attributes: [],
1257
+ span: SYNTHETIC_SPAN
1258
+ };
1259
+ });
1260
+ }
1261
+ /** The document's `types { … }` block, one declaration per named storage type. */
1262
+ function buildTypesBlock(contract, typeMap, context) {
1263
+ const declarations = [];
1264
+ for (const [name, instance] of Object.entries(contract.storage.types ?? {})) {
1265
+ refuseUnwritableName("named type", name);
1266
+ const { typeName, typeConstructor } = buildColumnType({
1267
+ column: new StorageColumn({
1268
+ nativeType: instance.nativeType,
1269
+ codecId: instance.codecId,
1270
+ nullable: false,
1271
+ ...ifDefined("typeParams", instance.typeParams)
1272
+ }),
1273
+ typeMap,
1274
+ authoringTypes: context.authoringContributions.type,
1275
+ enumBlockNames: /* @__PURE__ */ new Map(),
1276
+ coordinate: `types.${name}`
1277
+ });
1278
+ declarations.push({
1279
+ kind: "namedType",
1280
+ name,
1281
+ ...typeConstructor === void 0 ? { baseType: typeName } : { typeConstructor },
1282
+ attributes: [],
1283
+ span: SYNTHETIC_SPAN
1284
+ });
1285
+ }
1286
+ return declarations.length === 0 ? void 0 : {
1287
+ kind: "types",
1288
+ declarations,
1289
+ span: SYNTHETIC_SPAN
1290
+ };
1291
+ }
1292
+ /**
1293
+ * One `enum <name> { … }` block per domain enum, each member written as
1294
+ * `Name = <value>` under `@@type`. The PSL source reads a member value as JSON,
1295
+ * so the value is written as JSON text.
1296
+ */
1297
+ function buildDomainEnumBlocks(enums) {
1298
+ return Object.entries(enums).map(([name, domainEnum]) => {
1299
+ refuseUnwritableName("enum", name);
1300
+ return {
1301
+ kind: "enum",
1302
+ keyword: "enum",
1303
+ name,
1304
+ parameters: Object.fromEntries(domainEnum.members.map((member) => {
1305
+ refuseUnwritableName("enum member", member.name);
1306
+ return [member.name, {
1307
+ kind: "value",
1308
+ raw: JSON.stringify(member.value),
1309
+ span: SYNTHETIC_SPAN
1310
+ }];
1311
+ })),
1312
+ blockAttributes: [{
1313
+ name: "type",
1314
+ args: [{
1315
+ kind: "positional",
1316
+ value: `"${escapePslString(domainEnum.codecId)}"`,
1317
+ span: SYNTHETIC_SPAN
1318
+ }],
1319
+ span: SYNTHETIC_SPAN
1320
+ }],
1321
+ attributes: { type: {
1322
+ args: { codec: domainEnum.codecId },
1323
+ span: SYNTHETIC_SPAN
1324
+ } },
1325
+ span: SYNTHETIC_SPAN
1326
+ };
1327
+ });
1328
+ }
1329
+ function sameValues(left, right) {
1330
+ return left.length === right.length && left.every((value, index) => value === right[index]);
1331
+ }
1332
+ /**
1333
+ * Builds one `native_enum` block per enum type a namespace declares.
1334
+ *
1335
+ * A contract keys a native enum by its type name and keys the value set it
1336
+ * derives by the name the schema gave the enum, and the PSL source derives
1337
+ * that value set from the block, named after the block. So the block is named
1338
+ * after the enum's value set: the value set a column typed by the enum names;
1339
+ * else, for an enum no column refers to, the unclaimed value set with the
1340
+ * enum's own name that holds exactly its members, or else the first unclaimed
1341
+ * one that does. An enum with no such value set is refused. `@@map` carries
1342
+ * the type name whenever it differs from the block name.
1343
+ */
1344
+ function buildNativeEnumBlocksForNamespace(input) {
1345
+ const valueSetNamesByTypeName = /* @__PURE__ */ new Map();
1346
+ for (const column of input.columns) {
1347
+ const valueSetName = column.valueSet?.entityName;
1348
+ if (valueSetName === void 0) continue;
1349
+ valueSetNamesByTypeName.set(column.nativeType, valueSetName);
1350
+ }
1351
+ const claimed = new Set(valueSetNamesByTypeName.values());
1352
+ const unreferenced = [];
1353
+ const nameByEntry = /* @__PURE__ */ new Map();
1354
+ for (const [entryName, nativeEnum] of input.nativeEnums) {
1355
+ refuseNativeEnumControl(input.namespaceId, nativeEnum);
1356
+ const { typeName } = nativeEnum;
1357
+ const fromColumn = valueSetNamesByTypeName.get(typeName) ?? valueSetNamesByTypeName.get(`${input.namespaceId}.${typeName}`);
1358
+ if (fromColumn === void 0) {
1359
+ unreferenced.push({
1360
+ entryName,
1361
+ nativeEnum
1362
+ });
1363
+ continue;
1364
+ }
1365
+ nameByEntry.set(entryName, fromColumn);
1366
+ }
1367
+ for (const { entryName, nativeEnum } of unreferenced) {
1368
+ const candidates = [...input.valueSets].filter(([name, values]) => !claimed.has(name) && sameValues(values, nativeEnum.members)).map(([name]) => name);
1369
+ const chosen = candidates.find((name) => name === entryName) ?? candidates[0];
1370
+ if (chosen === void 0) refuseNativeEnumWithoutValueSet(input.namespaceId, nativeEnum);
1371
+ claimed.add(chosen);
1372
+ nameByEntry.set(entryName, chosen);
1373
+ }
1374
+ const blocks = [];
1375
+ const blockNamesByTypeName = /* @__PURE__ */ new Map();
1376
+ const derivedValueSets = /* @__PURE__ */ new Map();
1377
+ for (const [entryName, nativeEnum] of input.nativeEnums) {
1378
+ const { typeName } = nativeEnum;
1379
+ const blockName = nameByEntry.get(entryName) ?? typeName;
1380
+ refuseUnwritableName("native enum", blockName);
1381
+ blocks.push(buildNativeEnumBlock(blockName, typeName, nativeEnum.members));
1382
+ blockNamesByTypeName.set(typeName, blockName);
1383
+ blockNamesByTypeName.set(`${input.namespaceId}.${typeName}`, blockName);
1384
+ derivedValueSets.set(blockName, nativeEnum.members);
1385
+ }
1386
+ return {
1387
+ blocks,
1388
+ blockNamesByTypeName,
1389
+ derivedValueSets
1390
+ };
1391
+ }
1392
+ /**
1393
+ * The checks the PSL source derives itself for a table, keyed by name, so
1394
+ * they are not also written as `@@check`. A table that is not managed derives
1395
+ * none. A managed one derives a membership check for each column typed by a
1396
+ * domain enum and an element-not-null check for each list column, less the
1397
+ * kinds a column waives with `@noCheck`.
1398
+ */
1399
+ function derivedChecks(input) {
1400
+ const checks = /* @__PURE__ */ new Map();
1401
+ if (!input.managed) return checks;
1402
+ for (const [columnName, column] of Object.entries(input.table.columns)) {
1403
+ const enumValues = column.codecId === "pg/enum@1" || column.valueSet === void 0 ? void 0 : input.domainEnumValues.get(column.valueSet.entityName);
1404
+ const memberValues = enumValues?.filter((value) => typeof value === "string" || typeof value === "number");
1405
+ const waived = new Set(column.noCheck ?? []);
1406
+ for (const candidate of postgresRenderCheckExpressions({
1407
+ tableName: input.tableName,
1408
+ columnName,
1409
+ many: column.many === true,
1410
+ memberValues: memberValues?.length === enumValues?.length ? memberValues : void 0
1411
+ })) {
1412
+ if (waived.has(candidate.kind)) continue;
1413
+ const prefix = composeCheckWirePrefix(input.tableName, columnName, candidate.kind);
1414
+ checks.set(formatWireName(prefix, computeCheckContentHash(candidate.expression)), {
1415
+ prefix,
1416
+ expression: candidate.expression
1417
+ });
1418
+ }
1419
+ }
1420
+ return checks;
1421
+ }
1422
+ /**
1423
+ * Whether a table object belongs to this model when several models share the
1424
+ * table: a single-table variant owns what lies within its own columns, and the
1425
+ * base owns the rest.
1426
+ */
1427
+ function ownsTableObject(entry, variant, singleTableVariants, columns) {
1428
+ if (variant?.singleTable === true) return columns?.every((column) => entry.ownColumns.has(column)) === true;
1429
+ return !singleTableVariants.some((other) => columns?.every((column) => other.ownColumns.has(column)) === true);
1430
+ }
1431
+ /**
1432
+ * How a check or index is named in PSL: `name:` with its prefix when the name
1433
+ * is that prefix and the hash of its content, which the PSL source derives
1434
+ * again; `map:` when it has no prefix. A prefix whose name is anything else is
1435
+ * refused, because neither form reads back as it.
1436
+ */
1437
+ function attributeNaming(input) {
1438
+ const { kind, entry, name, prefix } = input;
1439
+ if (prefix === void 0) return { kind: "exact" };
1440
+ if (formatWireName(prefix, input.contentHash()) === name) return {
1441
+ kind: "wire",
1442
+ prefix
1443
+ };
1444
+ refuseUnwritableObjectName({
1445
+ kind,
1446
+ entry,
1447
+ name,
1448
+ prefix
1449
+ });
1450
+ }
1451
+ /**
1452
+ * The `@@` attributes of one model: its polymorphism, its keys, checks and indexes, its control
1453
+ * policy, `@@rls` and `@@map`. A table object several models share goes on the model that owns it.
1454
+ */
1455
+ function buildModelAttributes(input) {
1456
+ const { entry, variant, singleTableVariants, derivedChecksByName } = input;
1457
+ const attributes = [];
1458
+ const fieldNameOf = (column) => entry.fieldNamesByColumn.get(column) ?? column;
1459
+ const owns = (columns) => ownsTableObject(entry, variant, singleTableVariants, columns);
1460
+ if (entry.model.discriminator !== void 0) attributes.push(buildAttribute("model", "discriminator", [positionalArg(entry.model.discriminator.field)]));
1461
+ if (variant !== void 0) attributes.push(buildAttribute("model", "base", [positionalArg(variant.base.name), positionalArg(`"${escapePslString(variant.value)}"`)]));
1462
+ const primaryKeyColumns = variant === void 0 ? entry.table.primaryKey?.columns ?? [] : [];
1463
+ if (primaryKeyColumns.length > 1) attributes.push(buildModelConstraintAttribute("id", primaryKeyColumns.map(fieldNameOf), entry.table.primaryKey?.name));
1464
+ for (const unique of entry.table.uniques) {
1465
+ if (!owns(unique.columns)) continue;
1466
+ attributes.push(buildModelConstraintAttribute("unique", unique.columns.map(fieldNameOf), unique.name));
1467
+ }
1468
+ for (const check of entry.table.checks ?? []) {
1469
+ if (derivedChecksByName.has(check.name) || !owns(void 0)) continue;
1470
+ attributes.push(buildCheckAttribute(check, attributeNaming({
1471
+ kind: "check",
1472
+ entry,
1473
+ name: check.name,
1474
+ prefix: check.prefix,
1475
+ contentHash: () => computeCheckContentHash(check.expression)
1476
+ })));
1477
+ }
1478
+ for (const index of entry.table.indexes) {
1479
+ if (!owns(index.columns)) continue;
1480
+ refuseUnwritableIndexOptions(entry, index);
1481
+ attributes.push(buildIndexAttribute(index, index.columns?.map(fieldNameOf), attributeNaming({
1482
+ kind: "index",
1483
+ entry,
1484
+ name: index.name,
1485
+ prefix: index.prefix,
1486
+ contentHash: () => computeIndexContentHash(index)
1487
+ })));
1488
+ }
1489
+ if (entry.table.control !== void 0 && variant?.singleTable !== true) attributes.push(buildAttribute("model", "control", [positionalArg(entry.table.control)]));
1490
+ if (input.rlsEnabled && variant?.singleTable !== true) attributes.push(buildAttribute("model", "rls", []));
1491
+ const mapName = pslModelMapName(entry.name, entry.tableName);
1492
+ if (mapName !== void 0 && variant?.singleTable !== true) attributes.push(buildMapAttribute("model", mapName));
1493
+ return attributes;
1494
+ }
1495
+ const PSL_REFERENTIAL_ACTIONS = {
1496
+ noAction: "NoAction",
1497
+ restrict: "Restrict",
1498
+ cascade: "Cascade",
1499
+ setNull: "SetNull",
1500
+ setDefault: "SetDefault"
1501
+ };
1502
+ function isReferenceRelation(relation) {
1503
+ return "on" in relation && relation.on !== void 0;
1504
+ }
1505
+ function collectRelations(models) {
1506
+ const entries = [];
1507
+ for (const owner of models) for (const [fieldName, relation] of Object.entries(owner.model.relations)) {
1508
+ if (!isReferenceRelation(relation)) refuseRelationWithoutJoin(owner.name, fieldName);
1509
+ entries.push({
1510
+ owner,
1511
+ fieldName,
1512
+ relation,
1513
+ targetCoordinate: crossReferenceCoordinate(relation.to)
1514
+ });
1515
+ }
1516
+ return entries;
1517
+ }
1518
+ /** A relation whose local fields carry the foreign key — the side `@relation(fields:…)` goes on. */
1519
+ function isOwningRelation(entry) {
1520
+ return entry.relation.cardinality === "N:1";
1521
+ }
1522
+ function relationKey(entry) {
1523
+ return JSON.stringify([
1524
+ entry.owner.namespaceId,
1525
+ entry.owner.name,
1526
+ entry.fieldName
1527
+ ]);
1528
+ }
1529
+ /** The relation name a pair is pinned with when the model pair carries more than one relation. */
1530
+ function relationName(entry) {
1531
+ return `${entry.owner.name}_${entry.fieldName}`;
1532
+ }
1533
+ function columnsIn(model, fieldNames) {
1534
+ return fieldNames.map((fieldName) => model.storage.fields[fieldName]?.column ?? fieldName);
1535
+ }
1536
+ function columnsOf(entry, fieldNames) {
1537
+ return columnsIn(entry.owner, fieldNames);
1538
+ }
1539
+ function sameColumns(a, b) {
1540
+ return a.length === b.length && a.every((value, index) => value === b[index]);
1541
+ }
1542
+ /** The foreign key that backs an owning relation. */
1543
+ function foreignKeyFor(entry, target) {
1544
+ const localColumns = columnsOf(entry, entry.relation.on.localFields);
1545
+ const targetColumns = columnsIn(target, entry.relation.on.targetFields);
1546
+ 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));
1547
+ }
1548
+ /**
1549
+ * The owning relation on `target` that pairs with a back-relation `entry`: the
1550
+ * one pointing back at `entry`'s model over the same columns. The
1551
+ * back-relation's target fields name fields of the target model, so they are
1552
+ * resolved to columns through the candidate's own model, not through the
1553
+ * back-relation's.
1554
+ */
1555
+ function owningPartner(entry, relationsByModel) {
1556
+ const ownerCoordinate = modelCoordinate(entry.owner.namespaceId, entry.owner.name);
1557
+ 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)));
1558
+ }
1559
+ /**
1560
+ * The junction-side relation that points back at the parent of a many-to-many
1561
+ * relation — the one whose columns are the junction's parent columns.
1562
+ */
1563
+ function junctionParentRelation(entry, relationsByModel) {
1564
+ const through = entry.relation.through;
1565
+ if (through === void 0) return void 0;
1566
+ const ownerCoordinate = modelCoordinate(entry.owner.namespaceId, entry.owner.name);
1567
+ for (const [, relations] of relationsByModel) for (const candidate of relations) {
1568
+ if (candidate.owner.tableName !== through.table || candidate.owner.namespaceId !== through.namespaceId || candidate.targetCoordinate !== ownerCoordinate || !isOwningRelation(candidate)) continue;
1569
+ if (sameColumns(columnsOf(candidate, candidate.relation.on.localFields), through.parentColumns)) return candidate;
1570
+ }
1571
+ }
1572
+ /** The PSL field one relation is written as. */
1573
+ function buildRelationField(input) {
1574
+ const { entry, target, name } = input;
1575
+ const { relation } = entry;
1576
+ const typeNamespaceId = target.namespaceId === entry.owner.namespaceId ? void 0 : pslNamespaceName(target.namespaceId);
1577
+ const args = [];
1578
+ if (name !== void 0) args.push(namedArg("name", `"${escapePslString(name)}"`));
1579
+ if (relation.cardinality === "N:1" && input.ownerIsSingleTableVariant) {
1580
+ args.push(namedArg("fields", `[${relation.on.localFields.join(", ")}]`));
1581
+ args.push(namedArg("references", `[${relation.on.targetFields.join(", ")}]`));
1582
+ } else if (relation.cardinality === "N:1") {
1583
+ const foreignKey = foreignKeyFor(entry, target);
1584
+ if (foreignKey === void 0) refuseToOneRelationWithoutForeignKey(entry.owner.name, entry.fieldName);
1585
+ args.push(namedArg("fields", `[${relation.on.localFields.join(", ")}]`));
1586
+ args.push(namedArg("references", `[${relation.on.targetFields.join(", ")}]`));
1587
+ if (foreignKey.onDelete !== void 0) args.push(namedArg("onDelete", PSL_REFERENTIAL_ACTIONS[foreignKey.onDelete]));
1588
+ if (foreignKey.onUpdate !== void 0) args.push(namedArg("onUpdate", PSL_REFERENTIAL_ACTIONS[foreignKey.onUpdate]));
1589
+ if (foreignKey.name !== void 0) args.push(namedArg("map", `"${escapePslString(foreignKey.name)}"`));
1590
+ args.push(namedArg("index", "false"));
1591
+ }
1592
+ const list = relation.cardinality === "1:N" || relation.cardinality === "N:M";
1593
+ const optional = !list && (relation.cardinality === "1:1" || relation.cardinality === "N:1") && relation.nullable === true;
1594
+ return {
1595
+ kind: "field",
1596
+ name: entry.fieldName,
1597
+ typeName: target.name,
1598
+ ...ifDefined("typeNamespaceId", typeNamespaceId),
1599
+ optional,
1600
+ list,
1601
+ attributes: args.length > 0 ? [buildAttribute("field", "relation", args)] : [],
1602
+ span: SYNTHETIC_SPAN
1603
+ };
1604
+ }
1605
+ /** The relations of each model, keyed by the model's coordinate. */
1606
+ function relationsByModel(relations) {
1607
+ const byModel = /* @__PURE__ */ new Map();
1608
+ for (const entry of relations) {
1609
+ const key = modelCoordinate(entry.owner.namespaceId, entry.owner.name);
1610
+ const bucket = byModel.get(key) ?? [];
1611
+ bucket.push(entry);
1612
+ byModel.set(key, bucket);
1613
+ }
1614
+ return byModel;
1615
+ }
1616
+ /**
1617
+ * The relation names to pin. A pair needs one when either of its models
1618
+ * carries more than one relation to the other; a many-to-many list field
1619
+ * additionally pins the junction-side relation it travels through, so that
1620
+ * relation is named too.
1621
+ */
1622
+ function resolvePinnedRelations(relations, relationsByModel) {
1623
+ const pairCounts = /* @__PURE__ */ new Map();
1624
+ for (const entry of relations) {
1625
+ const key = JSON.stringify([modelCoordinate(entry.owner.namespaceId, entry.owner.name), entry.targetCoordinate]);
1626
+ pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1);
1627
+ }
1628
+ const ambiguous = (entry) => {
1629
+ const ownerCoordinate = modelCoordinate(entry.owner.namespaceId, entry.owner.name);
1630
+ const forward = pairCounts.get(JSON.stringify([ownerCoordinate, entry.targetCoordinate])) ?? 0;
1631
+ const backward = pairCounts.get(JSON.stringify([entry.targetCoordinate, ownerCoordinate])) ?? 0;
1632
+ return forward > 1 || backward > 1;
1633
+ };
1634
+ const pinned = /* @__PURE__ */ new Set();
1635
+ for (const entry of relations) {
1636
+ if (!ambiguous(entry)) continue;
1637
+ const owning = isOwningRelation(entry) ? entry : entry.relation.cardinality === "N:M" ? junctionParentRelation(entry, relationsByModel) : owningPartner(entry, relationsByModel);
1638
+ if (owning !== void 0) pinned.add(relationKey(owning));
1639
+ }
1640
+ return pinned;
1641
+ }
1642
+ /**
1643
+ * Relation fields in the order their foreign keys appear in storage, so the
1644
+ * `foreignKeys` the PSL source derives come back in the same order. A relation
1645
+ * that owns no foreign key keeps its place at the end.
1646
+ */
1647
+ function orderedByForeignKey(entry, relations) {
1648
+ const positions = /* @__PURE__ */ new Map();
1649
+ for (const relation of relations) {
1650
+ const target = relation.relation.on.localFields.map((fieldName) => relation.owner.storage.fields[fieldName]?.column ?? fieldName);
1651
+ const position = entry.table.foreignKeys.findIndex((fk) => fk.source.columns.length === target.length && fk.source.columns.every((column, index) => column === target[index]));
1652
+ positions.set(relation, isOwningRelation(relation) && position >= 0 ? position : relations.length);
1653
+ }
1654
+ return [...relations].sort((a, b) => (positions.get(a) ?? 0) - (positions.get(b) ?? 0));
1655
+ }
1656
+ /**
1657
+ * The relation fields of one model, in the order of its foreign keys. Each foreign key an owning
1658
+ * relation travels is added to `travelledForeignKeys`.
1659
+ */
1660
+ function buildRelationFields(input) {
1661
+ const fields = [];
1662
+ for (const modelRelation of orderedByForeignKey(input.entry, input.relations)) {
1663
+ refuseUnwritableName("field", modelRelation.fieldName);
1664
+ const target = relationTarget(modelRelation, input.modelsByCoordinate);
1665
+ const junctionRelation = modelRelation.relation.cardinality === "N:M" ? junctionParentRelation(modelRelation, input.relationsByModel) : void 0;
1666
+ if (modelRelation.relation.cardinality === "N:M" && junctionRelation === void 0) refuseManyToManyWithoutJunctionRelation(modelRelation.owner.name, modelRelation.fieldName);
1667
+ const owning = isOwningRelation(modelRelation) ? modelRelation : modelRelation.relation.cardinality === "N:M" ? junctionRelation : owningPartner(modelRelation, input.relationsByModel);
1668
+ if (owning === void 0) refuseBackRelationWithoutOwningRelation({
1669
+ modelName: modelRelation.owner.name,
1670
+ fieldName: modelRelation.fieldName,
1671
+ targetModel: target.name
1672
+ });
1673
+ const name = input.pinned.has(relationKey(owning)) ? relationName(owning) : void 0;
1674
+ if (isOwningRelation(modelRelation)) {
1675
+ const foreignKey = foreignKeyFor(modelRelation, target);
1676
+ if (foreignKey !== void 0) input.travelledForeignKeys.add(foreignKey);
1677
+ }
1678
+ fields.push(buildRelationField({
1679
+ entry: modelRelation,
1680
+ target,
1681
+ name,
1682
+ ownerIsSingleTableVariant: input.variant?.singleTable === true
1683
+ }));
1684
+ }
1685
+ return fields;
1686
+ }
1687
+ /**
1688
+ * The model a relation points at. A relation into another contract space is
1689
+ * refused: the printer does not write one yet.
1690
+ */
1691
+ function relationTarget(entry, modelsByCoordinate) {
1692
+ const { to } = entry.relation;
1693
+ refuseRelationToOtherContractSpace({
1694
+ modelName: entry.owner.name,
1695
+ fieldName: entry.fieldName,
1696
+ targetModel: to.model,
1697
+ space: to.space
1698
+ });
1699
+ const target = modelsByCoordinate.get(entry.targetCoordinate);
1700
+ assertDefined(target, `relation "${entry.owner.name}.${entry.fieldName}" targets model "${to.namespace}.${to.model}", which the contract does not declare`);
1701
+ return target;
1702
+ }
1703
+ /**
1704
+ * The storage tables of one namespace that have row-level security enabled,
1705
+ * each written as `@@rls` on its model. The PSL source files each one under
1706
+ * its table name, in the namespace of its model.
1707
+ */
1708
+ function rlsEnabledTables(namespaceId, entries) {
1709
+ const tables = /* @__PURE__ */ new Set();
1710
+ for (const [name, entity] of Object.entries(entries ?? {})) {
1711
+ invariant(entity instanceof PostgresRlsEnablement, `"rls" entry "${name}" in namespace "${namespaceId}" is not a row-level security setting`);
1712
+ refuseEntryInOtherNamespace({
1713
+ namespaceId,
1714
+ kind: "rls",
1715
+ name,
1716
+ recordedNamespaceId: entity.namespaceId
1717
+ });
1718
+ refuseEntryFiledUnderAnotherName({
1719
+ namespaceId,
1720
+ kind: "rls",
1721
+ name,
1722
+ readsBackAs: entity.tableName
1723
+ });
1724
+ tables.add(entity.tableName);
1725
+ }
1726
+ return tables;
1727
+ }
1728
+ /**
1729
+ * One `role <name> {}` block per role. The PSL source reads a role block only
1730
+ * inside `namespace unbound`, and files it under its name.
1731
+ */
1732
+ function buildRoleBlocks(namespaceId, entries) {
1733
+ return Object.entries(entries ?? {}).map(([name, entity]) => {
1734
+ invariant(entity instanceof PostgresRole, `"role" entry "${name}" in namespace "${namespaceId}" is not a role`);
1735
+ refuseRoleOutsideUnbound(namespaceId, name);
1736
+ refuseEntryInOtherNamespace({
1737
+ namespaceId,
1738
+ kind: "role",
1739
+ name,
1740
+ recordedNamespaceId: entity.namespaceId
1741
+ });
1742
+ refuseEntryFiledUnderAnotherName({
1743
+ namespaceId,
1744
+ kind: "role",
1745
+ name,
1746
+ readsBackAs: entity.name
1747
+ });
1748
+ refuseUnwritableName("role", entity.name);
1749
+ return {
1750
+ kind: "role",
1751
+ keyword: "role",
1752
+ name: entity.name,
1753
+ parameters: {},
1754
+ blockAttributes: [],
1755
+ attributes: {},
1756
+ span: SYNTHETIC_SPAN
1757
+ };
1758
+ });
1759
+ }
1760
+ /**
1761
+ * Whether the PSL source, reading a policy block named `head`, derives this
1762
+ * policy's name: the block name with the hash of the policy's content for a
1763
+ * wire-named policy, or the `@@map` name for an exact one.
1764
+ */
1765
+ function policyNameReadsBack(head, policy) {
1766
+ if (policy.prefix === void 0) return true;
1767
+ const hash = computeContentHash({
1768
+ ...policy.using === void 0 ? {} : { using: policy.using },
1769
+ ...policy.withCheck === void 0 ? {} : { withCheck: policy.withCheck },
1770
+ roles: policy.roles,
1771
+ operation: policy.operation,
1772
+ permissive: policy.permissive
1773
+ });
1774
+ return policy.prefix === head && policy.name === formatWireName(head, hash);
1775
+ }
1776
+ /**
1777
+ * One `policy_<operation>` block per policy, named by its entry key, which is
1778
+ * the block head it was authored under. A policy with an exact name also
1779
+ * prints `@@map` with that name.
1780
+ */
1781
+ function buildPolicyBlocks(input) {
1782
+ return Object.entries(input.entries ?? {}).map(([head, policy]) => {
1783
+ invariant(policy instanceof PostgresRlsPolicy, `"policy" entry "${head}" in namespace "${input.namespaceId}" is not a policy`);
1784
+ refuseUnwritableName("policy", head);
1785
+ refuseEntryInOtherNamespace({
1786
+ namespaceId: input.namespaceId,
1787
+ kind: "policy",
1788
+ name: head,
1789
+ recordedNamespaceId: policy.namespaceId
1790
+ });
1791
+ const modelName = input.modelNameForTable(policy.tableName);
1792
+ if (modelName === void 0) refusePolicyWithoutModel(policy);
1793
+ if (!input.rlsTables.has(policy.tableName)) refusePolicyWithoutRls(policy);
1794
+ if (!policyNameReadsBack(head, policy)) refusePolicyNameNotDerived(policy);
1795
+ for (const role of policy.roles) refuseUnwritableName("role", role);
1796
+ return {
1797
+ kind: "policy",
1798
+ keyword: POLICY_BLOCK_KEYWORDS[policy.operation],
1799
+ name: head,
1800
+ parameters: {
1801
+ target: {
1802
+ kind: "ref",
1803
+ identifier: modelName,
1804
+ span: SYNTHETIC_SPAN
1805
+ },
1806
+ roles: {
1807
+ kind: "list",
1808
+ items: policy.roles.map((role) => ({
1809
+ kind: "ref",
1810
+ identifier: role,
1811
+ span: SYNTHETIC_SPAN
1812
+ })),
1813
+ span: SYNTHETIC_SPAN
1814
+ },
1815
+ ...policy.using !== void 0 ? { using: {
1816
+ kind: "value",
1817
+ raw: JSON.stringify(policy.using),
1818
+ span: SYNTHETIC_SPAN
1819
+ } } : {},
1820
+ ...policy.withCheck !== void 0 ? { withCheck: {
1821
+ kind: "value",
1822
+ raw: JSON.stringify(policy.withCheck),
1823
+ span: SYNTHETIC_SPAN
1824
+ } } : {},
1825
+ ...policy.permissive ? {} : { permissive: {
1826
+ kind: "value",
1827
+ raw: "false",
1828
+ span: SYNTHETIC_SPAN
1829
+ } }
1830
+ },
1831
+ blockAttributes: policy.prefix === void 0 ? [{
1832
+ name: "map",
1833
+ args: [{
1834
+ kind: "positional",
1835
+ value: `"${escapePslString(policy.name)}"`,
1836
+ span: SYNTHETIC_SPAN
1837
+ }],
1838
+ span: SYNTHETIC_SPAN
1839
+ }] : [],
1840
+ attributes: policy.prefix === void 0 ? { map: {
1841
+ args: { name: policy.name },
1842
+ span: SYNTHETIC_SPAN
1843
+ } } : {},
1844
+ span: SYNTHETIC_SPAN
1845
+ };
1846
+ });
1847
+ }
1848
+ /**
1849
+ * The `@default(…)` attribute for a storage column, or `undefined` when the column carries no
1850
+ * default.
1851
+ *
1852
+ * A literal prints as the PSL literal the data type of the column's codec reads back, through the
1853
+ * stack's data types, with the mapping `contract infer` uses. An enum column's default is a member
1854
+ * name, which reads as text; a domain enum's literal prints as the member name that carries it.
1855
+ * `now()` and `autoincrement()` print by name; every other function default prints as a `sql`
1856
+ * tagged literal.
1857
+ *
1858
+ * A literal is refused when the column's codec has no data type in the stack, or when no PSL
1859
+ * literal of that data type reads back as the stored value.
1860
+ */
1861
+ function buildColumnDefault(input) {
1862
+ const columnDefault = input.column.default;
1863
+ if (columnDefault === void 0) return;
1864
+ const coordinate = `"${input.namespaceId}"."${input.tableName}"."${input.columnName}"`;
1865
+ if (input.domainEnum !== void 0 && columnDefault.kind === "literal") {
1866
+ const memberName = input.domainEnum.members.find((member) => member.value === columnDefault.value)?.name;
1867
+ if (memberName === void 0) refuseDefaultOutsideEnum({
1868
+ coordinate,
1869
+ value: columnDefault.value,
1870
+ pslTypeName: input.pslTypeName
1871
+ });
1872
+ return buildAttribute("field", "default", [positionalArg(memberName)]);
1873
+ }
1874
+ const { context } = input;
1875
+ const result = mapDefault(columnDefault, {
1876
+ dataTypeEntries: context.authoringContributions.dataTypes,
1877
+ dataTypes: context.dataTypeLookup,
1878
+ columnDataType: context.codecLookup.descriptorFor?.(input.isEnum ? PG_TEXT_CODEC_ID : input.column.codecId)?.dataType,
1879
+ list: input.column.many === true
1880
+ });
1881
+ if (result === void 0) refuseUnwritableLiteralDefault({
1882
+ coordinate,
1883
+ written: columnDefault.kind === "literal" ? JSON.stringify(columnDefault.value) : columnDefault.expression,
1884
+ pslTypeName: input.pslTypeName
1885
+ });
1886
+ return parseDefaultAttributeString(result.attribute);
1887
+ }
1888
+ /**
1889
+ * The `temporal.*` field preset each codec with a "now" generator is authored through. The target
1890
+ * contributes the presets; `test/integration/test/psl-print/generated-values-roundtrip.integration.test.ts` writes and
1891
+ * reads back every one the stack contributes, so this table cannot drift from them.
1892
+ */
1893
+ const TEMPORAL_PRESET_NAMES = /* @__PURE__ */ new Map([
1894
+ [PG_TIMESTAMP_TEMPORAL_CODEC_ID, "timestamp"],
1895
+ [PG_TIMESTAMPTZ_TEMPORAL_CODEC_ID, "timestamptz"],
1896
+ [PG_TIMESTAMP_STRING_CODEC_ID, "timestampString"],
1897
+ [PG_TIMESTAMPTZ_STRING_CODEC_ID, "timestamptzString"],
1898
+ [PG_TIMESTAMPTZ_DATE_CODEC_ID, "timestamptzJsDate"]
1899
+ ]);
1900
+ const GENERATOR_CALLS = /* @__PURE__ */ new Map([
1901
+ ["uuidv4", () => "uuid()"],
1902
+ ["uuidv7", () => "uuid(7)"],
1903
+ ["cuid2", () => "cuid(2)"],
1904
+ ["ulid", () => "ulid()"],
1905
+ ["nanoid", (params) => typeof params?.["size"] === "number" ? `nanoid(${params["size"]})` : "nanoid()"]
1906
+ ]);
1907
+ /**
1908
+ * How one column's execution generators are written in PSL: an id generator as a `@default(<fn>())`
1909
+ * attribute, and a wall-clock-now generator as the `temporal.*` preset the column's codec is
1910
+ * authored through.
1911
+ */
1912
+ function buildExecutionDefault(input) {
1913
+ const { executionDefault, codecId, coordinate } = input;
1914
+ const onCreateId = executionDefault.onCreate?.id;
1915
+ const onUpdateId = executionDefault.onUpdate?.id;
1916
+ const nowGeneratorId = postgresNowGeneratorIdFor(codecId);
1917
+ const presetName = TEMPORAL_PRESET_NAMES.get(codecId);
1918
+ if (nowGeneratorId !== void 0 && presetName !== void 0) {
1919
+ const onCreate = onCreateId === nowGeneratorId;
1920
+ const onUpdate = onUpdateId === nowGeneratorId;
1921
+ if (onCreate || onUpdate) {
1922
+ if (onCreateId !== void 0 && !onCreate || onUpdateId !== void 0 && !onUpdate) refuseNowGeneratorPairedWithAnother({
1923
+ coordinate,
1924
+ onCreate: onCreateId,
1925
+ onUpdate: onUpdateId,
1926
+ other: onCreate ? onUpdateId : onCreateId
1927
+ });
1928
+ return {
1929
+ kind: "temporal",
1930
+ phases: {
1931
+ presetName,
1932
+ onCreate,
1933
+ onUpdate
1934
+ }
1935
+ };
1936
+ }
1937
+ }
1938
+ const phases = {
1939
+ coordinate,
1940
+ onCreate: onCreateId,
1941
+ onUpdate: onUpdateId
1942
+ };
1943
+ if (onUpdateId !== void 0) refuseGeneratorOnUpdate(phases);
1944
+ const call = onCreateId === void 0 ? void 0 : GENERATOR_CALLS.get(onCreateId);
1945
+ if (call === void 0) refuseGeneratorWithoutPslFunction(phases);
1946
+ return {
1947
+ kind: "attribute",
1948
+ attribute: buildAttribute("field", "default", [positionalArg(call(executionDefault.onCreate?.params))])
1949
+ };
1950
+ }
1951
+ /** The `temporal.<preset>(precision?, onCreate: now, onUpdate: now)` argument list. */
1952
+ function temporalPresetArguments(input) {
1953
+ const args = [];
1954
+ if (typeof input.precision === "number") args.push(positionalArg(String(input.precision)));
1955
+ if (input.phases.onCreate) args.push(namedArg("onCreate", "now"));
1956
+ if (input.phases.onUpdate) args.push(namedArg("onUpdate", "now"));
1957
+ return args;
1958
+ }
1959
+ /** The generated values of the contract, keyed by the column they fill. */
1960
+ function executionDefaultsByColumn(contract) {
1961
+ const byColumn = /* @__PURE__ */ new Map();
1962
+ for (const entry of contract.execution?.mutations.defaults ?? []) byColumn.set(JSON.stringify([
1963
+ entry.ref.namespace,
1964
+ entry.ref.entry,
1965
+ entry.ref.field
1966
+ ]), entry);
1967
+ return byColumn;
1968
+ }
1969
+ function scalarFieldAttributes(input) {
1970
+ const attributes = [];
1971
+ if (input.isSingleColumnId) attributes.push(buildAttribute("field", "id", input.primaryKeyName === void 0 ? [] : [namedArg("map", `"${escapePslString(input.primaryKeyName)}"`)]));
1972
+ const columnDefault = input.generatedDefault ?? buildColumnDefault({
1973
+ column: input.column,
1974
+ pslTypeName: input.pslTypeName,
1975
+ isEnum: input.isEnum,
1976
+ domainEnum: input.domainEnum,
1977
+ namespaceId: input.namespaceId,
1978
+ tableName: input.tableName,
1979
+ columnName: input.columnName,
1980
+ context: input.context
1981
+ });
1982
+ if (columnDefault !== void 0) attributes.push(columnDefault);
1983
+ for (const kind of input.column.noCheck ?? []) attributes.push(buildAttribute("field", "noCheck", [positionalArg(kind)]));
1984
+ const mapName = pslFieldMapName(input.fieldName, input.columnName);
1985
+ if (mapName !== void 0) attributes.push(buildMapAttribute("field", mapName));
1986
+ return attributes;
1987
+ }
1988
+ /**
1989
+ * The scalar and value-object fields of one model, one per column its storage names. Each generated
1990
+ * value written with a field is added to `writtenExecutionDefaults`.
1991
+ */
1992
+ function buildScalarFields(input) {
1993
+ const { entry, variant, enums, domainEnums, typeMap, context, executionDefaults } = input;
1994
+ const primaryKeyColumns = variant === void 0 ? entry.table.primaryKey?.columns ?? [] : [];
1995
+ const fields = [];
1996
+ refuseFieldsWithoutColumn(entry);
1997
+ for (const [fieldName, fieldStorage] of Object.entries(entry.storage.fields)) {
1998
+ const columnName = fieldStorage.column;
1999
+ const coordinate = `"${entry.namespaceId}"."${entry.tableName}"."${columnName}"`;
2000
+ const column = entry.table.columns[columnName];
2001
+ const field = entry.model.fields[fieldName];
2002
+ assertDefined(column, `column ${coordinate} is not declared by its table`);
2003
+ if (field === void 0) refuseStorageOfUndeclaredField({
2004
+ entry,
2005
+ fieldName,
2006
+ coordinate
2007
+ });
2008
+ refuseUnwritableName("field", fieldName);
2009
+ refuseUnwritableMappedName("column", columnName);
2010
+ refuseUnwritableFieldShape(field, coordinate);
2011
+ refuseColumnControl(column, coordinate);
2012
+ refuseFieldColumnMismatch({
2013
+ field,
2014
+ column,
2015
+ coordinate,
2016
+ modelName: entry.name,
2017
+ singleTableVariant: variant?.singleTable === true,
2018
+ domainEnumNames: input.defaultDomainEnumNames
2019
+ });
2020
+ if (column.typeRef !== void 0) refuseColumnDifferingFromNamedType({
2021
+ column,
2022
+ typeRef: column.typeRef,
2023
+ namedType: input.namedTypes[column.typeRef],
2024
+ coordinate
2025
+ });
2026
+ const columnType = column.typeRef !== void 0 ? { typeName: column.typeRef } : field.type.kind === "valueObject" ? buildDomainFieldType({
2027
+ field,
2028
+ coordinate,
2029
+ typeMap,
2030
+ context,
2031
+ enumBlockNames: enums.blockNamesByTypeName
2032
+ }) : buildColumnType({
2033
+ column,
2034
+ typeMap,
2035
+ authoringTypes: context.authoringContributions.type,
2036
+ enumBlockNames: enums.blockNamesByTypeName,
2037
+ coordinate
2038
+ });
2039
+ let { typeName, typeConstructor } = columnType;
2040
+ const execution = executionDefaults.get(JSON.stringify([
2041
+ entry.namespaceId,
2042
+ entry.tableName,
2043
+ columnName
2044
+ ]));
2045
+ let generatedDefault;
2046
+ if (execution !== void 0) {
2047
+ input.writtenExecutionDefaults.add(execution);
2048
+ const built = buildExecutionDefault({
2049
+ executionDefault: execution,
2050
+ codecId: column.codecId,
2051
+ coordinate
2052
+ });
2053
+ if (built.kind === "temporal") {
2054
+ typeName = `temporal.${built.phases.presetName}`;
2055
+ typeConstructor = {
2056
+ kind: "typeConstructor",
2057
+ path: ["temporal", built.phases.presetName],
2058
+ args: temporalPresetArguments({
2059
+ phases: built.phases,
2060
+ precision: column.typeParams?.["precision"]
2061
+ }),
2062
+ span: SYNTHETIC_SPAN
2063
+ };
2064
+ } else if (column.default !== void 0) refuseGeneratorWithDatabaseDefault({
2065
+ coordinate,
2066
+ onCreate: execution.onCreate?.id
2067
+ });
2068
+ else generatedDefault = built.attribute;
2069
+ }
2070
+ fields.push({
2071
+ kind: "field",
2072
+ name: fieldName,
2073
+ typeName,
2074
+ ...ifDefined("typeConstructor", typeConstructor),
2075
+ optional: field.nullable,
2076
+ list: field.many === true,
2077
+ attributes: scalarFieldAttributes({
2078
+ column,
2079
+ fieldName,
2080
+ namespaceId: entry.namespaceId,
2081
+ tableName: entry.tableName,
2082
+ columnName,
2083
+ isSingleColumnId: primaryKeyColumns.length === 1 && primaryKeyColumns[0] === columnName,
2084
+ primaryKeyName: entry.table.primaryKey?.name,
2085
+ pslTypeName: columnType.typeName,
2086
+ isEnum: column.codecId === PG_ENUM_CODEC_ID,
2087
+ domainEnum: column.codecId === "pg/enum@1" || column.valueSet === void 0 ? void 0 : domainEnums[column.valueSet.entityName],
2088
+ generatedDefault,
2089
+ context
2090
+ }),
2091
+ span: SYNTHETIC_SPAN
2092
+ });
2093
+ }
2094
+ return fields;
2095
+ }
2096
+ /** The native enums of one namespace, keyed as the contract keys them. */
2097
+ function nativeEnumsOf(namespaceId, entries) {
2098
+ const nativeEnums = /* @__PURE__ */ new Map();
2099
+ for (const [name, entity] of Object.entries(entries["native_enum"] ?? {})) {
2100
+ invariant(PostgresNativeEnum.is(entity), `"native_enum" entry "${name}" in namespace "${namespaceId}" is not a native enum`);
2101
+ nativeEnums.set(name, entity);
2102
+ }
2103
+ return nativeEnums;
2104
+ }
2105
+ /** The value sets the PSL source derives for a namespace from the enum blocks written for it. */
2106
+ function derivedValueSetsOf(namespaceId, enums, defaultDomainEnums) {
2107
+ const derived = new Map(enums.derivedValueSets);
2108
+ if (namespaceId !== "public") return derived;
2109
+ for (const [name, domainEnum] of Object.entries(defaultDomainEnums)) {
2110
+ if (derived.has(name)) refuseEnumAndNativeEnumSharingName(namespaceId, name);
2111
+ derived.set(name, domainEnum.members.map((member) => member.value));
2112
+ }
2113
+ return derived;
2114
+ }
2115
+ /** One model of a namespace, with its fields and attributes. */
2116
+ function buildModel(all, entry, enums, rlsTables) {
2117
+ const { models, variants, relationsByModel, byCoordinate } = all;
2118
+ refuseUnwritableName("model", entry.name);
2119
+ refuseModelOwner(entry);
2120
+ const variant = variants.get(entry);
2121
+ if (variant !== void 0 && !variant.singleTable) refuseUnderivedVariantLink(entry, variant);
2122
+ const singleTableVariants = models.filter((other) => other !== entry && variants.get(other)?.singleTable === true && variants.get(other)?.base === entry);
2123
+ const travelledForeignKeys = /* @__PURE__ */ new Set();
2124
+ const fields = [...buildScalarFields({
2125
+ entry,
2126
+ variant,
2127
+ enums,
2128
+ domainEnums: all.contract.domain.namespaces[entry.namespaceId]?.enum ?? {},
2129
+ typeMap: all.typeMap,
2130
+ context: all.context,
2131
+ executionDefaults: all.executionDefaults,
2132
+ writtenExecutionDefaults: all.writtenExecutionDefaults,
2133
+ defaultDomainEnumNames: new Set(Object.keys(all.defaultDomainEnums)),
2134
+ namedTypes: all.contract.storage.types ?? {}
2135
+ }), ...buildRelationFields({
2136
+ entry,
2137
+ variant,
2138
+ relations: relationsByModel.get(modelCoordinate(entry.namespaceId, entry.name)) ?? [],
2139
+ relationsByModel,
2140
+ modelsByCoordinate: byCoordinate,
2141
+ pinned: all.pinned,
2142
+ travelledForeignKeys
2143
+ })];
2144
+ if (variant?.singleTable !== true) for (const other of singleTableVariants) for (const relation of relationsByModel.get(modelCoordinate(entry.namespaceId, other.name)) ?? []) {
2145
+ const target = byCoordinate.get(relation.targetCoordinate);
2146
+ const fk = target === void 0 ? void 0 : foreignKeyFor(relation, target);
2147
+ if (fk !== void 0) travelledForeignKeys.add(fk);
2148
+ }
2149
+ refuseUntravelledForeignKeys(entry, variant, travelledForeignKeys);
2150
+ const checks = derivedChecks({
2151
+ table: entry.table,
2152
+ tableName: entry.tableName,
2153
+ managed: effectiveControlPolicy(entry.table.control, all.contract.defaultControlPolicy) === "managed",
2154
+ domainEnumValues: all.domainEnumValues
2155
+ });
2156
+ if (variant?.singleTable !== true) refuseUnderivedChecks(entry, checks);
2157
+ return {
2158
+ kind: "model",
2159
+ name: entry.name,
2160
+ fields,
2161
+ attributes: buildModelAttributes({
2162
+ entry,
2163
+ variant,
2164
+ singleTableVariants,
2165
+ derivedChecksByName: checks,
2166
+ rlsEnabled: rlsTables.has(entry.tableName)
2167
+ }),
2168
+ span: SYNTHETIC_SPAN
2169
+ };
2170
+ }
2171
+ /**
2172
+ * The namespace block of one storage namespace: its models, value objects, enum blocks, roles and
2173
+ * policies. `undefined` when the namespace holds none of them.
2174
+ */
2175
+ function buildNamespace(all, namespaceId, namespace) {
2176
+ const { contract, models, variants } = all;
2177
+ refuseUnprintedEntryKinds(namespaceId, namespace.entries);
2178
+ const valueSets = new Map(Object.entries(namespace.entries.valueSet ?? {}).map(([name, valueSet]) => [name, valueSet.values]));
2179
+ const enums = buildNativeEnumBlocksForNamespace({
2180
+ namespaceId,
2181
+ nativeEnums: nativeEnumsOf(namespaceId, namespace.entries),
2182
+ valueSets,
2183
+ columns: models.filter((entry) => entry.namespaceId === namespaceId).flatMap((entry) => Object.values(entry.table.columns))
2184
+ });
2185
+ refuseUnderivedValueSets({
2186
+ namespaceId,
2187
+ actual: valueSets,
2188
+ derived: derivedValueSetsOf(namespaceId, enums, all.defaultDomainEnums)
2189
+ });
2190
+ const rlsTables = rlsEnabledTables(namespaceId, namespace.entries["rls"]);
2191
+ const namespaceModels = models.filter((entry) => entry.namespaceId === namespaceId).map((entry) => buildModel(all, entry, enums, rlsTables));
2192
+ const compositeTypes = buildCompositeTypes({
2193
+ contract,
2194
+ namespaceId,
2195
+ typeMap: all.typeMap,
2196
+ context: all.context,
2197
+ enumBlockNames: enums.blockNamesByTypeName
2198
+ });
2199
+ const modelNameForTable = (tableName) => models.find((entry) => entry.namespaceId === namespaceId && entry.tableName === tableName && variants.get(entry)?.singleTable !== true)?.name;
2200
+ for (const tableName of rlsTables) if (modelNameForTable(tableName) === void 0) refuseRlsWithoutModel(namespaceId, tableName);
2201
+ const blocks = [
2202
+ ...enums.blocks,
2203
+ ...buildRoleBlocks(namespaceId, namespace.entries["role"]),
2204
+ ...buildPolicyBlocks({
2205
+ namespaceId,
2206
+ entries: namespace.entries["policy"],
2207
+ modelNameForTable,
2208
+ rlsTables
2209
+ })
2210
+ ];
2211
+ if (namespaceModels.length === 0 && blocks.length === 0 && compositeTypes.length === 0) return;
2212
+ refuseNamespaceNamedUnbound(namespaceId);
2213
+ const name = pslNamespaceName(namespaceId);
2214
+ refuseUnwritableName("namespace", name);
2215
+ return makePslNamespace({
2216
+ kind: "namespace",
2217
+ name,
2218
+ entries: makePslNamespaceEntries(namespaceModels, compositeTypes, blocks),
2219
+ span: SYNTHETIC_SPAN
2220
+ });
2221
+ }
2222
+ function refuseUnwritableTableNames(contract) {
2223
+ for (const domainNamespace of Object.values(contract.domain.namespaces)) for (const model of Object.values(domainNamespace.models)) refuseUnwritableMappedName("table", blindCast(model.storage).table);
2224
+ }
2225
+ /**
2226
+ * Builds the Prisma 8 PSL document a Postgres contract was, or would have been, authored as: every
2227
+ * model with its columns, keys, indexes and relations, every value object, every named type and
2228
+ * every native enum, in the namespace block that carries it.
2229
+ *
2230
+ * Read back by the PSL contract source with the same stack, the document yields the contract it was
2231
+ * built from. Anything the language cannot carry is refused by name. `contract` must be one the
2232
+ * Postgres contract serializer accepted: its structure is asserted, not checked again.
2233
+ */
2234
+ function buildPostgresPslContract(contract, context) {
2235
+ refuseUnwritableTableNames(contract);
2236
+ const models = indexContractModels(contract);
2237
+ refuseDuplicateModelNames(models);
2238
+ const byCoordinate = modelsByCoordinate(models);
2239
+ const relations = collectRelations(models);
2240
+ const byModel = relationsByModel(relations);
2241
+ const defaultDomainEnums = contract.domain.namespaces["public"]?.enum ?? {};
2242
+ const all = {
2243
+ contract,
2244
+ context,
2245
+ typeMap: createPostgresTypeMap(),
2246
+ models,
2247
+ byCoordinate,
2248
+ variants: new Map(models.map((entry) => [entry, variantInfo(entry, byCoordinate)])),
2249
+ relationsByModel: byModel,
2250
+ pinned: resolvePinnedRelations(relations, byModel),
2251
+ executionDefaults: executionDefaultsByColumn(contract),
2252
+ writtenExecutionDefaults: /* @__PURE__ */ new Set(),
2253
+ defaultDomainEnums,
2254
+ domainEnumValues: new Map(Object.entries(defaultDomainEnums).map(([name, domainEnum]) => [name, domainEnum.members.map((member) => member.value)]))
2255
+ };
2256
+ const namespaces = [];
2257
+ refuseEnumsOutsideDefaultNamespace(contract);
2258
+ const topLevelEnums = buildDomainEnumBlocks(defaultDomainEnums);
2259
+ if (topLevelEnums.length > 0) namespaces.push(makePslNamespace({
2260
+ kind: "namespace",
2261
+ name: UNSPECIFIED_PSL_NAMESPACE_ID,
2262
+ entries: makePslNamespaceEntries([], [], topLevelEnums),
2263
+ span: SYNTHETIC_SPAN
2264
+ }));
2265
+ const writtenStorageNamespaces = /* @__PURE__ */ new Set();
2266
+ for (const [namespaceId, namespace] of Object.entries(contract.storage.namespaces)) {
2267
+ const built = buildNamespace(all, namespaceId, namespace);
2268
+ if (built === void 0) continue;
2269
+ writtenStorageNamespaces.add(namespaceId);
2270
+ namespaces.push(built);
2271
+ }
2272
+ refuseUnmodelledTablesAndColumns(contract, models, all.variants);
2273
+ refuseUnwrittenNamespaces({
2274
+ contract,
2275
+ models,
2276
+ writtenStorageNamespaces
2277
+ });
2278
+ refuseUnwrittenExecutionDefaults(contract, all.writtenExecutionDefaults);
2279
+ refuseContractMeta(contract);
2280
+ refuseUnderivedRoots(contract, models, all.variants);
2281
+ return {
2282
+ kind: "document",
2283
+ sourceId: "<contract>",
2284
+ namespaces,
2285
+ ...ifDefined("types", buildTypesBlock(contract, all.typeMap, context)),
2286
+ span: SYNTHETIC_SPAN
2287
+ };
2288
+ }
2289
+ function postgresRenderDefault(def, column) {
2290
+ if (def.kind === "function") return def.expression;
2291
+ return renderDefaultLiteral(def.value, column);
2292
+ }
2293
+ const postgresTargetDescriptor = {
2294
+ ...postgresTargetDescriptorMeta,
2295
+ contractSerializer: new PostgresContractSerializer(),
2296
+ schemaVerifier: new PostgresSchemaVerifier(),
2297
+ inferPslContract(schema, describedContracts) {
2298
+ PostgresDatabaseSchemaNode.assert(schema);
2299
+ return inferPostgresPslContract(schema, describedContracts);
2300
+ },
2301
+ buildPslContract(contract, context) {
2302
+ return buildPostgresPslContract(contract, context);
2303
+ },
2304
+ diffSchema(input) {
2305
+ return diffPostgresSchema(input);
2306
+ },
2307
+ classifySubjectGranularity: postgresDiffSubjectGranularity,
2308
+ classifyEntityKind: postgresDiffSubjectEntityKind,
2309
+ migrations: {
2310
+ createPlanner(adapter) {
2311
+ return createPostgresMigrationPlanner(adapter);
2312
+ },
2313
+ createRunner(family) {
2314
+ return blindCast(createPostgresMigrationRunner(family));
2315
+ },
2316
+ contractToSchema(contract, frameworkComponents) {
2317
+ const expander = buildNativeTypeExpander(frameworkComponents);
2318
+ return contractToPostgresDatabaseSchemaNode(blindCast(contract), {
2319
+ annotationNamespace: "pg",
2320
+ ...ifDefined("expandNativeType", expander),
2321
+ renderDefault: postgresRenderDefault,
2322
+ resolveDefault: postgresResolveDefault
2323
+ });
2324
+ }
2325
+ },
2326
+ create() {
2327
+ return {
2328
+ familyId: "sql",
2329
+ targetId: "postgres"
2330
+ };
2331
+ },
2332
+ /**
2333
+ * Direct method for SQL-specific usage.
2334
+ * @deprecated Use migrations.createPlanner() for CLI compatibility.
2335
+ */
2336
+ createPlanner(adapter) {
2337
+ return createPostgresMigrationPlanner(adapter);
2338
+ },
2339
+ /**
2340
+ * Direct method for SQL-specific usage.
2341
+ * @deprecated Use migrations.createRunner() for CLI compatibility.
2342
+ */
2343
+ createRunner(family) {
2344
+ return createPostgresMigrationRunner(family);
2345
+ }
2346
+ };
2347
+ //#endregion
2348
+ export { postgresTargetDescriptor as n, postgresRenderDefault as t };
2349
+
2350
+ //# sourceMappingURL=control-CX9tMnuS.mjs.map