@prisma-next/target-postgres 0.11.0-dev.7 → 0.11.0-dev.70

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 (107) hide show
  1. package/dist/codec-types-CRlHq7Cz.d.mts.map +1 -1
  2. package/dist/codecs-Dud5KDNk.d.mts.map +1 -1
  3. package/dist/codecs.d.mts.map +1 -1
  4. package/dist/codecs.mjs.map +1 -1
  5. package/dist/control.d.mts.map +1 -1
  6. package/dist/control.mjs +11 -29
  7. package/dist/control.mjs.map +1 -1
  8. package/dist/data-transform-CdtGUWp2.mjs.map +1 -1
  9. package/dist/data-transform-bmOKkygi.d.mts.map +1 -1
  10. package/dist/{default-normalizer-DHCsbfjc.mjs → default-normalizer-CRscvhS5.mjs} +1 -1
  11. package/dist/{default-normalizer-DHCsbfjc.mjs.map → default-normalizer-CRscvhS5.mjs.map} +1 -1
  12. package/dist/default-normalizer.d.mts.map +1 -1
  13. package/dist/default-normalizer.mjs +1 -1
  14. package/dist/descriptor-meta-DLA2xV6B.mjs.map +1 -1
  15. package/dist/enum-planning-KW36pJfm.mjs +0 -0
  16. package/dist/enum-planning-KW36pJfm.mjs.map +1 -0
  17. package/dist/enum-planning.d.mts +41 -3
  18. package/dist/enum-planning.d.mts.map +1 -1
  19. package/dist/enum-planning.mjs +2 -2
  20. package/dist/errors--zafB5_n.mjs.map +1 -1
  21. package/dist/errors.d.mts.map +1 -1
  22. package/dist/{issue-planner-Ct9xNqbr.mjs → issue-planner-BdFZtaeF.mjs} +105 -48
  23. package/dist/issue-planner-BdFZtaeF.mjs.map +1 -0
  24. package/dist/issue-planner.d.mts.map +1 -1
  25. package/dist/issue-planner.mjs +1 -1
  26. package/dist/migration.d.mts.map +1 -1
  27. package/dist/migration.mjs +1 -1
  28. package/dist/migration.mjs.map +1 -1
  29. package/dist/{native-type-normalizer-DMikJJ1V.mjs → native-type-normalizer-ClNPq__-.mjs} +1 -1
  30. package/dist/{native-type-normalizer-DMikJJ1V.mjs.map → native-type-normalizer-ClNPq__-.mjs.map} +1 -1
  31. package/dist/native-type-normalizer.d.mts.map +1 -1
  32. package/dist/native-type-normalizer.mjs +1 -1
  33. package/dist/{op-factory-call-CB6tPJ3f.mjs → op-factory-call-ByxoQ2BS.mjs} +2 -2
  34. package/dist/{op-factory-call-CB6tPJ3f.mjs.map → op-factory-call-ByxoQ2BS.mjs.map} +1 -1
  35. package/dist/op-factory-call-Drccm_JD.d.mts.map +1 -1
  36. package/dist/op-factory-call.mjs +1 -1
  37. package/dist/pack.d.mts.map +1 -1
  38. package/dist/{planner-DlhK35aV.mjs → planner-B-NSmVRT.mjs} +8 -8
  39. package/dist/planner-B-NSmVRT.mjs.map +1 -0
  40. package/dist/{planner-ddl-builders--0TmW6Ey.mjs → planner-ddl-builders-Yp3t-9mV.mjs} +3 -3
  41. package/dist/{planner-ddl-builders--0TmW6Ey.mjs.map → planner-ddl-builders-Yp3t-9mV.mjs.map} +1 -1
  42. package/dist/planner-ddl-builders.d.mts.map +1 -1
  43. package/dist/planner-ddl-builders.mjs +1 -1
  44. package/dist/planner-identity-values-ojX-6cPV.mjs.map +1 -1
  45. package/dist/planner-identity-values.d.mts.map +1 -1
  46. package/dist/{planner-produced-postgres-migration-TJWH2m_x.mjs → planner-produced-postgres-migration-N1yqYg20.mjs} +3 -5
  47. package/dist/planner-produced-postgres-migration-N1yqYg20.mjs.map +1 -0
  48. package/dist/planner-produced-postgres-migration-p-VKkCia.d.mts.map +1 -1
  49. package/dist/planner-produced-postgres-migration.mjs +1 -1
  50. package/dist/planner-schema-lookup-BGyukuzG.mjs.map +1 -1
  51. package/dist/planner-schema-lookup.d.mts.map +1 -1
  52. package/dist/{planner-sql-checks-BDtJQ9WD.mjs → planner-sql-checks-DvcI55d1.mjs} +3 -3
  53. package/dist/{planner-sql-checks-BDtJQ9WD.mjs.map → planner-sql-checks-DvcI55d1.mjs.map} +1 -1
  54. package/dist/planner-sql-checks.d.mts.map +1 -1
  55. package/dist/planner-sql-checks.mjs +1 -1
  56. package/dist/planner-target-details-CIj61DUj.d.mts.map +1 -1
  57. package/dist/planner.d.mts.map +1 -1
  58. package/dist/planner.mjs +1 -1
  59. package/dist/{postgres-contract-serializer-CYct4Y7O.mjs → postgres-contract-serializer-Cloy2WOf.mjs} +2 -2
  60. package/dist/postgres-contract-serializer-Cloy2WOf.mjs.map +1 -0
  61. package/dist/postgres-enum-type-CNhPTDhy.d.mts.map +1 -1
  62. package/dist/postgres-enum-type-DS-KLVRH.mjs.map +1 -1
  63. package/dist/postgres-migration-uADmx0dW.mjs.map +1 -1
  64. package/dist/{postgres-schema-BL0RAvew.mjs → postgres-schema-bm3T3UGn.mjs} +2 -2
  65. package/dist/{postgres-schema-BL0RAvew.mjs.map → postgres-schema-bm3T3UGn.mjs.map} +1 -1
  66. package/dist/render-ops-BC2PtCkj.mjs.map +1 -1
  67. package/dist/render-ops.d.mts.map +1 -1
  68. package/dist/{render-typescript-CI1wbgUc.mjs → render-typescript-CPk7hhWH.mjs} +2 -3
  69. package/dist/render-typescript-CPk7hhWH.mjs.map +1 -0
  70. package/dist/render-typescript.d.mts +0 -1
  71. package/dist/render-typescript.d.mts.map +1 -1
  72. package/dist/render-typescript.mjs +1 -1
  73. package/dist/runtime.d.mts.map +1 -1
  74. package/dist/runtime.mjs +1 -1
  75. package/dist/runtime.mjs.map +1 -1
  76. package/dist/shared-ByhSooBS.d.mts.map +1 -1
  77. package/dist/{sql-utils-BewXAnsG.mjs → sql-utils-B_ruBD-M.mjs} +1 -1
  78. package/dist/{sql-utils-BewXAnsG.mjs.map → sql-utils-B_ruBD-M.mjs.map} +1 -1
  79. package/dist/sql-utils.d.mts.map +1 -1
  80. package/dist/sql-utils.mjs +1 -1
  81. package/dist/statement-builders-vImtdfmM.mjs.map +1 -1
  82. package/dist/statement-builders.d.mts +1 -1
  83. package/dist/statement-builders.d.mts.map +1 -1
  84. package/dist/{tables-Vhh4k5yz.mjs → tables-D1xjs8QW.mjs} +3 -3
  85. package/dist/{tables-Vhh4k5yz.mjs.map → tables-D1xjs8QW.mjs.map} +1 -1
  86. package/dist/types-D-XIpzHA.d.mts.map +1 -1
  87. package/dist/types.d.mts.map +1 -1
  88. package/dist/types.mjs +1 -1
  89. package/package.json +17 -17
  90. package/src/core/migrations/enum-planning.ts +134 -14
  91. package/src/core/migrations/issue-planner.ts +20 -11
  92. package/src/core/migrations/planner-produced-postgres-migration.ts +0 -2
  93. package/src/core/migrations/planner-strategies.ts +132 -34
  94. package/src/core/migrations/planner.ts +2 -3
  95. package/src/core/migrations/render-typescript.ts +1 -5
  96. package/src/core/migrations/runner.ts +11 -43
  97. package/src/core/migrations/statement-builders.ts +1 -1
  98. package/src/core/postgres-contract-serializer.ts +4 -4
  99. package/src/exports/control.ts +16 -0
  100. package/src/exports/enum-planning.ts +5 -0
  101. package/dist/enum-planning-Bqp96iIw.mjs +0 -63
  102. package/dist/enum-planning-Bqp96iIw.mjs.map +0 -1
  103. package/dist/issue-planner-Ct9xNqbr.mjs.map +0 -1
  104. package/dist/planner-DlhK35aV.mjs.map +0 -1
  105. package/dist/planner-produced-postgres-migration-TJWH2m_x.mjs.map +0 -1
  106. package/dist/postgres-contract-serializer-CYct4Y7O.mjs.map +0 -1
  107. package/dist/render-typescript-CI1wbgUc.mjs.map +0 -1
