@prisma-next/target-postgres 0.11.0-dev.9 → 0.12.0-dev.1

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 (168) hide show
  1. package/dist/{codec-ids-D9fJ4HP5.d.mts → codec-ids-DliyCWPY.d.mts} +1 -1
  2. package/dist/{codec-ids-D9fJ4HP5.d.mts.map → codec-ids-DliyCWPY.d.mts.map} +1 -1
  3. package/dist/codec-ids.d.mts +1 -1
  4. package/dist/{codec-types-CRlHq7Cz.d.mts → codec-types-BF1DXTPs.d.mts} +2 -2
  5. package/dist/codec-types-BF1DXTPs.d.mts.map +1 -0
  6. package/dist/codec-types.d.mts +1 -1
  7. package/dist/{codecs-Dud5KDNk.d.mts → codecs-DuP3d9Au.d.mts} +2 -2
  8. package/dist/{codecs-Dud5KDNk.d.mts.map → codecs-DuP3d9Au.d.mts.map} +1 -1
  9. package/dist/codecs.d.mts +1 -1
  10. package/dist/codecs.d.mts.map +1 -1
  11. package/dist/codecs.mjs.map +1 -1
  12. package/dist/control.d.mts +1 -1
  13. package/dist/control.d.mts.map +1 -1
  14. package/dist/control.mjs +18 -41
  15. package/dist/control.mjs.map +1 -1
  16. package/dist/{data-transform-bmOKkygi.d.mts → data-transform-CAPmAdxS.d.mts} +2 -2
  17. package/dist/data-transform-CAPmAdxS.d.mts.map +1 -0
  18. package/dist/{data-transform-CdtGUWp2.mjs → data-transform-CRkv2T_U.mjs} +1 -1
  19. package/dist/{data-transform-CdtGUWp2.mjs.map → data-transform-CRkv2T_U.mjs.map} +1 -1
  20. package/dist/data-transform.d.mts +1 -1
  21. package/dist/data-transform.mjs +1 -1
  22. package/dist/{default-normalizer-DHCsbfjc.mjs → default-normalizer-DaAhmzBV.mjs} +1 -1
  23. package/dist/{default-normalizer-DHCsbfjc.mjs.map → default-normalizer-DaAhmzBV.mjs.map} +1 -1
  24. package/dist/default-normalizer.d.mts.map +1 -1
  25. package/dist/default-normalizer.mjs +1 -1
  26. package/dist/descriptor-meta-Dvr_77Z3.mjs +13 -0
  27. package/dist/descriptor-meta-Dvr_77Z3.mjs.map +1 -0
  28. package/dist/{descriptor-meta-DLA2xV6B.mjs → descriptor-meta-runtime-ByjztWgs.mjs} +81 -77
  29. package/dist/descriptor-meta-runtime-ByjztWgs.mjs.map +1 -0
  30. package/dist/enum-planning-DrNWCtCp.mjs +0 -0
  31. package/dist/enum-planning-DrNWCtCp.mjs.map +1 -0
  32. package/dist/enum-planning.d.mts +42 -4
  33. package/dist/enum-planning.d.mts.map +1 -1
  34. package/dist/enum-planning.mjs +2 -2
  35. package/dist/{errors--zafB5_n.mjs → errors-BbnITmAD.mjs} +1 -1
  36. package/dist/{errors--zafB5_n.mjs.map → errors-BbnITmAD.mjs.map} +1 -1
  37. package/dist/errors.d.mts.map +1 -1
  38. package/dist/errors.mjs +1 -1
  39. package/dist/{issue-planner-Ct9xNqbr.mjs → issue-planner-2RgYsjUJ.mjs} +113 -56
  40. package/dist/issue-planner-2RgYsjUJ.mjs.map +1 -0
  41. package/dist/issue-planner.d.mts +1 -1
  42. package/dist/issue-planner.d.mts.map +1 -1
  43. package/dist/issue-planner.mjs +1 -1
  44. package/dist/migration.d.mts +3 -3
  45. package/dist/migration.d.mts.map +1 -1
  46. package/dist/migration.mjs +3 -3
  47. package/dist/migration.mjs.map +1 -1
  48. package/dist/{native-type-normalizer-DMikJJ1V.mjs → native-type-normalizer-BNEQ9VDs.mjs} +1 -1
  49. package/dist/{native-type-normalizer-DMikJJ1V.mjs.map → native-type-normalizer-BNEQ9VDs.mjs.map} +1 -1
  50. package/dist/native-type-normalizer.d.mts.map +1 -1
  51. package/dist/native-type-normalizer.mjs +1 -1
  52. package/dist/{op-factory-call-Drccm_JD.d.mts → op-factory-call-CDlImOF_.d.mts} +3 -3
  53. package/dist/op-factory-call-CDlImOF_.d.mts.map +1 -0
  54. package/dist/{op-factory-call-CB6tPJ3f.mjs → op-factory-call-C_K5ibAY.mjs} +2 -2
  55. package/dist/{op-factory-call-CB6tPJ3f.mjs.map → op-factory-call-C_K5ibAY.mjs.map} +1 -1
  56. package/dist/op-factory-call.d.mts +1 -1
  57. package/dist/op-factory-call.mjs +1 -1
  58. package/dist/pack.d.mts +9 -8
  59. package/dist/pack.d.mts.map +1 -1
  60. package/dist/pack.mjs +1 -1
  61. package/dist/{planner-DlhK35aV.mjs → planner-CC3r_uNJ.mjs} +17 -25
  62. package/dist/planner-CC3r_uNJ.mjs.map +1 -0
  63. package/dist/{planner-ddl-builders--0TmW6Ey.mjs → planner-ddl-builders-DgyqpFji.mjs} +3 -3
  64. package/dist/{planner-ddl-builders--0TmW6Ey.mjs.map → planner-ddl-builders-DgyqpFji.mjs.map} +1 -1
  65. package/dist/planner-ddl-builders.d.mts +1 -1
  66. package/dist/planner-ddl-builders.d.mts.map +1 -1
  67. package/dist/planner-ddl-builders.mjs +1 -1
  68. package/dist/{planner-identity-values-ojX-6cPV.mjs → planner-identity-values-nhVj0hp-.mjs} +1 -1
  69. package/dist/{planner-identity-values-ojX-6cPV.mjs.map → planner-identity-values-nhVj0hp-.mjs.map} +1 -1
  70. package/dist/planner-identity-values.d.mts.map +1 -1
  71. package/dist/planner-identity-values.mjs +1 -1
  72. package/dist/{planner-produced-postgres-migration-p-VKkCia.d.mts → planner-produced-postgres-migration-D02NOhVQ.d.mts} +3 -3
  73. package/dist/planner-produced-postgres-migration-D02NOhVQ.d.mts.map +1 -0
  74. package/dist/{planner-produced-postgres-migration-TJWH2m_x.mjs → planner-produced-postgres-migration-D_nsXbhl.mjs} +5 -7
  75. package/dist/planner-produced-postgres-migration-D_nsXbhl.mjs.map +1 -0
  76. package/dist/planner-produced-postgres-migration.d.mts +1 -1
  77. package/dist/planner-produced-postgres-migration.mjs +1 -1
  78. package/dist/{planner-schema-lookup-BGyukuzG.mjs → planner-schema-lookup-CGxxYfnD.mjs} +1 -1
  79. package/dist/{planner-schema-lookup-BGyukuzG.mjs.map → planner-schema-lookup-CGxxYfnD.mjs.map} +1 -1
  80. package/dist/planner-schema-lookup.d.mts.map +1 -1
  81. package/dist/planner-schema-lookup.mjs +1 -1
  82. package/dist/{planner-sql-checks-BDtJQ9WD.mjs → planner-sql-checks-BMu3fiMc.mjs} +3 -3
  83. package/dist/{planner-sql-checks-BDtJQ9WD.mjs.map → planner-sql-checks-BMu3fiMc.mjs.map} +1 -1
  84. package/dist/planner-sql-checks.d.mts.map +1 -1
  85. package/dist/planner-sql-checks.mjs +1 -1
  86. package/dist/{planner-target-details-CIj61DUj.d.mts → planner-target-details-a_wuOiYf.d.mts} +1 -1
  87. package/dist/{planner-target-details-CIj61DUj.d.mts.map → planner-target-details-a_wuOiYf.d.mts.map} +1 -1
  88. package/dist/planner-target-details.d.mts +1 -1
  89. package/dist/planner.d.mts +2 -7
  90. package/dist/planner.d.mts.map +1 -1
  91. package/dist/planner.mjs +1 -1
  92. package/dist/{postgres-contract-serializer-CYct4Y7O.mjs → postgres-contract-serializer-C0UtIDB8.mjs} +3 -3
  93. package/dist/postgres-contract-serializer-C0UtIDB8.mjs.map +1 -0
  94. package/dist/{postgres-enum-type-CNhPTDhy.d.mts → postgres-enum-type-5MBoKsIj.d.mts} +1 -1
  95. package/dist/postgres-enum-type-5MBoKsIj.d.mts.map +1 -0
  96. package/dist/postgres-enum-type-DS-KLVRH.mjs.map +1 -1
  97. package/dist/{postgres-migration-uADmx0dW.mjs → postgres-migration-BatbEvU6.mjs} +3 -3
  98. package/dist/{postgres-migration-uADmx0dW.mjs.map → postgres-migration-BatbEvU6.mjs.map} +1 -1
  99. package/dist/{postgres-migration-Fd4fQkBw.d.mts → postgres-migration-DRY8V-bQ.d.mts} +3 -3
  100. package/dist/{postgres-migration-Fd4fQkBw.d.mts.map → postgres-migration-DRY8V-bQ.d.mts.map} +1 -1
  101. package/dist/{postgres-schema-BL0RAvew.mjs → postgres-schema-vp5rvbYg.mjs} +12 -19
  102. package/dist/postgres-schema-vp5rvbYg.mjs.map +1 -0
  103. package/dist/{render-ops-BC2PtCkj.mjs → render-ops-XhICjX_P.mjs} +1 -1
  104. package/dist/{render-ops-BC2PtCkj.mjs.map → render-ops-XhICjX_P.mjs.map} +1 -1
  105. package/dist/render-ops.d.mts +1 -1
  106. package/dist/render-ops.d.mts.map +1 -1
  107. package/dist/render-ops.mjs +1 -1
  108. package/dist/{render-typescript-CI1wbgUc.mjs → render-typescript-K125n-RZ.mjs} +2 -3
  109. package/dist/render-typescript-K125n-RZ.mjs.map +1 -0
  110. package/dist/render-typescript.d.mts +0 -1
  111. package/dist/render-typescript.d.mts.map +1 -1
  112. package/dist/render-typescript.mjs +1 -1
  113. package/dist/runtime.d.mts.map +1 -1
  114. package/dist/runtime.mjs +3 -3
  115. package/dist/runtime.mjs.map +1 -1
  116. package/dist/{shared-ByhSooBS.d.mts → shared-Do_a5ymU.d.mts} +2 -2
  117. package/dist/shared-Do_a5ymU.d.mts.map +1 -0
  118. package/dist/{sql-utils-BewXAnsG.mjs → sql-utils-CggjWNij.mjs} +1 -1
  119. package/dist/{sql-utils-BewXAnsG.mjs.map → sql-utils-CggjWNij.mjs.map} +1 -1
  120. package/dist/sql-utils.d.mts.map +1 -1
  121. package/dist/sql-utils.mjs +1 -1
  122. package/dist/{statement-builders-vImtdfmM.mjs → statement-builders-DVI5IVAa.mjs} +1 -1
  123. package/dist/statement-builders-DVI5IVAa.mjs.map +1 -0
  124. package/dist/statement-builders.d.mts +1 -1
  125. package/dist/statement-builders.d.mts.map +1 -1
  126. package/dist/statement-builders.mjs +1 -1
  127. package/dist/{tables-Vhh4k5yz.mjs → tables-C8RrPLUq.mjs} +3 -3
  128. package/dist/{tables-Vhh4k5yz.mjs.map → tables-C8RrPLUq.mjs.map} +1 -1
  129. package/dist/{types-D-XIpzHA.d.mts → types-O40IcFV9.d.mts} +1 -1
  130. package/dist/types-O40IcFV9.d.mts.map +1 -0
  131. package/dist/types.d.mts +12 -16
  132. package/dist/types.d.mts.map +1 -1
  133. package/dist/types.mjs +1 -1
  134. package/package.json +29 -18
  135. package/src/core/authoring.ts +1 -1
  136. package/src/core/descriptor-meta-runtime.ts +28 -0
  137. package/src/core/descriptor-meta.ts +2 -6
  138. package/src/core/migrations/enum-planning.ts +134 -14
  139. package/src/core/migrations/issue-planner.ts +20 -11
  140. package/src/core/migrations/planner-produced-postgres-migration.ts +0 -2
  141. package/src/core/migrations/planner-strategies.ts +138 -40
  142. package/src/core/migrations/planner.ts +9 -21
  143. package/src/core/migrations/render-typescript.ts +1 -5
  144. package/src/core/migrations/runner.ts +20 -61
  145. package/src/core/migrations/statement-builders.ts +1 -1
  146. package/src/core/migrations/verify-postgres-namespaces.ts +6 -6
  147. package/src/core/postgres-contract-serializer.ts +4 -4
  148. package/src/core/postgres-schema.ts +10 -20
  149. package/src/exports/control.ts +16 -0
  150. package/src/exports/enum-planning.ts +5 -0
  151. package/src/exports/runtime.ts +2 -2
  152. package/dist/codec-types-CRlHq7Cz.d.mts.map +0 -1
  153. package/dist/data-transform-bmOKkygi.d.mts.map +0 -1
  154. package/dist/descriptor-meta-DLA2xV6B.mjs.map +0 -1
  155. package/dist/enum-planning-Bqp96iIw.mjs +0 -63
  156. package/dist/enum-planning-Bqp96iIw.mjs.map +0 -1
  157. package/dist/issue-planner-Ct9xNqbr.mjs.map +0 -1
  158. package/dist/op-factory-call-Drccm_JD.d.mts.map +0 -1
  159. package/dist/planner-DlhK35aV.mjs.map +0 -1
  160. package/dist/planner-produced-postgres-migration-TJWH2m_x.mjs.map +0 -1
  161. package/dist/planner-produced-postgres-migration-p-VKkCia.d.mts.map +0 -1
  162. package/dist/postgres-contract-serializer-CYct4Y7O.mjs.map +0 -1
  163. package/dist/postgres-enum-type-CNhPTDhy.d.mts.map +0 -1
  164. package/dist/postgres-schema-BL0RAvew.mjs.map +0 -1
  165. package/dist/render-typescript-CI1wbgUc.mjs.map +0 -1
  166. package/dist/shared-ByhSooBS.d.mts.map +0 -1
  167. package/dist/statement-builders-vImtdfmM.mjs.map +0 -1
  168. package/dist/types-D-XIpzHA.d.mts.map +0 -1