@@ -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,
@@ -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
  }
@@ -19,7 +19,7 @@ import type {
19
19
  } from '@prisma-next/framework-components/control';
20
20
  import { parsePostgresDefault } from '../default-normalizer';
21
21
  import { normalizeSchemaNativeType } from '../native-type-normalizer';
22
- import { readExistingEnumValues } from './enum-planning';
22
+ import { createResolveExistingEnumValues } from './enum-planning';
23
23
  import { planIssues } from './issue-planner';
24
24
  import { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';
25
25
  import { postgresPlannerStrategies } from './planner-strategies';
@@ -219,8 +219,7 @@ export class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgr
219
219
  frameworkComponents: options.frameworkComponents,
220
220
  normalizeDefault: parsePostgresDefault,
221
221
  normalizeNativeType: normalizeSchemaNativeType,
222
- resolveExistingEnumValues: (schema, enumType) =>
223
- readExistingEnumValues(schema, enumType.nativeType),
222
+ resolveExistingEnumValues: createResolveExistingEnumValues(options.contract.storage),
224
223
  };
225
224
  const verifyResult = verifySqlSchema(verifyOptions);
226
225
  // 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('');
@@ -1,7 +1,6 @@
1
1
  import type { ContractMarkerRecord } from '@prisma-next/contract/types';