@@ -5,9 +5,138 @@
5
5
  */
6
6
 
7
7
  import { arraysEqual } from '@prisma-next/family-sql/schema-verify';
8
+ import { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';
9
+ import type { PostgresEnumStorageEntry, SqlStorage } from '@prisma-next/sql-contract/types';
8
10
  import type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';
9
11
  import { PG_ENUM_CODEC_ID } from '../codec-ids';
10
12
  import type { PostgresEnumType } from '../postgres-enum-type';
13
+ import { isPostgresSchema } from '../postgres-schema';
14
+
15
+ /**
16
+ * Codec-typed enum entry shape stored under
17
+ * `schema.annotations.pg.storageTypes[(schemaName, nativeType)]`.
18
+ */
19
+ interface PgStorageTypeEntry {
20
+ readonly codecId?: string;
21
+ readonly typeParams?: { readonly values?: unknown };
22
+ }
23
+
24
+ /** Postgres-specific subtree on family `SqlSchemaIR.annotations`. */
25
+ export interface PostgresSchemaIrAnnotations {
26
+ readonly schema?: string;
27
+ readonly storageTypes?: Readonly<Record<string, PgStorageTypeEntry>>;
28
+ }
29
+
30
+ function readOptionalString(value: unknown): string | undefined {
31
+ return typeof value === 'string' ? value : undefined;
32
+ }
33
+
34
+ function readPgStorageTypeEntry(value: unknown): PgStorageTypeEntry | undefined {
35
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
36
+ return undefined;
37
+ }
38
+ const codecId = Reflect.get(value, 'codecId');
39
+ const typeParamsRaw = Reflect.get(value, 'typeParams');
40
+ const typeParams =
41
+ typeParamsRaw !== undefined &&
42
+ typeParamsRaw !== null &&
43
+ typeof typeParamsRaw === 'object' &&
44
+ !Array.isArray(typeParamsRaw)
45
+ ? { values: Reflect.get(typeParamsRaw, 'values') }
46
+ : undefined;
47
+ return {
48
+ ...(typeof codecId === 'string' ? { codecId } : {}),
49
+ ...(typeParams !== undefined ? { typeParams } : {}),
50
+ };
51
+ }
52
+
53
+ function readPgStorageTypesMap(
54
+ value: unknown,
55
+ ): Readonly<Record<string, PgStorageTypeEntry>> | undefined {
56
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
57
+ return undefined;
58
+ }
59
+ const entries: Record<string, PgStorageTypeEntry> = {};
60
+ for (const [key, entryValue] of Object.entries(value)) {
61
+ const entry = readPgStorageTypeEntry(entryValue);
62
+ if (entry !== undefined) {
63
+ entries[key] = entry;
64
+ }
65
+ }
66
+ return Object.keys(entries).length > 0 ? entries : undefined;
67
+ }
68
+
69
+ /**
70
+ * Reads the Postgres annotation envelope (`schema.annotations.pg`) from
71
+ * family Schema IR. `SqlAnnotations` is an open target-pack extensibility
72
+ * map (`Record<string, unknown>`); this accessor narrows the `pg` slot at
73
+ * runtime so Postgres code can read introspection fields without casts.
74
+ */
75
+ export function readPostgresSchemaIrAnnotations(schema: SqlSchemaIR): PostgresSchemaIrAnnotations {
76
+ const raw = schema.annotations?.['pg'];
77
+ if (raw === undefined || raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
78
+ return {};
79
+ }
80
+ const schemaField = readOptionalString(Reflect.get(raw, 'schema'));
81
+ const storageTypes = readPgStorageTypesMap(Reflect.get(raw, 'storageTypes'));
82
+ return {
83
+ ...(schemaField !== undefined ? { schema: schemaField } : {}),
84
+ ...(storageTypes !== undefined ? { storageTypes } : {}),
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Separator for `(schemaName, nativeType)` keys in introspected
90
+ * `schema.annotations.pg.storageTypes`. NUL cannot appear in Postgres
91
+ * identifiers, so the pair is unambiguous.
92
+ */
93
+ export const ENUM_STORAGE_KEY_SEP = '\u0000';
94
+
95
+ /** Builds the schema-qualified storageTypes map key for a live Postgres enum. */
96
+ export function enumStorageCompoundKey(schemaName: string, nativeType: string): string {
97
+ return `${schemaName}${ENUM_STORAGE_KEY_SEP}${nativeType}`;
98
+ }
99
+
100
+ /**
101
+ * Resolves the live-schema name a namespace's enums are introspected under,
102
+ * for keying `readExistingEnumValues` lookups. The unbound namespace's
103
+ * `ddlSchemaName` is a planner-emit sentinel (`__unbound__`) that never names a
104
+ * real schema, so for the unbound coordinate we read the *introspected* schema
105
+ * recorded on `annotations.pg.schema` (the live `current_schema()` the adapter
106
+ * walked) — that is the schema the enum's `storageTypes` entry is keyed under.
107
+ * Named namespaces resolve to their own DDL schema, which matches the
108
+ * per-schema introspection key directly.
109
+ */
110
+ export function resolveDdlSchemaForNamespaceStorage(
111
+ storage: SqlStorage,
112
+ namespaceId: string,
113
+ schemaIr?: SqlSchemaIR,
114
+ ): string {
115
+ if (namespaceId === UNBOUND_NAMESPACE_ID) {
116
+ return (schemaIr ? readPostgresSchemaIrAnnotations(schemaIr).schema : undefined) ?? 'public';
117
+ }
118
+ const namespace = storage.namespaces[namespaceId];
119
+ if (namespace && isPostgresSchema(namespace)) {
120
+ return namespace.ddlSchemaName(storage);
121
+ }
122
+ return namespaceId;
123
+ }
124
+
125
+ /** Contract-scoped bridge for the family verifier's enum value resolver. */
126
+ export function createResolveExistingEnumValues(
127
+ storage: SqlStorage,
128
+ ): (
129
+ schema: SqlSchemaIR,
130
+ enumType: PostgresEnumStorageEntry,
131
+ namespaceId: string,
132
+ ) => readonly string[] | null {
133
+ return (schema, enumType, namespaceId) =>
134
+ readExistingEnumValues(
135
+ schema,
136
+ resolveDdlSchemaForNamespaceStorage(storage, namespaceId, schema),
137
+ enumType.nativeType,
138
+ );
139
+ }
11
140
 
12
141
  /**
13
142
  * Categorisation of how an existing enum type's values relate to the
@@ -19,7 +148,7 @@ export type EnumDiff =
19
148
  | { readonly kind: 'rebuild'; readonly removedValues: readonly string[] };
20
149
 
21
150
  /**
22
- * Reads existing enum values for `nativeType` from the
151
+ * Reads existing enum values for `(schemaName, nativeType)` from the
23
152
  * Postgres-introspected `schema.annotations.pg.storageTypes` map.
24
153
  *
25
154
  * Schema IR's `storageTypes` slots are always codec-typed
@@ -33,20 +162,11 @@ export type EnumDiff =
33
162
  */
34
163
  export function readExistingEnumValues(
35
164
  schema: SqlSchemaIR,
165
+ schemaName: string,
36
166
  nativeType: string,
37
167
  ): readonly string[] | null {
38
- const storageTypes = (schema.annotations?.['pg'] as Record<string, unknown> | undefined)?.[
39
- 'storageTypes'
40
- ] as
41
- | Record<
42
- string,
43
- {
44
- codecId?: string;
45
- typeParams?: { values?: unknown };
46
- }
47
- >
48
- | undefined;
49
- const existing = storageTypes?.[nativeType];
168
+ const storageTypes = readPostgresSchemaIrAnnotations(schema).storageTypes;
169
+ const existing = storageTypes?.[enumStorageCompoundKey(schemaName, nativeType)];
50
170
  if (!existing || existing.codecId !== PG_ENUM_CODEC_ID) {
51
171
  return null;
52
172
  }
@@ -54,7 +174,7 @@ export function readExistingEnumValues(
54
174
  if (!Array.isArray(enumValues) || !enumValues.every((v) => typeof v === 'string')) {
55
175
  return null;
56
176
  }
57
- return enumValues as readonly string[];
177
+ return enumValues;
58
178
  }
59
179
 
60
180
  /**
@@ -63,13 +63,18 @@ import {
63
63
 
64
64
  export type { CallMigrationStrategy, StrategyContext };
65
65
 
66
- function locateNamespaceTypeInStorage(storage: SqlStorage, typeName: string): unknown {
67
- for (const ns of Object.values(storage.namespaces)) {
68
- if (!('enum' in ns) || ns.enum == null) continue;
69
- const entry = (ns.enum as Record<string, unknown>)[typeName];
70
- if (entry !== undefined) return entry;
71
- }
72
- return undefined;
66
+ /**
67
+ * Finds a type entry by explicit namespace coordinate. Reads the named
68
+ * namespace's `enum` slot directly never scans other namespaces.
69
+ */
70
+ function locateNamespaceTypeInStorage(
71
+ storage: SqlStorage,
72
+ namespaceId: string,
73
+ typeName: string,
74
+ ): unknown {
75
+ const ns = storage.namespaces[namespaceId];
76
+ if (!ns || !('enum' in ns) || ns.enum == null) return undefined;
77
+ return (ns.enum as Record<string, unknown>)[typeName];
73
78
  }
74
79
 
75
80
  // ============================================================================
@@ -596,11 +601,14 @@ function mapIssueToCall(
596
601
  case 'type_missing': {
597
602
  if (!issue.typeName)
598
603
  return notOk(issueConflict('unsupportedOperation', 'Type missing issue has no typeName'));
599
- // Enum types live in namespace.enum; codec aliases live in storage.types.
600
- // Check both so the planner handles whichever slot the type is in.
604
+ // Codec aliases live in storage.types; enum types live in namespace.enum.
605
+ // Check types first; fall back to the namespace-keyed enum slot using the
606
+ // issue's namespace coordinate (populated by the verifier for enum-related
607
+ // issues per the BaseSchemaIssue.namespaceId contract).
608
+ const namespaceId = resolveNamespaceIdForIssue(issue);
601
609
  const typeInstance: unknown =
602
610
  ctx.toContract.storage.types?.[issue.typeName] ??
603
- locateNamespaceTypeInStorage(ctx.toContract.storage, issue.typeName);
611
+ locateNamespaceTypeInStorage(ctx.toContract.storage, namespaceId, issue.typeName);
604
612
  if (!typeInstance) {
605
613
  return notOk(
606
614
  issueConflict(
@@ -610,9 +618,10 @@ function mapIssueToCall(
610
618
  );
611
619
  }
612
620
  if (typeInstance instanceof PostgresEnumType) {
621
+ const ddlSchema = resolveDdlSchemaForNamespace(ctx, namespaceId);
613
622
  return ok([
614
623
  new CreateEnumTypeCall(
615
- schemaName,
624
+ ddlSchema,
616
625
  issue.typeName,
617
626
  typeInstance.values,
618
627
  typeInstance.nativeType,
@@ -29,7 +29,6 @@ import type {
29
29
  OpFactoryCall,
30
30
  } from '@prisma-next/framework-components/control';
31
31
  import type { MigrationMeta } from '@prisma-next/migration-tools/migration';
32
- import { ifDefined } from '@prisma-next/utils/defined';
33
32
  import type { PostgresPlanTargetDetails } from './planner-target-details';
34
33
  import { PostgresMigration } from './postgres-migration';
35
34
  import { renderOps } from './render-ops';
@@ -73,7 +72,6 @@ export class TypeScriptRenderablePostgresMigration
73
72
  return renderCallsToTypeScript(this.#calls, {
74
73
  from: this.#meta.from,
75
74
  to: this.#meta.to,
76
- ...ifDefined('labels', this.#meta.labels),
77
75
  });
78
76
  }
79
77
  }
@@ -37,7 +37,11 @@ import {
37
37
  import type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';
38
38
  import { PostgresEnumType } from '../postgres-enum-type';
39
39
  import { isPostgresSchema } from '../postgres-schema';
40
- import { determineEnumDiff, readExistingEnumValues } from './enum-planning';
40
+ import {
41
+ determineEnumDiff,
42
+ readExistingEnumValues,
43
+ resolveDdlSchemaForNamespaceStorage,
44
+ } from './enum-planning';
41
45
  import {
42
46
  AddColumnCall,
43
47
  AddEnumValuesCall,
@@ -108,12 +112,12 @@ export function resolveNamespaceIdForIssue(issue: { readonly namespaceId?: strin
108
112
  /**
109
113
  * Resolve the DDL schema name for a namespace coordinate. Postgres-aware
110
114
  * namespaces dispatch to their polymorphic `ddlSchemaName` override —
111
- * named schemas return their own id and the unbound singleton projects
112
- * to `'public'` (sibling-present) or the framework sentinel
113
- * (sibling-absent). Legacy single-namespace contracts whose `__unbound__`
114
- * slot is the framework-default `SqlUnboundNamespace` (rather than the
115
- * Postgres-aware `PostgresUnboundSchema`) flow the coordinate through
116
- * unchanged so downstream `qualifyTableName` resolves polymorphically.
115
+ * named schemas return their own id; the unbound singleton returns
116
+ * `UNBOUND_NAMESPACE_ID`. Legacy single-namespace contracts whose
117
+ * `__unbound__` slot is the framework-default `SqlUnboundNamespace`
118
+ * (rather than the Postgres-aware `PostgresUnboundSchema`) flow the
119
+ * coordinate through unchanged so downstream `qualifyTableName`
120
+ * resolves polymorphically.
117
121
  */
118
122
  export function resolveDdlSchemaForNamespace(ctx: StrategyContext, namespaceId: string): string {
119
123
  const namespace = ctx.toContract.storage.namespaces[namespaceId];
@@ -123,21 +127,57 @@ export function resolveDdlSchemaForNamespace(ctx: StrategyContext, namespaceId:
123
127
  return namespaceId;
124
128
  }
125
129
 
130
+ /** Default Postgres enum landing namespace — where contract-level (`types:`)
131
+ * enums are placed by the authoring builder when no explicit namespace is
132
+ * given. Mirrors `POSTGRES_ENUM_NAMESPACE_ID` in the contract-ts builder. */
133
+ const DEFAULT_ENUM_NAMESPACE_ID = 'public';
134
+
135
+ function namespaceHasEnum(storage: SqlStorage, namespaceId: string, typeName: string): boolean {
136
+ const ns = storage.namespaces[namespaceId];
137
+ if (!ns || !('enum' in ns) || ns.enum == null) return false;
138
+ return (ns.enum as Record<string, PostgresEnumStorageEntry>)[typeName] !== undefined;
139
+ }
140
+
126
141
  /**
127
- * Finds a type entry by name across all namespace type registries.
128
- * Namespace types (e.g. Postgres enums) live under
129
- * `storage.namespaces[nsId].enum`, not under `storage.types`.
142
+ * Resolves which namespace's enum a column's bare `typeRef` binds to.
143
+ *
144
+ * Columns carry a bare (non-namespace-qualified) `typeRef`; the enum it names
145
+ * may live in a different namespace than the column's own (the authoring
146
+ * builder places contract-level `types:` enums in the default `public`
147
+ * namespace while a model's table may sit in the unbound namespace). The
148
+ * binding rule: an enum declared in the column's *own* namespace shadows
149
+ * everything; otherwise the column references the ambient enum — the sole
150
+ * namespace that defines `typeName`, preferring the default `public`
151
+ * namespace when several do. Returns `undefined` when no namespace defines it.
152
+ */
153
+ function resolveColumnEnumNamespace(
154
+ storage: SqlStorage,
155
+ columnNamespaceId: string,
156
+ typeName: string,
157
+ ): string | undefined {
158
+ if (namespaceHasEnum(storage, columnNamespaceId, typeName)) return columnNamespaceId;
159
+ const owners = Object.keys(storage.namespaces).filter((nsId) =>
160
+ namespaceHasEnum(storage, nsId, typeName),
161
+ );
162
+ if (owners.length === 1) return owners[0];
163
+ if (owners.includes(DEFAULT_ENUM_NAMESPACE_ID)) return DEFAULT_ENUM_NAMESPACE_ID;
164
+ return owners[0];
165
+ }
166
+
167
+ /**
168
+ * Finds a type entry by explicit namespace coordinate. Namespace types (e.g.
169
+ * Postgres enums) live under `storage.namespaces[nsId].enum`. Returns the
170
+ * entry from the named namespace only — never scans other namespaces, so two
171
+ * namespaces that hold an enum with the same name resolve independently.
130
172
  */
131
173
  function locateNamespaceType(
132
174
  storage: SqlStorage,
175
+ namespaceId: string,
133
176
  typeName: string,
134
177
  ): PostgresEnumStorageEntry | undefined {
135
- for (const ns of Object.values(storage.namespaces)) {
136
- if (!('enum' in ns) || ns.enum == null) continue;
137
- const entry = (ns.enum as Record<string, PostgresEnumStorageEntry>)[typeName];
138
- if (entry !== undefined) return entry;
139
- }
140
- return undefined;
178
+ const ns = storage.namespaces[namespaceId];
179
+ if (!ns || !('enum' in ns) || ns.enum == null) return undefined;
180
+ return (ns.enum as Record<string, PostgresEnumStorageEntry>)[typeName];
141
181
  }
142
182
 
143
183
  // ============================================================================
@@ -369,10 +409,11 @@ export const nullableTighteningCallStrategy: CallMigrationStrategy = (issues, ct
369
409
  };
370
410
 
371
411
  function enumRebuildCallRecipe(
412
+ namespaceId: string,
372
413
  typeName: string,
373
414
  ctx: StrategyContext,
374
415
  ): readonly PostgresOpFactoryCall[] {
375
- const toType = locateNamespaceType(ctx.toContract.storage, typeName);
416
+ const toType = locateNamespaceType(ctx.toContract.storage, namespaceId, typeName);
376
417
  if (!toType) return [];
377
418
  const isEnum = isPostgresEnumStorageEntry(toType);
378
419
  const nativeType = toType.nativeType;
@@ -380,13 +421,28 @@ function enumRebuildCallRecipe(
380
421
  ? toType.values
381
422
  : (((toType as StorageTypeInstance).typeParams['values'] ?? []) as readonly string[]);
382
423
  const tempName = `${nativeType}${REBUILD_SUFFIX}`;
424
+ // Type DDL targets the enum's real schema — the unbound coordinate resolves
425
+ // to the introspected `current_schema()`, never the `__unbound__` sentinel.
426
+ const ddlSchema = resolveDdlSchemaForNamespaceStorage(
427
+ ctx.toContract.storage,
428
+ namespaceId,
429
+ ctx.schema,
430
+ );
383
431
 
432
+ // Migrate every column whose `typeRef` binds to *this* enum. The column's
433
+ // bare `typeRef` resolves to an enum namespace (own-namespace shadows;
434
+ // otherwise the ambient/default `public` enum), so a column in the unbound
435
+ // namespace correctly binds to a `public`-namespace enum, while two
436
+ // same-named enums in distinct namespaces keep their columns disjoint.
384
437
  const columnRefs: { namespaceId: string; table: string; column: string }[] = [];
385
438
  for (const [nsId, ns] of Object.entries(ctx.toContract.storage.namespaces)) {
386
439
  for (const [tableName, tableNode] of Object.entries(ns.tables)) {
387
440
  const table = tableNode as StorageTable;
388
441
  for (const [columnName, column] of Object.entries(table.columns)) {
389
- if (column.typeRef === typeName) {
442
+ if (
443
+ column.typeRef === typeName &&
444
+ resolveColumnEnumNamespace(ctx.toContract.storage, nsId, typeName) === namespaceId
445
+ ) {
390
446
  columnRefs.push({ namespaceId: nsId, table: tableName, column: columnName });
391
447
  }
392
448
  }
@@ -394,7 +450,7 @@ function enumRebuildCallRecipe(
394
450
  }
395
451
 
396
452
  return [
397
- new CreateEnumTypeCall(ctx.schemaName, tempName, desiredValues),
453
+ new CreateEnumTypeCall(ddlSchema, tempName, desiredValues),
398
454
  ...columnRefs.map((ref) => {
399
455
  const using = `${ref.column}::text::${tempName}`;
400
456
  return new AlterColumnTypeCall(
@@ -409,8 +465,8 @@ function enumRebuildCallRecipe(
409
465
  },
410
466
  );
411
467
  }),
412
- new DropEnumTypeCall(ctx.schemaName, nativeType),
413
- new RenameTypeCall(ctx.schemaName, tempName, nativeType),
468
+ new DropEnumTypeCall(ddlSchema, nativeType),
469
+ new RenameTypeCall(ddlSchema, tempName, nativeType),
414
470
  ];
415
471
  }
416
472
 
@@ -450,6 +506,18 @@ function enumRebuildCallRecipe(
450
506
  * into the `dep` bucket — i.e. `CREATE TYPE` runs before any
451
507
  * `CreateTableCall` that references the new enum.
452
508
  */
509
+ /**
510
+ * Separator character for compound enum map keys (`namespaceId\u0000typeName`).
511
+ * NUL (`\u0000`) is invalid in both Postgres identifiers and TypeScript symbol
512
+ * names so it cannot appear in either component — unambiguous separator.
513
+ */
514
+ const COMPOUND_KEY_SEP = '\u0000';
515
+
516
+ /** Builds the compound map key for a namespace-qualified enum entry. */
517
+ function enumCompoundKey(namespaceId: string, typeName: string): string {
518
+ return `${namespaceId}${COMPOUND_KEY_SEP}${typeName}`;
519
+ }
520
+
453
521
  export const nativeEnumPlanCallStrategy: CallMigrationStrategy = (issues, ctx) => {
454
522
  const enumTypes = collectPostgresEnumTypes(ctx.toContract.storage);
455
523
  if (enumTypes.size === 0) return { kind: 'no_match' };
@@ -457,28 +525,42 @@ export const nativeEnumPlanCallStrategy: CallMigrationStrategy = (issues, ctx) =
457
525
  const dataAllowed = ctx.policy.allowedOperationClasses.includes('data');
458
526
 
459
527
  const calls: PostgresOpFactoryCall[] = [];
460
- const handledTypeNames = new Set<string>();
461
- const introducedTypeNames = new Set<string>();
462
- const rebuiltTypeNames = new Set<string>();
528
+ const handledKeys = new Set<string>();
529
+ const introducedKeys = new Set<string>();
530
+ const rebuiltKeys = new Set<string>();
463
531
  let emittedRebuildRecipe = false;
464
532
 
465
- for (const [typeName, enumType] of enumTypes) {
533
+ for (const [key, enumType] of enumTypes) {
534
+ const sepIdx = key.indexOf(COMPOUND_KEY_SEP);
535
+ const enumNamespaceId = key.slice(0, sepIdx);
536
+ const typeName = key.slice(sepIdx + 1);
537
+
466
538
  const desired = enumType.values;
467
- const existing = readExistingEnumValues(ctx.schema, enumType.nativeType);
539
+ // The enum's live schema: for the unbound coordinate this resolves to the
540
+ // introspected `current_schema()` (e.g. `public`), never the `__unbound__`
541
+ // DDL-emit sentinel — so both the existing-values lookup key and the
542
+ // emitted `CREATE TYPE` / `ALTER TYPE` target the real schema the type
543
+ // lives in. Named namespaces resolve to their own DDL schema.
544
+ const ddlSchema = resolveDdlSchemaForNamespaceStorage(
545
+ ctx.toContract.storage,
546
+ enumNamespaceId,
547
+ ctx.schema,
548
+ );
549
+ const existing = readExistingEnumValues(ctx.schema, ddlSchema, enumType.nativeType);
468
550
  if (!existing) {
469
- calls.push(new CreateEnumTypeCall(ctx.schemaName, typeName, desired, enumType.nativeType));
470
- handledTypeNames.add(typeName);
471
- introducedTypeNames.add(typeName);
551
+ calls.push(new CreateEnumTypeCall(ddlSchema, typeName, desired, enumType.nativeType));
552
+ handledKeys.add(key);
553
+ introducedKeys.add(key);
472
554
  continue;
473
555
  }
474
556
  const diff = determineEnumDiff(existing, desired);
475
557
  if (diff.kind === 'unchanged') {
476
- handledTypeNames.add(typeName);
558
+ handledKeys.add(key);
477
559
  continue;
478
560
  }
479
561
  if (diff.kind === 'add_values') {
480
- calls.push(new AddEnumValuesCall(ctx.schemaName, typeName, enumType.nativeType, diff.values));
481
- handledTypeNames.add(typeName);
562
+ calls.push(new AddEnumValuesCall(ddlSchema, typeName, enumType.nativeType, diff.values));
563
+ handledKeys.add(key);
482
564
  continue;
483
565
  }
484
566
  if (dataAllowed && diff.removedValues.length > 0) {
@@ -490,10 +572,10 @@ export const nativeEnumPlanCallStrategy: CallMigrationStrategy = (issues, ctx) =
490
572
  ),
491
573
  );
492
574
  }
493
- calls.push(...enumRebuildCallRecipe(typeName, ctx));
575
+ calls.push(...enumRebuildCallRecipe(enumNamespaceId, typeName, ctx));
494
576
  emittedRebuildRecipe = true;
495
- handledTypeNames.add(typeName);
496
- rebuiltTypeNames.add(typeName);
577
+ handledKeys.add(key);
578
+ rebuiltKeys.add(key);
497
579
  }
498
580
 
499
581
  // The strategy emits a single `recipe` flag for the entire pass,
@@ -505,9 +587,17 @@ export const nativeEnumPlanCallStrategy: CallMigrationStrategy = (issues, ctx) =
505
587
  // enum would fail at runtime with a confusing `type "X" does not
506
588
  // exist` error. Surface the unrepresentable case here as a
507
589
  // planner-time error so the failure mode is loud, not silent.
508
- if (introducedTypeNames.size > 0 && rebuiltTypeNames.size > 0) {
590
+ if (introducedKeys.size > 0 && rebuiltKeys.size > 0) {
591
+ const introducedDisplay = [...introducedKeys]
592
+ .sort()
593
+ .map((k) => k.replace(COMPOUND_KEY_SEP, '.'))
594
+ .join(', ');
595
+ const rebuiltDisplay = [...rebuiltKeys]
596
+ .sort()
597
+ .map((k) => k.replace(COMPOUND_KEY_SEP, '.'))
598
+ .join(', ');
509
599
  throw new Error(
510
- `nativeEnumPlanCallStrategy: cannot emit both a brand-new enum and a rebuild on a different enum in the same plan; the single recipe flag cannot route them to different buckets. Introduced: [${[...introducedTypeNames].sort().join(', ')}]; rebuilt: [${[...rebuiltTypeNames].sort().join(', ')}]. Split the strategy or grow the \`match\` return type before this case lands.`,
600
+ `nativeEnumPlanCallStrategy: cannot emit both a brand-new enum and a rebuild on a different enum in the same plan; the single recipe flag cannot route them to different buckets. Introduced: [${introducedDisplay}]; rebuilt: [${rebuiltDisplay}]. Split the strategy or grow the \`match\` return type before this case lands.`,
511
601
  );
512
602
  }
513
603
 
@@ -516,7 +606,7 @@ export const nativeEnumPlanCallStrategy: CallMigrationStrategy = (issues, ctx) =
516
606
  !(
517
607
  (issue.kind === 'type_missing' || issue.kind === 'enum_values_changed') &&
518
608
  issue.typeName &&
519
- handledTypeNames.has(issue.typeName)
609
+ handledKeys.has(enumCompoundKey(resolveNamespaceIdForIssue(issue), issue.typeName))
520
610
  ),
521
611
  );
522
612
 
@@ -538,14 +628,22 @@ export const nativeEnumPlanCallStrategy: CallMigrationStrategy = (issues, ctx) =
538
628
  return { kind: 'match', issues: remaining, calls, recipe: emittedRebuildRecipe };
539
629
  };
540
630
 
631
+ /**
632
+ * Collects every `PostgresEnumType` instance across all declared namespaces,
633
+ * returning a compound-keyed map (`${namespaceId}\u0000${typeName}`). Two
634
+ * namespaces that declare an enum with the same name produce two distinct
635
+ * entries — no name collision, no last-write-wins.
636
+ *
637
+ * Entries within each namespace are sorted by name for deterministic ordering.
638
+ */
541
639
  function collectPostgresEnumTypes(storage: SqlStorage): ReadonlyMap<string, PostgresEnumType> {
542
640
  const result = new Map<string, PostgresEnumType>();
543
- for (const ns of Object.values(storage.namespaces)) {
641
+ for (const [nsId, ns] of Object.entries(storage.namespaces)) {
544
642
  if (!('enum' in ns) || ns.enum == null) continue;
545
643
  const nsEnums = ns.enum as Record<string, unknown>;
546
644
  for (const [name, instance] of Object.entries(nsEnums).sort(([a], [b]) => a.localeCompare(b))) {
547
645
  if (instance instanceof PostgresEnumType) {
548
- result.set(name, instance);
646
+ result.set(enumCompoundKey(nsId, name), instance);
549
647
  }
550
648
  }
551
649
  }
@@ -17,9 +17,10 @@ import type {
17
17
  MigrationScaffoldContext,
18
18
  SchemaIssue,
19
19
  } from '@prisma-next/framework-components/control';
20
+ import { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';
20
21
  import { parsePostgresDefault } from '../default-normalizer';
21
22
  import { normalizeSchemaNativeType } from '../native-type-normalizer';
22
- import { readExistingEnumValues } from './enum-planning';
23
+ import { createResolveExistingEnumValues } from './enum-planning';
23
24
  import { planIssues } from './issue-planner';
24
25
  import { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';
25
26
  import { postgresPlannerStrategies } from './planner-strategies';
@@ -39,21 +40,8 @@ type VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0
39
40
  readonly frameworkComponents: PlannerFrameworkComponents;
40
41
  };
41
42
 
42
- interface PlannerConfig {
43
- readonly defaultSchema: string;
44
- }
45
-
46
- const DEFAULT_PLANNER_CONFIG: PlannerConfig = {
47
- defaultSchema: 'public',
48
- };
49
-
50
- export function createPostgresMigrationPlanner(
51
- config: Partial<PlannerConfig> = {},
52
- ): PostgresMigrationPlanner {
53
- return new PostgresMigrationPlanner({
54
- ...DEFAULT_PLANNER_CONFIG,
55
- ...config,
56
- });
43
+ export function createPostgresMigrationPlanner(): PostgresMigrationPlanner {
44
+ return new PostgresMigrationPlanner();
57
45
  }
58
46
 
59
47
  /**
@@ -84,8 +72,6 @@ export type PostgresPlanResult =
84
72
  * authoring surface.
85
73
  */
86
74
  export class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgres'> {
87
- constructor(private readonly config: PlannerConfig) {}
88
-
89
75
  plan(options: {
90
76
  readonly contract: unknown;
91
77
  readonly schema: unknown;
@@ -132,7 +118,10 @@ export class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgr
132
118
  }
133
119
 
134
120
  private planSql(options: SqlMigrationPlannerPlanOptions): PostgresPlanResult {
135
- const schemaName = options.schemaName ?? this.config.defaultSchema;
121
+ const schemaName =
122
+ options.schemaName ??
123
+ Object.keys(options.contract.storage.namespaces).find((id) => id !== UNBOUND_NAMESPACE_ID) ??
124
+ UNBOUND_NAMESPACE_ID;
136
125
  const policyResult = this.ensureAdditivePolicy(options.policy);
137
126
  if (policyResult) {
138
127
  return policyResult;
@@ -219,8 +208,7 @@ export class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgr
219
208
  frameworkComponents: options.frameworkComponents,
220
209
  normalizeDefault: parsePostgresDefault,
221
210
  normalizeNativeType: normalizeSchemaNativeType,
222
- resolveExistingEnumValues: (schema, enumType) =>
223
- readExistingEnumValues(schema, enumType.nativeType),
211
+ resolveExistingEnumValues: createResolveExistingEnumValues(options.contract.storage),
224
212
  };
225
213
  const verifyResult = verifySqlSchema(verifyOptions);
226
214
  // Schema presence is a Postgres-specific concern (no equivalent in
@@ -11,12 +11,11 @@
11
11
 
12
12
  import type { OpFactoryCall } from '@prisma-next/framework-components/control';
13
13
  import { detectScaffoldRuntime, shebangLineFor } from '@prisma-next/migration-tools/migration-ts';
14
- import { type ImportRequirement, jsonToTsSource, renderImports } from '@prisma-next/ts-render';
14
+ import { type ImportRequirement, renderImports } from '@prisma-next/ts-render';
15
15
 
16
16
  export interface RenderMigrationMeta {
17
17
  readonly from: string | null;
18
18
  readonly to: string;
19
- readonly labels?: readonly string[];
20
19
  }
21
20
 
22
21
  /**
@@ -83,9 +82,6 @@ function buildDescribeMethod(meta: RenderMigrationMeta): string {
83
82
  lines.push(' return {');
84
83
  lines.push(` from: ${JSON.stringify(meta.from)},`);
85
84
  lines.push(` to: ${JSON.stringify(meta.to)},`);
86
- if (meta.labels && meta.labels.length > 0) {
87
- lines.push(` labels: ${jsonToTsSource(meta.labels)},`);
88
- }
89
85
  lines.push(' };');
90
86
  lines.push(' }');
91
87
  lines.push('');