2
2
  import type {
3
3
  MigrationOperationPolicy,
4
- MultiSpaceRunnerResult,
5
4
  SqlControlFamilyInstance,
6
5
  SqlMigrationPlanContractInfo,
7
6
  SqlMigrationPlanOperation,
@@ -14,7 +13,10 @@ import type {
14
13
  } from '@prisma-next/family-sql/control';
15
14
  import { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';
16
15
  import { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';
17
- import type { ControlDriverInstance } from '@prisma-next/framework-components/control';
16
+ import type {
17
+ ControlDriverInstance,
18
+ MigrationRunnerResult,
19
+ } from '@prisma-next/framework-components/control';
18
20
  import { APP_SPACE_ID } from '@prisma-next/framework-components/control';
19
21
  import { SqlQueryError } from '@prisma-next/sql-errors';
20
22
  import { ifDefined } from '@prisma-next/utils/defined';
@@ -22,7 +24,7 @@ import type { Result } from '@prisma-next/utils/result';
22
24
  import { notOk, ok, okVoid } from '@prisma-next/utils/result';
23
25
  import { parsePostgresDefault } from '../default-normalizer';
24
26
  import { normalizeSchemaNativeType } from '../native-type-normalizer';
25
- import { readExistingEnumValues } from './enum-planning';
27
+ import { createResolveExistingEnumValues } from './enum-planning';
26
28
  import type { PostgresPlanTargetDetails } from './planner-target-details';
27
29
  import {
28
30
  buildLedgerInsertStatement,
@@ -84,44 +86,9 @@ class PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDe
84
86
  private readonly config: RunnerConfig,
85
87
  ) {}
86
88
 
87
- async execute(
88
- options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,
89
- ): Promise<SqlMigrationRunnerResult> {
90
- const driver = options.driver;
91
-
92
- // Static checks fail fast before any transaction work — no point
93
- // burning a BEGIN/ROLLBACK round-trip on a destination-contract
94
- // mismatch the caller can fix locally.
95
- const destinationCheck = this.ensurePlanMatchesDestinationContract(
96
- options.plan.destination,
97
- options.destinationContract,
98
- );
99
- if (!destinationCheck.ok) return destinationCheck;
100
-
101
- const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);
102
- if (!policyCheck.ok) return policyCheck;
103
-
104
- await this.beginTransaction(driver);
105
- let committed = false;
106
- try {
107
- const result = await this.executeOnConnection(options);
108
- if (!result.ok) {
109
- return result;
110
- }
111
- await this.commitTransaction(driver);
112
- committed = true;
113
- return result;
114
- } finally {
115
- if (!committed) {
116
- await this.rollbackTransaction(driver);
117
- }
118
- }
119
- }
120
-
121
89
  /**
122
90
  * Body of the migration runner without transaction management. The
123
- * caller (single-space `execute(...)` above, or the multi-space
124
- * outer-tx orchestrator at the SQL family level) owns the
91
+ * caller ({@link PostgresMigrationRunner.execute}) owns the
125
92
  * `BEGIN`/`COMMIT`/`ROLLBACK` lifecycle.
126
93
  */
127
94
  async executeOnConnection(
@@ -188,8 +155,9 @@ class PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDe
188
155
  frameworkComponents: options.frameworkComponents,
189
156
  normalizeDefault: parsePostgresDefault,
190
157
  normalizeNativeType: normalizeSchemaNativeType,
191
- resolveExistingEnumValues: (schema, enumType) =>
192
- readExistingEnumValues(schema, enumType.nativeType),
158
+ resolveExistingEnumValues: createResolveExistingEnumValues(
159
+ options.destinationContract.storage,
160
+ ),
193
161
  });
194
162
  if (!schemaVerifyResult.ok) {
195
163
  return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {
@@ -216,12 +184,12 @@ class PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDe
216
184
  });
217
185
  }
218
186
 
219
- async executeAcrossSpaces(options: {
187
+ async execute(options: {
220
188
  readonly driver: ControlDriverInstance<'sql', string>;
221
189
  readonly perSpaceOptions: ReadonlyArray<
222
190
  SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>
223
191
  >;
224
- }): Promise<MultiSpaceRunnerResult> {
192
+ }): Promise<MigrationRunnerResult> {
225
193
  const driver = options.driver;
226
194
  const perSpaceOptions = options.perSpaceOptions;
227
195
 
@@ -56,7 +56,7 @@ export interface MergeMarkerInput {
56
56
  * Logical space identifier for this marker row. Required at every
57
57
  * call site so the type system surfaces every place that needs to
58
58
  * thread the value (rather than letting an `?? APP_SPACE_ID`
59
- * fall-through silently collapse multi-space markers onto the
59
+ * fall-through silently collapse per-space markers onto the
60
60
  * `'app'` row). App-plan callers pass {@link APP_SPACE_ID}
61
61
  * (`'app'`); per-extension callers (planner / runner / verifier
62
62
  * extensions over contract spaces) pass the extension's space id.
@@ -117,10 +117,10 @@ export class PostgresContractSerializer extends SqlContractSerializerBase<Contra
117
117
  if (isPostgresSchema(ns)) {
118
118
  namespacesJson[nsId] = this.serializePostgresNamespace(ns, ns.id === UNBOUND_NAMESPACE_ID);
119
119
  } else {
120
- // Family-level SqlNamespacePayload / SqlUnboundNamespace haven't
121
- // been promoted to a PostgresSchema instance yet (e.g. they came
122
- // straight from the TS builder, which uses the family-shared
123
- // SqlStorage constructor). Serialise them as postgres-schema /
120
+ // Family-level SqlUnboundNamespace or other family-built SQL
121
+ // namespaces haven't been promoted to a PostgresSchema instance
122
+ // yet (e.g. they came straight from the TS builder before a target
123
+ // `createNamespace` factory ran). Serialise them as postgres-schema /
124
124
  // postgres-unbound-schema so the round-trip through
125
125
  // deserializeContract hydrates them back into PostgresSchema
126
126
  // instances.
@@ -12,6 +12,10 @@ import type {
12
12
  import type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';
13
13
  import { ifDefined } from '@prisma-next/utils/defined';
14
14
  import { postgresTargetDescriptorMeta } from '../core/descriptor-meta';
15
+ import {
16
+ enumStorageCompoundKey,
17
+ resolveDdlSchemaForNamespaceStorage,
18
+ } from '../core/migrations/enum-planning';
15
19
  import { createPostgresMigrationPlanner } from '../core/migrations/planner';
16
20
  import { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';
17
21
  import type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';
@@ -78,6 +82,18 @@ const postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresP
78
82
  annotationNamespace: 'pg',
79
83
  ...ifDefined('expandNativeType', expander),
80
84
  renderDefault: postgresRenderDefault,
85
+ // Schema-qualify enum annotation keys so the projected "from" IR's
86
+ // `storageTypes` match `readExistingEnumValues` on the read side
87
+ // (the contract-to-contract `migration plan` path). The DDL-schema
88
+ // resolution + compound-key format stay here in the target layer;
89
+ // the family projector treats the returned string as opaque.
90
+ // `undefined` schema IR ⇒ the unbound coordinate resolves to the
91
+ // default `public` landing schema, matching the read-side fallback.
92
+ resolveEnumStorageKey: (storage, namespaceId, nativeType) =>
93
+ enumStorageCompoundKey(
94
+ resolveDdlSchemaForNamespaceStorage(storage, namespaceId, undefined),
95
+ nativeType,
96
+ ),
81
97
  });
82
98
  },
83
99
  },
@@ -1,6 +1,11 @@
1
1
  export {
2
+ createResolveExistingEnumValues,
2
3
  determineEnumDiff,
3
4
  type EnumDiff,
5
+ enumStorageCompoundKey,
4
6
  getDesiredEnumValues,
7
+ type PostgresSchemaIrAnnotations,
5
8
  readExistingEnumValues,
9
+ readPostgresSchemaIrAnnotations,
10
+ resolveDdlSchemaForNamespaceStorage,
6
11
  } from '../core/migrations/enum-planning';
@@ -1,63 +0,0 @@
1
- import "./codec-ids-C5qzBqus.mjs";
2
- import { arraysEqual } from "@prisma-next/family-sql/schema-verify";
3
- //#region src/core/migrations/enum-planning.ts
4
- /**
5
- * Pure planning helpers for Postgres enum types: the diff/rebuild logic
6
- * that the verifier and planner use to walk `PostgresEnumType` instances
7
- * natively. Op builders live in `./operations/enums.ts`.
8
- */
9
- /**
10
- * Reads existing enum values for `nativeType` from the
11
- * Postgres-introspected `schema.annotations.pg.storageTypes` map.
12
- *
13
- * Schema IR's `storageTypes` slots are always codec-typed
14
- * (`{codecId: PG_ENUM_CODEC_ID, typeParams.values}`): the introspector
15
- * writes that shape, and the Contract→Schema IR projector resolves
16
- * `PostgresEnumType` instances down to the same codec-typed triple before
17
- * they ever land in Schema IR. There is no second on-disk shape to
18
- * accept here.
19
- *
20
- * Returns `null` when no enum entry exists for the given native type.
21
- */
22
- function readExistingEnumValues(schema, nativeType) {
23
- const existing = ((schema.annotations?.["pg"])?.["storageTypes"])?.[nativeType];
24
- if (!existing || existing.codecId !== "pg/enum@1") return null;
25
- const enumValues = existing.typeParams?.values;
26
- if (!Array.isArray(enumValues) || !enumValues.every((v) => typeof v === "string")) return null;
27
- return enumValues;
28
- }
29
- /**
30
- * Determines what changes are needed to transform existing enum values to
31
- * desired values.
32
- *
33
- * Postgres enums can only have values added (not removed or reordered)
34
- * without a full type rebuild involving temp type creation and column
35
- * migration; `'rebuild'` covers the value-removal and reorder cases.
36
- */
37
- function determineEnumDiff(existing, desired) {
38
- if (arraysEqual(existing, desired)) return { kind: "unchanged" };
39
- const existingSet = new Set(existing);
40
- const desiredSet = new Set(desired);
41
- const missingValues = desired.filter((value) => !existingSet.has(value));
42
- const removedValues = existing.filter((value) => !desiredSet.has(value));
43
- const orderMismatch = missingValues.length === 0 && removedValues.length === 0 && !arraysEqual(existing, desired);
44
- if (removedValues.length > 0 || orderMismatch) return {
45
- kind: "rebuild",
46
- removedValues
47
- };
48
- return {
49
- kind: "add_values",
50
- values: missingValues
51
- };
52
- }
53
- /**
54
- * Convenience accessor — returns the enum's desired values from a
55
- * `PostgresEnumType` IR instance.
56
- */
57
- function getDesiredEnumValues(typeInstance) {
58
- return typeInstance.values;
59
- }
60
- //#endregion
61
- export { getDesiredEnumValues as n, readExistingEnumValues as r, determineEnumDiff as t };
62
-
63
- //# sourceMappingURL=enum-planning-Bqp96iIw.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"enum-planning-Bqp96iIw.mjs","names":[],"sources":["../src/core/migrations/enum-planning.ts"],"sourcesContent":["/**\n * Pure planning helpers for Postgres enum types: the diff/rebuild logic\n * that the verifier and planner use to walk `PostgresEnumType` instances\n * natively. Op builders live in `./operations/enums.ts`.\n */\n\nimport { arraysEqual } from '@prisma-next/family-sql/schema-verify';\nimport type { SqlSchemaIR } from '@prisma-next/sql-schema-ir/types';\nimport { PG_ENUM_CODEC_ID } from '../codec-ids';\nimport type { PostgresEnumType } from '../postgres-enum-type';\n\n/**\n * Categorisation of how an existing enum type's values relate to the\n * desired set in the contract.\n */\nexport type EnumDiff =\n | { readonly kind: 'unchanged' }\n | { readonly kind: 'add_values'; readonly values: readonly string[] }\n | { readonly kind: 'rebuild'; readonly removedValues: readonly string[] };\n\n/**\n * Reads existing enum values for `nativeType` from the\n * Postgres-introspected `schema.annotations.pg.storageTypes` map.\n *\n * Schema IR's `storageTypes` slots are always codec-typed\n * (`{codecId: PG_ENUM_CODEC_ID, typeParams.values}`): the introspector\n * writes that shape, and the Contract→Schema IR projector resolves\n * `PostgresEnumType` instances down to the same codec-typed triple before\n * they ever land in Schema IR. There is no second on-disk shape to\n * accept here.\n *\n * Returns `null` when no enum entry exists for the given native type.\n */\nexport function readExistingEnumValues(\n schema: SqlSchemaIR,\n nativeType: string,\n): readonly string[] | null {\n const storageTypes = (schema.annotations?.['pg'] as Record<string, unknown> | undefined)?.[\n 'storageTypes'\n ] as\n | Record<\n string,\n {\n codecId?: string;\n typeParams?: { values?: unknown };\n }\n >\n | undefined;\n const existing = storageTypes?.[nativeType];\n if (!existing || existing.codecId !== PG_ENUM_CODEC_ID) {\n return null;\n }\n const enumValues = existing.typeParams?.values;\n if (!Array.isArray(enumValues) || !enumValues.every((v) => typeof v === 'string')) {\n return null;\n }\n return enumValues as readonly string[];\n}\n\n/**\n * Determines what changes are needed to transform existing enum values to\n * desired values.\n *\n * Postgres enums can only have values added (not removed or reordered)\n * without a full type rebuild involving temp type creation and column\n * migration; `'rebuild'` covers the value-removal and reorder cases.\n */\nexport function determineEnumDiff(\n existing: readonly string[],\n desired: readonly string[],\n): EnumDiff {\n if (arraysEqual(existing, desired)) {\n return { kind: 'unchanged' };\n }\n const existingSet = new Set(existing);\n const desiredSet = new Set(desired);\n const missingValues = desired.filter((value) => !existingSet.has(value));\n const removedValues = existing.filter((value) => !desiredSet.has(value));\n const orderMismatch =\n missingValues.length === 0 && removedValues.length === 0 && !arraysEqual(existing, desired);\n if (removedValues.length > 0 || orderMismatch) {\n return { kind: 'rebuild', removedValues };\n }\n return { kind: 'add_values', values: missingValues };\n}\n\n/**\n * Convenience accessor — returns the enum's desired values from a\n * `PostgresEnumType` IR instance.\n */\nexport function getDesiredEnumValues(typeInstance: PostgresEnumType): readonly string[] {\n return typeInstance.values;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,uBACd,QACA,YAC0B;CAY1B,MAAM,aAXgB,OAAO,cAAc,SACzC,mBAU8B;CAChC,IAAI,CAAC,YAAY,SAAS,YAAA,aACxB,OAAO;CAET,MAAM,aAAa,SAAS,YAAY;CACxC,IAAI,CAAC,MAAM,QAAQ,WAAW,IAAI,CAAC,WAAW,OAAO,MAAM,OAAO,MAAM,SAAS,EAC/E,OAAO;CAET,OAAO;;;;;;;;;;AAWT,SAAgB,kBACd,UACA,SACU;CACV,IAAI,YAAY,UAAU,QAAQ,EAChC,OAAO,EAAE,MAAM,aAAa;CAE9B,MAAM,cAAc,IAAI,IAAI,SAAS;CACrC,MAAM,aAAa,IAAI,IAAI,QAAQ;CACnC,MAAM,gBAAgB,QAAQ,QAAQ,UAAU,CAAC,YAAY,IAAI,MAAM,CAAC;CACxE,MAAM,gBAAgB,SAAS,QAAQ,UAAU,CAAC,WAAW,IAAI,MAAM,CAAC;CACxE,MAAM,gBACJ,cAAc,WAAW,KAAK,cAAc,WAAW,KAAK,CAAC,YAAY,UAAU,QAAQ;CAC7F,IAAI,cAAc,SAAS,KAAK,eAC9B,OAAO;EAAE,MAAM;EAAW;EAAe;CAE3C,OAAO;EAAE,MAAM;EAAc,QAAQ;EAAe;;;;;;AAOtD,SAAgB,qBAAqB,cAAmD;CACtF,OAAO,aAAa"}