@prisma-next/target-postgres 0.5.0-dev.30 → 0.5.0-dev.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- import { n as dataTypes } from "./codecs-OkTYeJQb.mjs";
1
+ import { n as dataTypes } from "./codecs-dzZ_dMpK.mjs";
2
2
 
3
3
  export { dataTypes };
@@ -1 +1 @@
1
- {"version":3,"file":"codecs-CE5EUsNM.d.mts","names":[],"sources":["../src/core/codecs.ts"],"sourcesContent":[],"mappings":";;;;;;cAolBM,8CAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA+BC;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA/BD,SAAA,KAAA,OAAA,CAAA,aAAA,EAAA,SAAA,CAAA,UAAA,EAAA,OAAA,EAAA,SAAA,CAAA,EAAA,MAAA,EAAA,MAAA,QAAA,CAAA,MAAA,EAAA,OAAA,CAAA,EAAA,OAAA,CAAA;IA+BC,SAAA,KAAA,EAA0C,MAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAC1C,SAA4B,MAAA,EAAA,QAAA;IAE7B,SAAU,KAAA,OAAU,CAAA,aAAO,EAAA,SAAU,CAAA,UAAA,EAAA,OAAA,EAAA,SAAA,CAAA,EAAA,MAAA,EAAA,MAAA,QAAA,CAAA,MAAA,EAAA,OAAA,CAAA,EAAA,OAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAFpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAED,UAAA,UAAoB,MAAA,CAAO"}
1
+ {"version":3,"file":"codecs-CE5EUsNM.d.mts","names":[],"sources":["../src/core/codecs.ts"],"sourcesContent":[],"mappings":";;;;;;cA2kBM,8CAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA+BC;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA/BD,SAAA,KAAA,OAAA,CAAA,aAAA,EAAA,SAAA,CAAA,UAAA,EAAA,OAAA,EAAA,SAAA,CAAA,EAAA,MAAA,EAAA,MAAA,QAAA,CAAA,MAAA,EAAA,OAAA,CAAA,EAAA,OAAA,CAAA;IA+BC,SAAA,KAAA,EAA0C,MAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAC1C,SAA4B,MAAA,EAAA,QAAA;IAE7B,SAAU,KAAA,OAAA,CAAU,aAAO,EAAA,SAAU,CAAA,UAAA,EAAA,OAAA,EAAA,SAAA,CAAA,EAAA,MAAA,EAAA,MAAA,QAAA,CAAA,MAAA,EAAA,OAAA,CAAA,EAAA,OAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAFpC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAED,UAAA,UAAoB,MAAA,CAAO"}
@@ -3,78 +3,6 @@ import { codec, defineCodecs, sqlCodecDefinitions } from "@prisma-next/sql-relat
3
3
  import { ifDefined } from "@prisma-next/utils/defined";
4
4
  import { type } from "arktype";
5
5
 
6
- //#region src/core/json-schema-type-expression.ts
7
- const MAX_DEPTH = 32;
8
- function isRecord(value) {
9
- return typeof value === "object" && value !== null;
10
- }
11
- function escapeStringLiteral(str) {
12
- return str.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
13
- }
14
- function quotePropertyKey(key) {
15
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : `'${escapeStringLiteral(key)}'`;
16
- }
17
- function renderLiteral(value) {
18
- if (typeof value === "string") return `'${escapeStringLiteral(value)}'`;
19
- if (typeof value === "number" || typeof value === "boolean") return String(value);
20
- if (value === null) return "null";
21
- return "unknown";
22
- }
23
- function renderUnion(items, depth) {
24
- return items.map((item) => render(item, depth)).join(" | ");
25
- }
26
- function renderObjectType(schema, depth) {
27
- const properties = isRecord(schema["properties"]) ? schema["properties"] : {};
28
- const required = Array.isArray(schema["required"]) ? new Set(schema["required"].filter((key) => typeof key === "string")) : /* @__PURE__ */ new Set();
29
- const keys = Object.keys(properties).sort((left, right) => left.localeCompare(right));
30
- if (keys.length === 0) {
31
- const additionalProperties = schema["additionalProperties"];
32
- if (additionalProperties === true || additionalProperties === void 0) return "Record<string, unknown>";
33
- return `Record<string, ${render(additionalProperties, depth)}>`;
34
- }
35
- return `{ ${keys.map((key) => {
36
- const valueSchema = properties[key];
37
- const optionalMarker = required.has(key) ? "" : "?";
38
- return `${quotePropertyKey(key)}${optionalMarker}: ${render(valueSchema, depth)}`;
39
- }).join("; ")} }`;
40
- }
41
- function renderArrayType(schema, depth) {
42
- if (Array.isArray(schema["items"])) return `readonly [${schema["items"].map((item) => render(item, depth)).join(", ")}]`;
43
- if (schema["items"] !== void 0) {
44
- const itemType = render(schema["items"], depth);
45
- return itemType.includes(" | ") || itemType.includes(" & ") ? `(${itemType})[]` : `${itemType}[]`;
46
- }
47
- return "unknown[]";
48
- }
49
- function render(schema, depth) {
50
- if (depth > MAX_DEPTH || !isRecord(schema)) return "JsonValue";
51
- const nextDepth = depth + 1;
52
- if ("const" in schema) return renderLiteral(schema["const"]);
53
- if (Array.isArray(schema["enum"])) return schema["enum"].map((value) => renderLiteral(value)).join(" | ");
54
- if (Array.isArray(schema["oneOf"])) return renderUnion(schema["oneOf"], nextDepth);
55
- if (Array.isArray(schema["anyOf"])) return renderUnion(schema["anyOf"], nextDepth);
56
- if (Array.isArray(schema["allOf"])) return schema["allOf"].map((item) => render(item, nextDepth)).join(" & ");
57
- if (Array.isArray(schema["type"])) return schema["type"].map((item) => render({
58
- ...schema,
59
- type: item
60
- }, nextDepth)).join(" | ");
61
- switch (schema["type"]) {
62
- case "string": return "string";
63
- case "number":
64
- case "integer": return "number";
65
- case "boolean": return "boolean";
66
- case "null": return "null";
67
- case "array": return renderArrayType(schema, nextDepth);
68
- case "object": return renderObjectType(schema, nextDepth);
69
- default: break;
70
- }
71
- return "JsonValue";
72
- }
73
- function renderTypeScriptTypeFromJsonSchema(schema) {
74
- return render(schema, 0);
75
- }
76
-
77
- //#endregion
78
6
  //#region src/core/codecs.ts
79
7
  const lengthParamsSchema = type({ length: "number.integer > 0" });
80
8
  const numericParamsSchema = type({
@@ -94,13 +22,6 @@ function renderPrecision(typeName, typeParams) {
94
22
  if (typeof precision !== "number" || !Number.isFinite(precision) || !Number.isInteger(precision)) throw new Error(`renderOutputType: expected integer "precision" in typeParams for ${typeName}, got ${String(precision)}`);
95
23
  return `${typeName}<${precision}>`;
96
24
  }
97
- function renderJsonOutputType(typeParams) {
98
- const typeName = typeParams["type"];
99
- if (typeof typeName === "string" && typeName.trim().length > 0) return typeName.trim();
100
- const schema = typeParams["schemaJson"];
101
- if (schema && typeof schema === "object") return renderTypeScriptTypeFromJsonSchema(schema);
102
- throw new Error(`renderOutputType: JSON codec typeParams must contain "type" (string) or "schemaJson" (object), got keys: ${Object.keys(typeParams).join(", ")}`);
103
- }
104
25
  function aliasCodec(base, options) {
105
26
  return {
106
27
  id: options.typeId,
@@ -350,7 +271,6 @@ const pgJsonCodec = codec({
350
271
  traits: [],
351
272
  encode: (value) => JSON.stringify(value),
352
273
  decode: (wire) => typeof wire === "string" ? JSON.parse(wire) : wire,
353
- renderOutputType: renderJsonOutputType,
354
274
  meta: { db: { sql: { postgres: { nativeType: "json" } } } }
355
275
  });
356
276
  const pgJsonbCodec = codec({
@@ -359,7 +279,6 @@ const pgJsonbCodec = codec({
359
279
  traits: ["equality"],
360
280
  encode: (value) => JSON.stringify(value),
361
281
  decode: (wire) => typeof wire === "string" ? JSON.parse(wire) : wire,
362
- renderOutputType: renderJsonOutputType,
363
282
  meta: { db: { sql: { postgres: { nativeType: "jsonb" } } } }
364
283
  });
365
284
  const codecs = defineCodecs().add("char", sqlCharCodec).add("varchar", sqlVarcharCodec).add("int", sqlIntCodec).add("float", sqlFloatCodec).add("sql-text", sqlTextCodec).add("sql-timestamp", sqlTimestampCodec).add("text", pgTextCodec).add("character", pgCharCodec).add("character varying", pgVarcharCodec).add("integer", pgIntCodec).add("double precision", pgFloatCodec).add("int4", pgInt4Codec).add("int2", pgInt2Codec).add("int8", pgInt8Codec).add("float4", pgFloat4Codec).add("float8", pgFloat8Codec).add("numeric", pgNumericCodec).add("timestamp", pgTimestampCodec).add("timestamptz", pgTimestamptzCodec).add("time", pgTimeCodec).add("timetz", pgTimetzCodec).add("bool", pgBoolCodec).add("bit", pgBitCodec).add("bit varying", pgVarbitCodec).add("interval", pgIntervalCodec).add("enum", pgEnumCodec).add("json", pgJsonCodec).add("jsonb", pgJsonbCodec);
@@ -368,4 +287,4 @@ const dataTypes = codecs.dataTypes;
368
287
 
369
288
  //#endregion
370
289
  export { dataTypes as n, codecDefinitions as t };
371
- //# sourceMappingURL=codecs-OkTYeJQb.mjs.map
290
+ //# sourceMappingURL=codecs-dzZ_dMpK.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codecs-dzZ_dMpK.mjs","names":["arktype"],"sources":["../src/core/codecs.ts"],"sourcesContent":["/**\n * Unified codec definitions for Postgres adapter.\n *\n * This file contains a single source of truth for all codec information:\n * - Scalar names\n * - Type IDs\n * - Codec implementations (runtime)\n * - Type information (compile-time)\n *\n * This structure is used both at runtime (to populate the registry) and\n * at compile time (to derive CodecTypes).\n */\n\nimport type { JsonValue } from '@prisma-next/contract/types';\nimport type { Codec, CodecMeta, CodecTrait } from '@prisma-next/sql-relational-core/ast';\nimport { codec, defineCodecs, sqlCodecDefinitions } from '@prisma-next/sql-relational-core/ast';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { type as arktype } from 'arktype';\nimport {\n PG_BIT_CODEC_ID,\n PG_BOOL_CODEC_ID,\n PG_CHAR_CODEC_ID,\n PG_ENUM_CODEC_ID,\n PG_FLOAT_CODEC_ID,\n PG_FLOAT4_CODEC_ID,\n PG_FLOAT8_CODEC_ID,\n PG_INT_CODEC_ID,\n PG_INT2_CODEC_ID,\n PG_INT4_CODEC_ID,\n PG_INT8_CODEC_ID,\n PG_INTERVAL_CODEC_ID,\n PG_JSON_CODEC_ID,\n PG_JSONB_CODEC_ID,\n PG_NUMERIC_CODEC_ID,\n PG_TEXT_CODEC_ID,\n PG_TIME_CODEC_ID,\n PG_TIMESTAMP_CODEC_ID,\n PG_TIMESTAMPTZ_CODEC_ID,\n PG_TIMETZ_CODEC_ID,\n PG_VARBIT_CODEC_ID,\n PG_VARCHAR_CODEC_ID,\n} from './codec-ids';\n\nconst lengthParamsSchema = arktype({\n length: 'number.integer > 0',\n});\n\nconst numericParamsSchema = arktype({\n precision: 'number.integer > 0 & number.integer <= 1000',\n 'scale?': 'number.integer >= 0',\n});\n\nconst precisionParamsSchema = arktype({\n 'precision?': 'number.integer >= 0 & number.integer <= 6',\n});\n\nfunction renderLength(typeName: string, typeParams: Record<string, unknown>): string | undefined {\n const length = typeParams['length'];\n if (length === undefined) {\n return undefined;\n }\n if (typeof length !== 'number' || !Number.isFinite(length) || !Number.isInteger(length)) {\n throw new Error(\n `renderOutputType: expected integer \"length\" in typeParams for ${typeName}, got ${String(length)}`,\n );\n }\n return `${typeName}<${length}>`;\n}\n\nfunction renderPrecision(typeName: string, typeParams: Record<string, unknown>): string {\n const precision = typeParams['precision'];\n if (precision === undefined) {\n return typeName;\n }\n if (\n typeof precision !== 'number' ||\n !Number.isFinite(precision) ||\n !Number.isInteger(precision)\n ) {\n throw new Error(\n `renderOutputType: expected integer \"precision\" in typeParams for ${typeName}, got ${String(precision)}`,\n );\n }\n return `${typeName}<${precision}>`;\n}\n\n// Phase C: postgres' raw json/jsonb codecs no longer carry a\n// `renderOutputType` slot — the schema-typed JSON surface that drove\n// `typeParams: { schemaJson, type? }` retired in favor of the per-library\n// extension package (`@prisma-next/extension-arktype-json`). Untyped\n// json/jsonb columns have no typeParams; the framework emit path falls\n// through to the generic `CodecTypes['pg/jsonb@1']['output']` accessor\n// (which resolves to `JsonValue` via the codec-types map).\n\nfunction aliasCodec<\n Id extends string,\n TTraits extends readonly CodecTrait[],\n TWire,\n TJs,\n TParams,\n THelper,\n>(\n base: Codec<string, TTraits, TWire, TJs, TParams, THelper>,\n options: {\n readonly typeId: Id;\n readonly targetTypes: readonly string[];\n readonly meta?: CodecMeta;\n },\n): Codec<Id, TTraits, TWire, TJs, TParams, THelper> {\n return {\n id: options.typeId,\n targetTypes: options.targetTypes,\n ...ifDefined('meta', options.meta),\n ...ifDefined('paramsSchema', base.paramsSchema),\n ...ifDefined('init', base.init),\n ...ifDefined('encode', base.encode),\n ...ifDefined('traits', base.traits),\n ...ifDefined('renderOutputType', base.renderOutputType),\n decode: base.decode,\n encodeJson: base.encodeJson,\n decodeJson: base.decodeJson,\n } as Codec<Id, TTraits, TWire, TJs, TParams, THelper>;\n}\n\nconst sqlCharCodec = sqlCodecDefinitions.char.codec;\nconst sqlVarcharCodec = sqlCodecDefinitions.varchar.codec;\nconst sqlIntCodec = sqlCodecDefinitions.int.codec;\nconst sqlFloatCodec = sqlCodecDefinitions.float.codec;\nconst sqlTextCodec = sqlCodecDefinitions.text.codec;\nconst sqlTimestampCodec = sqlCodecDefinitions.timestamp.codec;\n\n// Create individual codec instances\nconst pgTextCodec = codec({\n typeId: PG_TEXT_CODEC_ID,\n targetTypes: ['text'],\n traits: ['equality', 'order', 'textual'],\n encode: (value: string): string => value,\n decode: (wire: string): string => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'text',\n },\n },\n },\n },\n});\n\nconst pgCharCodec = aliasCodec(sqlCharCodec, {\n typeId: PG_CHAR_CODEC_ID,\n targetTypes: ['character'],\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'character',\n },\n },\n },\n },\n});\n\nconst pgVarcharCodec = aliasCodec(sqlVarcharCodec, {\n typeId: PG_VARCHAR_CODEC_ID,\n targetTypes: ['character varying'],\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'character varying',\n },\n },\n },\n },\n});\n\nconst pgIntCodec = aliasCodec(sqlIntCodec, {\n typeId: PG_INT_CODEC_ID,\n targetTypes: ['int4'],\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'integer',\n },\n },\n },\n },\n});\n\nconst pgFloatCodec = aliasCodec(sqlFloatCodec, {\n typeId: PG_FLOAT_CODEC_ID,\n targetTypes: ['float8'],\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'double precision',\n },\n },\n },\n },\n});\n\nconst pgInt4Codec = codec({\n typeId: PG_INT4_CODEC_ID,\n targetTypes: ['int4'],\n traits: ['equality', 'order', 'numeric'],\n encode: (value: number): number => value,\n decode: (wire: number): number => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'integer',\n },\n },\n },\n },\n});\n\nconst pgNumericCodec = codec<\n typeof PG_NUMERIC_CODEC_ID,\n readonly ['equality', 'order', 'numeric'],\n string,\n string\n>({\n typeId: PG_NUMERIC_CODEC_ID,\n targetTypes: ['numeric', 'decimal'],\n traits: ['equality', 'order', 'numeric'],\n encode: (value: string): string => value,\n decode: (wire: string | number): string => {\n if (typeof wire === 'number') return String(wire);\n return wire;\n },\n paramsSchema: numericParamsSchema,\n renderOutputType: (typeParams) => {\n const precision = typeParams['precision'];\n if (precision === undefined) return undefined;\n if (\n typeof precision !== 'number' ||\n !Number.isFinite(precision) ||\n !Number.isInteger(precision)\n ) {\n throw new Error(\n `renderOutputType: expected integer \"precision\" in typeParams for Numeric, got ${String(precision)}`,\n );\n }\n const scale = typeParams['scale'];\n return typeof scale === 'number' ? `Numeric<${precision}, ${scale}>` : `Numeric<${precision}>`;\n },\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'numeric',\n },\n },\n },\n },\n});\n\nconst pgInt2Codec = codec({\n typeId: PG_INT2_CODEC_ID,\n targetTypes: ['int2'],\n traits: ['equality', 'order', 'numeric'],\n encode: (value: number): number => value,\n decode: (wire: number): number => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'smallint',\n },\n },\n },\n },\n});\n\nconst pgInt8Codec = codec({\n typeId: PG_INT8_CODEC_ID,\n targetTypes: ['int8'],\n traits: ['equality', 'order', 'numeric'],\n encode: (value: number): number => value,\n decode: (wire: number): number => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'bigint',\n },\n },\n },\n },\n});\n\nconst pgFloat4Codec = codec({\n typeId: PG_FLOAT4_CODEC_ID,\n targetTypes: ['float4'],\n traits: ['equality', 'order', 'numeric'],\n encode: (value: number): number => value,\n decode: (wire: number): number => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'real',\n },\n },\n },\n },\n});\n\nconst pgFloat8Codec = codec({\n typeId: PG_FLOAT8_CODEC_ID,\n targetTypes: ['float8'],\n traits: ['equality', 'order', 'numeric'],\n encode: (value: number): number => value,\n decode: (wire: number): number => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'double precision',\n },\n },\n },\n },\n});\n\nconst pgTimestampCodec = codec<\n typeof PG_TIMESTAMP_CODEC_ID,\n readonly ['equality', 'order'],\n Date,\n Date\n>({\n typeId: PG_TIMESTAMP_CODEC_ID,\n targetTypes: ['timestamp'],\n traits: ['equality', 'order'],\n encode: (value: Date): Date => value,\n decode: (wire: Date): Date => wire,\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') {\n throw new Error(`Expected ISO date string for pg/timestamp@1, got ${typeof json}`);\n }\n const date = new Date(json);\n if (Number.isNaN(date.getTime())) {\n throw new Error(`Invalid ISO date string for pg/timestamp@1: ${json}`);\n }\n return date;\n },\n paramsSchema: precisionParamsSchema,\n renderOutputType: (typeParams) => renderPrecision('Timestamp', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'timestamp without time zone',\n },\n },\n },\n },\n});\n\nconst pgTimestamptzCodec = codec<\n typeof PG_TIMESTAMPTZ_CODEC_ID,\n readonly ['equality', 'order'],\n Date,\n Date\n>({\n typeId: PG_TIMESTAMPTZ_CODEC_ID,\n targetTypes: ['timestamptz'],\n traits: ['equality', 'order'],\n encode: (value: Date): Date => value,\n decode: (wire: Date): Date => wire,\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') {\n throw new Error(`Expected ISO date string for pg/timestamptz@1, got ${typeof json}`);\n }\n const date = new Date(json);\n if (Number.isNaN(date.getTime())) {\n throw new Error(`Invalid ISO date string for pg/timestamptz@1: ${json}`);\n }\n return date;\n },\n paramsSchema: precisionParamsSchema,\n renderOutputType: (typeParams) => renderPrecision('Timestamptz', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'timestamp with time zone',\n },\n },\n },\n },\n});\n\nconst pgTimeCodec = codec<typeof PG_TIME_CODEC_ID, readonly ['equality', 'order'], string, string>({\n typeId: PG_TIME_CODEC_ID,\n targetTypes: ['time'],\n traits: ['equality', 'order'],\n encode: (value: string): string => value,\n decode: (wire: string): string => wire,\n paramsSchema: precisionParamsSchema,\n renderOutputType: (typeParams) => renderPrecision('Time', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'time',\n },\n },\n },\n },\n});\n\nconst pgTimetzCodec = codec<\n typeof PG_TIMETZ_CODEC_ID,\n readonly ['equality', 'order'],\n string,\n string\n>({\n typeId: PG_TIMETZ_CODEC_ID,\n targetTypes: ['timetz'],\n traits: ['equality', 'order'],\n encode: (value: string): string => value,\n decode: (wire: string): string => wire,\n paramsSchema: precisionParamsSchema,\n renderOutputType: (typeParams) => renderPrecision('Timetz', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'timetz',\n },\n },\n },\n },\n});\n\nconst pgBoolCodec = codec({\n typeId: PG_BOOL_CODEC_ID,\n targetTypes: ['bool'],\n traits: ['equality', 'boolean'],\n encode: (value: boolean): boolean => value,\n decode: (wire: boolean): boolean => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'boolean',\n },\n },\n },\n },\n});\n\nconst pgBitCodec = codec<typeof PG_BIT_CODEC_ID, readonly ['equality', 'order'], string, string>({\n typeId: PG_BIT_CODEC_ID,\n targetTypes: ['bit'],\n traits: ['equality', 'order'],\n encode: (value: string): string => value,\n decode: (wire: string): string => wire,\n paramsSchema: lengthParamsSchema,\n renderOutputType: (typeParams) => renderLength('Bit', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'bit',\n },\n },\n },\n },\n});\n\nconst pgVarbitCodec = codec<\n typeof PG_VARBIT_CODEC_ID,\n readonly ['equality', 'order'],\n string,\n string\n>({\n typeId: PG_VARBIT_CODEC_ID,\n targetTypes: ['bit varying'],\n traits: ['equality', 'order'],\n encode: (value: string): string => value,\n decode: (wire: string): string => wire,\n paramsSchema: lengthParamsSchema,\n renderOutputType: (typeParams) => renderLength('VarBit', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'bit varying',\n },\n },\n },\n },\n});\n\nconst pgEnumCodec = codec({\n typeId: PG_ENUM_CODEC_ID,\n targetTypes: ['enum'],\n traits: ['equality', 'order'],\n encode: (value: string): string => value,\n decode: (wire: string): string => wire,\n renderOutputType: (typeParams) => {\n const values = typeParams['values'];\n if (!Array.isArray(values)) {\n throw new Error(\n `renderOutputType: expected array \"values\" in typeParams for enum, got ${typeof values}`,\n );\n }\n return values\n .map((value) => `'${String(value).replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`)\n .join(' | ');\n },\n});\n\nconst pgIntervalCodec = codec<\n typeof PG_INTERVAL_CODEC_ID,\n readonly ['equality', 'order'],\n string | Record<string, unknown>,\n string\n>({\n typeId: PG_INTERVAL_CODEC_ID,\n targetTypes: ['interval'],\n traits: ['equality', 'order'],\n encode: (value: string): string => value,\n decode: (wire: string | Record<string, unknown>): string => {\n if (typeof wire === 'string') return wire;\n return JSON.stringify(wire);\n },\n paramsSchema: precisionParamsSchema,\n renderOutputType: (typeParams) => renderPrecision('Interval', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'interval',\n },\n },\n },\n },\n});\n\nconst pgJsonCodec = codec({\n typeId: PG_JSON_CODEC_ID,\n targetTypes: ['json'],\n traits: [],\n encode: (value: string | JsonValue): string => JSON.stringify(value),\n decode: (wire: string | JsonValue): JsonValue =>\n typeof wire === 'string' ? JSON.parse(wire) : wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'json',\n },\n },\n },\n },\n});\n\nconst pgJsonbCodec = codec({\n typeId: PG_JSONB_CODEC_ID,\n targetTypes: ['jsonb'],\n traits: ['equality'],\n encode: (value: string | JsonValue): string => JSON.stringify(value),\n decode: (wire: string | JsonValue): JsonValue =>\n typeof wire === 'string' ? JSON.parse(wire) : wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'jsonb',\n },\n },\n },\n },\n});\n\n// Build codec definitions using the builder DSL\nconst codecs = defineCodecs()\n .add('char', sqlCharCodec)\n .add('varchar', sqlVarcharCodec)\n .add('int', sqlIntCodec)\n .add('float', sqlFloatCodec)\n .add('sql-text', sqlTextCodec)\n .add('sql-timestamp', sqlTimestampCodec)\n .add('text', pgTextCodec)\n .add('character', pgCharCodec)\n .add('character varying', pgVarcharCodec)\n .add('integer', pgIntCodec)\n .add('double precision', pgFloatCodec)\n .add('int4', pgInt4Codec)\n .add('int2', pgInt2Codec)\n .add('int8', pgInt8Codec)\n .add('float4', pgFloat4Codec)\n .add('float8', pgFloat8Codec)\n .add('numeric', pgNumericCodec)\n .add('timestamp', pgTimestampCodec)\n .add('timestamptz', pgTimestamptzCodec)\n .add('time', pgTimeCodec)\n .add('timetz', pgTimetzCodec)\n .add('bool', pgBoolCodec)\n .add('bit', pgBitCodec)\n .add('bit varying', pgVarbitCodec)\n .add('interval', pgIntervalCodec)\n .add('enum', pgEnumCodec)\n .add('json', pgJsonCodec)\n .add('jsonb', pgJsonbCodec);\n\n// Export derived structures directly from codecs builder\nexport const codecDefinitions = codecs.codecDefinitions;\nexport const dataTypes = codecs.dataTypes;\n\nexport type CodecTypes = typeof codecs.CodecTypes;\n"],"mappings":";;;;;;AA2CA,MAAM,qBAAqBA,KAAQ,EACjC,QAAQ,sBACT,CAAC;AAEF,MAAM,sBAAsBA,KAAQ;CAClC,WAAW;CACX,UAAU;CACX,CAAC;AAEF,MAAM,wBAAwBA,KAAQ,EACpC,cAAc,6CACf,CAAC;AAEF,SAAS,aAAa,UAAkB,YAAyD;CAC/F,MAAM,SAAS,WAAW;AAC1B,KAAI,WAAW,OACb;AAEF,KAAI,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,OAAO,IAAI,CAAC,OAAO,UAAU,OAAO,CACrF,OAAM,IAAI,MACR,iEAAiE,SAAS,QAAQ,OAAO,OAAO,GACjG;AAEH,QAAO,GAAG,SAAS,GAAG,OAAO;;AAG/B,SAAS,gBAAgB,UAAkB,YAA6C;CACtF,MAAM,YAAY,WAAW;AAC7B,KAAI,cAAc,OAChB,QAAO;AAET,KACE,OAAO,cAAc,YACrB,CAAC,OAAO,SAAS,UAAU,IAC3B,CAAC,OAAO,UAAU,UAAU,CAE5B,OAAM,IAAI,MACR,oEAAoE,SAAS,QAAQ,OAAO,UAAU,GACvG;AAEH,QAAO,GAAG,SAAS,GAAG,UAAU;;AAWlC,SAAS,WAQP,MACA,SAKkD;AAClD,QAAO;EACL,IAAI,QAAQ;EACZ,aAAa,QAAQ;EACrB,GAAG,UAAU,QAAQ,QAAQ,KAAK;EAClC,GAAG,UAAU,gBAAgB,KAAK,aAAa;EAC/C,GAAG,UAAU,QAAQ,KAAK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,YAAY,OAAO"}
package/dist/codecs.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { n as dataTypes, t as codecDefinitions } from "./codecs-OkTYeJQb.mjs";
1
+ import { n as dataTypes, t as codecDefinitions } from "./codecs-dzZ_dMpK.mjs";
2
2
 
3
3
  export { codecDefinitions, dataTypes };
package/dist/control.mjs CHANGED
@@ -3,7 +3,7 @@ import { t as parsePostgresDefault } from "./default-normalizer-DNOpRoOF.mjs";
3
3
  import { t as normalizeSchemaNativeType } from "./native-type-normalizer-CInai_oY.mjs";
4
4
  import { o as renderDefaultLiteral } from "./planner-ddl-builders-Dxvw1LHw.mjs";
5
5
  import "./issue-planner-CFjB0_oO.mjs";
6
- import { t as createPostgresMigrationPlanner } from "./planner-BGMG70Ns.mjs";
6
+ import { t as createPostgresMigrationPlanner } from "./planner-B4ZSLHRI.mjs";
7
7
  import { a as ensurePrismaContractSchemaStatement, i as ensureMarkerTableStatement, n as buildMergeMarkerStatements, r as ensureLedgerTableStatement, t as buildLedgerInsertStatement } from "./statement-builders-CHqCtSfe.mjs";
8
8
  import { ifDefined } from "@prisma-next/utils/defined";
9
9
  import { contractToSchemaIR, extractCodecControlHooks, runnerFailure, runnerSuccess } from "@prisma-next/family-sql/control";
@@ -56,7 +56,9 @@ var PostgresMigrationRunner = class {
56
56
  const existingMarker = await this.family.readMarker({ driver });
57
57
  const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);
58
58
  if (!markerCheck.ok) return markerCheck;
59
- const skipOperations = this.markerMatchesDestination(existingMarker, options.plan) && options.plan.origin != null;
59
+ const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);
60
+ const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;
61
+ const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;
60
62
  let applyValue;
61
63
  if (skipOperations) applyValue = {
62
64
  operationsExecuted: 0,
@@ -85,8 +87,13 @@ var PostgresMigrationRunner = class {
85
87
  why: "The resulting database schema does not satisfy the destination contract.",
86
88
  meta: { issues: schemaVerifyResult.schema.issues }
87
89
  });
88
- await this.upsertMarker(driver, options, existingMarker);
89
- await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);
90
+ const incomingInvariants = options.plan.providedInvariants;
91
+ const existingInvariants = new Set(existingMarker?.invariants ?? []);
92
+ const incomingIsSubsetOfExisting = incomingInvariants.every((id) => existingInvariants.has(id));
93
+ if (!(isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting)) {
94
+ await this.upsertMarker(driver, options, existingMarker);
95
+ await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);
96
+ }
90
97
  await this.commitTransaction(driver);
91
98
  committed = true;
92
99
  return runnerSuccess({
@@ -307,7 +314,7 @@ var PostgresMigrationRunner = class {
307
314
  return okVoid();
308
315
  }
309
316
  async upsertMarker(driver, options, existingMarker) {
310
- const incomingInvariants = Array.from(new Set(options.invariants ?? [])).sort();
317
+ const incomingInvariants = options.plan.providedInvariants;
311
318
  const writeStatements = buildMergeMarkerStatements({
312
319
  storageHash: options.plan.destination.storageHash,
313
320
  profileHash: options.plan.destination.profileHash ?? options.destinationContract.profileHash ?? options.plan.destination.storageHash,
@@ -1 +1 @@
1
- {"version":3,"file":"control.mjs","names":["DEFAULT_CONFIG: RunnerConfig","cloned: Record<string, unknown>","family: SqlControlFamilyInstance","config: RunnerConfig","applyValue: ApplyPlanSuccessValue","executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>","error: unknown","postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails>"],"sources":["../src/core/migrations/runner.ts","../src/exports/control.ts"],"sourcesContent":["import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { DataTransformOperation } from '@prisma-next/framework-components/control';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { ok, okVoid } from '@prisma-next/utils/result';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport {\n buildLedgerInsertStatement,\n buildMergeMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n ensurePrismaContractSchemaStatement,\n type SqlStatement,\n} from './statement-builders';\n\ninterface RunnerConfig {\n readonly defaultSchema: string;\n}\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst DEFAULT_CONFIG: RunnerConfig = {\n defaultSchema: 'public',\n};\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\nfunction isDataTransformOperation(op: unknown): op is DataTransformOperation {\n return (\n typeof op === 'object' &&\n op !== null &&\n 'operationClass' in op &&\n (op as { operationClass: string }).operationClass === 'data' &&\n 'name' in op &&\n 'check' in op &&\n 'run' in op\n );\n}\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n const lockKey = `${LOCK_DOMAIN}:${schema}`;\n\n // Static checks - fail fast before transaction\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) {\n return destinationCheck;\n }\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) {\n return policyCheck;\n }\n\n // Begin transaction for DB operations\n await this.beginTransaction(driver);\n let committed = false;\n try {\n await this.acquireLock(driver, lockKey);\n await this.ensureControlTables(driver);\n const existingMarker = await this.family.readMarker({ driver });\n\n // Validate plan origin matches existing marker (needs marker from DB)\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) {\n return markerCheck;\n }\n\n // db update (origin: null) always applies; migration-apply (origin set) skips if marker matches.\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const skipOperations = markerAtDestination && options.plan.origin != null;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) {\n return applyResult;\n }\n applyValue = applyResult.value;\n }\n\n // Verify resulting schema matches contract\n // Step 1: Introspect live schema (DB I/O, family-owned)\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\n\n // Step 2: Pure verification (no DB I/O)\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: {\n issues: schemaVerifyResult.schema.issues,\n },\n });\n }\n\n // Record marker and ledger entries\n await this.upsertMarker(driver, options, existingMarker);\n await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);\n\n await this.commitTransaction(driver);\n committed = true;\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Data transform operations have a different execution lifecycle\n if (operation.operationClass === 'data' && isDataTransformOperation(operation)) {\n const dtResult = await this.executeDataTransform(driver, operation, {\n runIdempotency,\n });\n if (!dtResult.ok) {\n return dtResult;\n }\n executedOperations.push(operation);\n operationsExecuted += 1;\n continue;\n }\n\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n }\n\n // Prechecks: only run if enabled\n if (runPrechecks) {\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n /**\n * Executes a data transform operation with the check → (skip or run) → check lifecycle.\n *\n * 1. If check is a query AST: render to SQL, execute. Empty result = already applied (skip).\n * 2. If check is `true`: always skip. If `false`: always run.\n * 3. Execute run ASTs (rendered to SQL) sequentially.\n * 4. Re-execute check as post-run validation. If violations remain, fail.\n */\n private async executeDataTransform(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n op: DataTransformOperation,\n options: { runIdempotency: boolean },\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n // Step 1: Check (skip guard)\n if (op.check === true) {\n // Always skip, regardless of idempotency setting\n return okVoid();\n }\n if (options.runIdempotency && op.check !== null && op.check !== false) {\n const checkResult = await driver.query(op.check.sql, op.check.params);\n if (checkResult.rows.length === 0) {\n // No violations — already applied, skip\n return okVoid();\n }\n }\n\n // Step 2: Execute run steps\n if (op.run) {\n for (const plan of op.run) {\n try {\n await driver.query(plan.sql, plan.params);\n } catch (error: unknown) {\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Data transform \"${op.name}\" failed: ${error.message}`,\n {\n why: error.message,\n meta: {\n operationId: op.id,\n dataTransformName: op.name,\n sql: plan.sql,\n sqlState: error.sqlState,\n },\n },\n );\n }\n throw error;\n }\n }\n }\n\n // Step 3: Post-run validation (check again)\n if (op.check !== null && op.check !== false) {\n const checkResult = await driver.query(op.check.sql, op.check.params);\n if (checkResult.rows.length > 0) {\n return runnerFailure(\n 'POSTCHECK_FAILED',\n `Data transform \"${op.name}\" did not resolve all violations (${checkResult.rows.length} remaining)`,\n {\n why: `After executing the data transform, the check query still returns ${checkResult.rows.length} violation(s).`,\n meta: {\n operationId: op.id,\n dataTransformName: op.name,\n remainingViolations: checkResult.rows.length,\n },\n },\n );\n }\n }\n\n return okVoid();\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql);\n } catch (error: unknown) {\n // Catch SqlQueryError and include normalized metadata\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n // Let SqlConnectionError and other errors propagate (fail-fast)\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.storageHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n ): Promise<void> {\n // Sort + dedupe so the INSERT path writes a stable initial value.\n // UPDATE merges server-side, so no client-side union is needed.\n const incomingInvariants = Array.from(new Set(options.invariants ?? [])).sort();\n const writeStatements = buildMergeMarkerStatements({\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJson: options.destinationContract,\n canonicalVersion: null,\n meta: {},\n invariants: incomingInvariants,\n });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<void> {\n const ledgerStatement = buildLedgerInsertStatement({\n originStorageHash: existingMarker?.storageHash ?? null,\n originProfileHash: existingMarker?.profileHash ?? null,\n destinationStorageHash: options.plan.destination.storageHash,\n destinationProfileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJsonBefore: existingMarker?.contractJson ?? null,\n contractJsonAfter: options.destinationContract,\n operations: executedOperations,\n });\n await this.executeStatement(driver, ledgerStatement);\n }\n\n private async acquireLock(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlStatement,\n ): Promise<void> {\n if (statement.params.length > 0) {\n await driver.query(statement.sql, statement.params);\n return;\n }\n await driver.query(statement.sql);\n }\n}\n","import type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n // Mirror `renderExpectedNativeType` in verify-sql-schema: when a codec\n // has no `expandNativeType` hook (e.g. `pg/enum@1`, whose typeParams\n // describe the value set rather than a DDL suffix), fall back to the\n // bare native type rather than throwing. Throwing here would reject\n // every plan involving an enum-/values-typed column as soon as its\n // `typeRef` resolved to a `StorageTypeInstance` carrying typeParams.\n if (!input.codecId) return input.nativeType;\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) return input.nativeType;\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n return contractToSchemaIR(contract as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: frameworkComponents ?? [],\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;;AAwCA,MAA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qB,IAAI,OAAO,OAAO;;AAGhD,MAAMC,2BACJ;CACE,GAAG;CACH,YAAY;EACV,cAAc,SAAmC;AAC/C,UAAO,gCAAgC;;EAEzC,aAAa,QAAQ;AACnB,UAAO,8BAA8B,OAAO;;EAE9C,iBAAiB,UAAU,qBAAqB;AAE9C,UAAO,mBAAmB,UAAyC;IACjE,qBAAqB;IACrB,GAAG,UAAU,oBAHE,wBAAwB,oBAAoB,CAGjB;IAC1C,eAAe;IACf,qBAAqB,uBAAuB,EAAE;IAC/C,CAAC;;EAEL;CACD,SAAmD;AACjD,SAAO;GACL,UAAU;GACV,UAAU;GACX;;CAMH,cAAc,SAAmC;AAC/C,SAAO,gCAAgC;;CAMzC,aAAa,QAAQ;AACnB,SAAO,8BAA8B,OAAO;;CAE/C;AAEH,sBAAe"}
1
+ {"version":3,"file":"control.mjs","names":["DEFAULT_CONFIG: RunnerConfig","cloned: Record<string, unknown>","family: SqlControlFamilyInstance","config: RunnerConfig","applyValue: ApplyPlanSuccessValue","executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>>","error: unknown","postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails>"],"sources":["../src/core/migrations/runner.ts","../src/exports/control.ts"],"sourcesContent":["import type { ContractMarkerRecord } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlControlFamilyInstance,\n SqlMigrationPlanContractInfo,\n SqlMigrationPlanOperation,\n SqlMigrationPlanOperationStep,\n SqlMigrationRunner,\n SqlMigrationRunnerExecuteOptions,\n SqlMigrationRunnerFailure,\n SqlMigrationRunnerResult,\n} from '@prisma-next/family-sql/control';\nimport { runnerFailure, runnerSuccess } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { DataTransformOperation } from '@prisma-next/framework-components/control';\nimport { SqlQueryError } from '@prisma-next/sql-errors';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { Result } from '@prisma-next/utils/result';\nimport { ok, okVoid } from '@prisma-next/utils/result';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport type { PostgresPlanTargetDetails } from './planner-target-details';\nimport {\n buildLedgerInsertStatement,\n buildMergeMarkerStatements,\n ensureLedgerTableStatement,\n ensureMarkerTableStatement,\n ensurePrismaContractSchemaStatement,\n type SqlStatement,\n} from './statement-builders';\n\ninterface RunnerConfig {\n readonly defaultSchema: string;\n}\n\ninterface ApplyPlanSuccessValue {\n readonly operationsExecuted: number;\n readonly executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[];\n}\n\nconst DEFAULT_CONFIG: RunnerConfig = {\n defaultSchema: 'public',\n};\n\nconst LOCK_DOMAIN = 'prisma_next.contract.marker';\n\nfunction isDataTransformOperation(op: unknown): op is DataTransformOperation {\n return (\n typeof op === 'object' &&\n op !== null &&\n 'operationClass' in op &&\n (op as { operationClass: string }).operationClass === 'data' &&\n 'name' in op &&\n 'check' in op &&\n 'run' in op\n );\n}\n\n/**\n * Deep clones and freezes a record object to prevent mutation.\n * Recursively clones nested objects and arrays to ensure complete isolation.\n */\nfunction cloneAndFreezeRecord<T extends Record<string, unknown>>(value: T): T {\n const cloned: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val === null || val === undefined) {\n cloned[key] = val;\n } else if (Array.isArray(val)) {\n // Clone array (shallow clone of array elements)\n cloned[key] = Object.freeze([...val]);\n } else if (typeof val === 'object') {\n // Recursively clone nested objects\n cloned[key] = cloneAndFreezeRecord(val as Record<string, unknown>);\n } else {\n // Primitives are copied as-is\n cloned[key] = val;\n }\n }\n return Object.freeze(cloned) as T;\n}\n\nexport function createPostgresMigrationRunner(\n family: SqlControlFamilyInstance,\n config: Partial<RunnerConfig> = {},\n): SqlMigrationRunner<PostgresPlanTargetDetails> {\n return new PostgresMigrationRunner(family, { ...DEFAULT_CONFIG, ...config });\n}\n\nclass PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDetails> {\n constructor(\n private readonly family: SqlControlFamilyInstance,\n private readonly config: RunnerConfig,\n ) {}\n\n async execute(\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<SqlMigrationRunnerResult> {\n const schema = options.schemaName ?? this.config.defaultSchema;\n const driver = options.driver;\n const lockKey = `${LOCK_DOMAIN}:${schema}`;\n\n // Static checks - fail fast before transaction\n const destinationCheck = this.ensurePlanMatchesDestinationContract(\n options.plan.destination,\n options.destinationContract,\n );\n if (!destinationCheck.ok) {\n return destinationCheck;\n }\n\n const policyCheck = this.enforcePolicyCompatibility(options.policy, options.plan.operations);\n if (!policyCheck.ok) {\n return policyCheck;\n }\n\n // Begin transaction for DB operations\n await this.beginTransaction(driver);\n let committed = false;\n try {\n await this.acquireLock(driver, lockKey);\n await this.ensureControlTables(driver);\n const existingMarker = await this.family.readMarker({ driver });\n\n // Validate plan origin matches existing marker (needs marker from DB)\n const markerCheck = this.ensureMarkerCompatibility(existingMarker, options.plan);\n if (!markerCheck.ok) {\n return markerCheck;\n }\n\n // db update (origin: null) always applies; migration-apply (origin set,\n // origin !== destination) skips if marker already matches destination.\n // Self-edges (origin === destination) intentionally bypass the skip:\n // the migration is data-only, and the data transform's own check\n // decides whether `run` fires.\n const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);\n const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;\n const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;\n let applyValue: ApplyPlanSuccessValue;\n\n if (skipOperations) {\n applyValue = { operationsExecuted: 0, executedOperations: [] };\n } else {\n const applyResult = await this.applyPlan(driver, options);\n if (!applyResult.ok) {\n return applyResult;\n }\n applyValue = applyResult.value;\n }\n\n // Verify resulting schema matches contract\n // Step 1: Introspect live schema (DB I/O, family-owned)\n const schemaIR = await this.family.introspect({\n driver,\n contract: options.destinationContract,\n });\n\n // Step 2: Pure verification (no DB I/O)\n const schemaVerifyResult = verifySqlSchema({\n contract: options.destinationContract,\n schema: schemaIR,\n strict: options.strictVerification ?? true,\n context: options.context ?? {},\n typeMetadataRegistry: this.family.typeMetadataRegistry,\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n });\n if (!schemaVerifyResult.ok) {\n return runnerFailure('SCHEMA_VERIFY_FAILED', schemaVerifyResult.summary, {\n why: 'The resulting database schema does not satisfy the destination contract.',\n meta: {\n issues: schemaVerifyResult.schema.issues,\n },\n });\n }\n\n // Self-edge no-op detection: a self-edge migration with zero ops in\n // the plan that brings no new invariants produced no observable\n // change. Skip the marker + ledger writes so an idempotent re-apply\n // of a self-edge data transform doesn't churn updatedAt or pile up\n // empty ledger entries. db update no-ops still write a ledger entry\n // as audit trail.\n //\n // TODO(invariant-routing follow-up): `executeDataTransform` always\n // counts every op it visits (including self-skips via `check === true`\n // or empty idempotency probe), so `operationsExecuted === 0` here\n // means \"the plan had zero ops\" rather than \"every op self-skipped\".\n // The CLI is unaffected today because `migration-apply.ts` marker-\n // subtraction empties `effectiveRequired` first and short-circuits\n // before we run; the non-CLI re-apply path needs a per-op `executed`\n // flag threaded through `executeDataTransform` to recover the\n // intended check. See review thread A13 / future M5 ADR draft.\n const incomingInvariants = options.plan.providedInvariants;\n const existingInvariants = new Set(existingMarker?.invariants ?? []);\n const incomingIsSubsetOfExisting = incomingInvariants.every((id) =>\n existingInvariants.has(id),\n );\n const isSelfEdgeNoOp =\n isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting;\n\n if (!isSelfEdgeNoOp) {\n await this.upsertMarker(driver, options, existingMarker);\n await this.recordLedgerEntry(\n driver,\n options,\n existingMarker,\n applyValue.executedOperations,\n );\n }\n\n await this.commitTransaction(driver);\n committed = true;\n return runnerSuccess({\n operationsPlanned: options.plan.operations.length,\n operationsExecuted: applyValue.operationsExecuted,\n });\n } finally {\n if (!committed) {\n await this.rollbackTransaction(driver);\n }\n }\n }\n\n private async applyPlan(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n ): Promise<Result<ApplyPlanSuccessValue, SqlMigrationRunnerFailure>> {\n const checks = options.executionChecks;\n const runPrechecks = checks?.prechecks !== false; // Default true\n const runPostchecks = checks?.postchecks !== false; // Default true\n const runIdempotency = checks?.idempotencyChecks !== false; // Default true\n\n let operationsExecuted = 0;\n const executedOperations: Array<SqlMigrationPlanOperation<PostgresPlanTargetDetails>> = [];\n for (const operation of options.plan.operations) {\n options.callbacks?.onOperationStart?.(operation);\n try {\n // Data transform operations have a different execution lifecycle\n if (operation.operationClass === 'data' && isDataTransformOperation(operation)) {\n const dtResult = await this.executeDataTransform(driver, operation, {\n runIdempotency,\n });\n if (!dtResult.ok) {\n return dtResult;\n }\n executedOperations.push(operation);\n operationsExecuted += 1;\n continue;\n }\n\n // Idempotency probe: only run if both postchecks and idempotency checks are enabled\n if (runPostchecks && runIdempotency) {\n const postcheckAlreadySatisfied = await this.expectationsAreSatisfied(\n driver,\n operation.postcheck,\n );\n if (postcheckAlreadySatisfied) {\n executedOperations.push(this.createPostcheckPreSatisfiedSkipRecord(operation));\n continue;\n }\n }\n\n // Prechecks: only run if enabled\n if (runPrechecks) {\n const precheckResult = await this.runExpectationSteps(\n driver,\n operation.precheck,\n operation,\n 'precheck',\n );\n if (!precheckResult.ok) {\n return precheckResult;\n }\n }\n\n const executeResult = await this.runExecuteSteps(driver, operation.execute, operation);\n if (!executeResult.ok) {\n return executeResult;\n }\n\n // Postchecks: only run if enabled\n if (runPostchecks) {\n const postcheckResult = await this.runExpectationSteps(\n driver,\n operation.postcheck,\n operation,\n 'postcheck',\n );\n if (!postcheckResult.ok) {\n return postcheckResult;\n }\n }\n\n executedOperations.push(operation);\n operationsExecuted += 1;\n } finally {\n options.callbacks?.onOperationComplete?.(operation);\n }\n }\n return ok({ operationsExecuted, executedOperations });\n }\n\n /**\n * Executes a data transform operation with the check → (skip or run) → check lifecycle.\n *\n * 1. If check is a query AST: render to SQL, execute. Empty result = already applied (skip).\n * 2. If check is `true`: always skip. If `false`: always run.\n * 3. Execute run ASTs (rendered to SQL) sequentially.\n * 4. Re-execute check as post-run validation. If violations remain, fail.\n */\n private async executeDataTransform(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n op: DataTransformOperation,\n options: { runIdempotency: boolean },\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n // Step 1: Check (skip guard)\n if (op.check === true) {\n // Always skip, regardless of idempotency setting\n return okVoid();\n }\n if (options.runIdempotency && op.check !== null && op.check !== false) {\n const checkResult = await driver.query(op.check.sql, op.check.params);\n if (checkResult.rows.length === 0) {\n // No violations — already applied, skip\n return okVoid();\n }\n }\n\n // Step 2: Execute run steps\n if (op.run) {\n for (const plan of op.run) {\n try {\n await driver.query(plan.sql, plan.params);\n } catch (error: unknown) {\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Data transform \"${op.name}\" failed: ${error.message}`,\n {\n why: error.message,\n meta: {\n operationId: op.id,\n dataTransformName: op.name,\n sql: plan.sql,\n sqlState: error.sqlState,\n },\n },\n );\n }\n throw error;\n }\n }\n }\n\n // Step 3: Post-run validation (check again)\n if (op.check !== null && op.check !== false) {\n const checkResult = await driver.query(op.check.sql, op.check.params);\n if (checkResult.rows.length > 0) {\n return runnerFailure(\n 'POSTCHECK_FAILED',\n `Data transform \"${op.name}\" did not resolve all violations (${checkResult.rows.length} remaining)`,\n {\n why: `After executing the data transform, the check query still returns ${checkResult.rows.length} violation(s).`,\n meta: {\n operationId: op.id,\n dataTransformName: op.name,\n remainingViolations: checkResult.rows.length,\n },\n },\n );\n }\n }\n\n return okVoid();\n }\n\n private async ensureControlTables(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await this.executeStatement(driver, ensurePrismaContractSchemaStatement);\n await this.executeStatement(driver, ensureMarkerTableStatement);\n await this.executeStatement(driver, ensureLedgerTableStatement);\n }\n\n private async runExpectationSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n phase: 'precheck' | 'postcheck',\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n const code = phase === 'precheck' ? 'PRECHECK_FAILED' : 'POSTCHECK_FAILED';\n return runnerFailure(\n code,\n `Operation ${operation.id} failed during ${phase}: ${step.description}`,\n {\n meta: {\n operationId: operation.id,\n phase,\n stepDescription: step.description,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private async runExecuteSteps(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): Promise<Result<void, SqlMigrationRunnerFailure>> {\n for (const step of steps) {\n try {\n await driver.query(step.sql);\n } catch (error: unknown) {\n // Catch SqlQueryError and include normalized metadata\n if (SqlQueryError.is(error)) {\n return runnerFailure(\n 'EXECUTION_FAILED',\n `Operation ${operation.id} failed during execution: ${step.description}`,\n {\n why: error.message,\n meta: {\n operationId: operation.id,\n stepDescription: step.description,\n sql: step.sql,\n sqlState: error.sqlState,\n constraint: error.constraint,\n table: error.table,\n column: error.column,\n detail: error.detail,\n },\n },\n );\n }\n // Let SqlConnectionError and other errors propagate (fail-fast)\n throw error;\n }\n }\n return okVoid();\n }\n\n private stepResultIsTrue(rows: readonly Record<string, unknown>[]): boolean {\n if (!rows || rows.length === 0) {\n return false;\n }\n const firstRow = rows[0];\n const firstValue = firstRow ? Object.values(firstRow)[0] : undefined;\n if (typeof firstValue === 'boolean') {\n return firstValue;\n }\n if (typeof firstValue === 'number') {\n return firstValue !== 0;\n }\n if (typeof firstValue === 'string') {\n const lower = firstValue.toLowerCase();\n // PostgreSQL boolean representations: 't'/'f', 'true'/'false', '1'/'0'\n if (lower === 't' || lower === 'true' || lower === '1') {\n return true;\n }\n if (lower === 'f' || lower === 'false' || lower === '0') {\n return false;\n }\n // For other strings, non-empty is truthy (though this case shouldn't occur for boolean checks)\n return firstValue.length > 0;\n }\n return Boolean(firstValue);\n }\n\n private async expectationsAreSatisfied(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n steps: readonly SqlMigrationPlanOperationStep[],\n ): Promise<boolean> {\n if (steps.length === 0) {\n return false;\n }\n for (const step of steps) {\n const result = await driver.query(step.sql);\n if (!this.stepResultIsTrue(result.rows)) {\n return false;\n }\n }\n return true;\n }\n\n private createPostcheckPreSatisfiedSkipRecord(\n operation: SqlMigrationPlanOperation<PostgresPlanTargetDetails>,\n ): SqlMigrationPlanOperation<PostgresPlanTargetDetails> {\n // Clone and freeze existing meta if present\n const clonedMeta = operation.meta ? cloneAndFreezeRecord(operation.meta) : undefined;\n\n // Create frozen runner metadata\n const runnerMeta = Object.freeze({\n skipped: true,\n reason: 'postcheck_pre_satisfied',\n });\n\n // Merge and freeze the combined meta\n const mergedMeta = Object.freeze({\n ...(clonedMeta ?? {}),\n runner: runnerMeta,\n });\n\n // Clone and freeze arrays to prevent mutation\n const frozenPostcheck = Object.freeze([...operation.postcheck]);\n\n return Object.freeze({\n id: operation.id,\n label: operation.label,\n ...ifDefined('summary', operation.summary),\n operationClass: operation.operationClass,\n target: operation.target, // Already frozen from plan creation\n precheck: Object.freeze([]),\n execute: Object.freeze([]),\n postcheck: frozenPostcheck,\n ...ifDefined('meta', operation.meta || mergedMeta ? mergedMeta : undefined),\n });\n }\n\n private markerMatchesDestination(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): boolean {\n if (!marker) {\n return false;\n }\n if (marker.storageHash !== plan.destination.storageHash) {\n return false;\n }\n if (plan.destination.profileHash && marker.profileHash !== plan.destination.profileHash) {\n return false;\n }\n return true;\n }\n\n private enforcePolicyCompatibility(\n policy: MigrationOperationPolicy,\n operations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Result<void, SqlMigrationRunnerFailure> {\n const allowedClasses = new Set(policy.allowedOperationClasses);\n for (const operation of operations) {\n if (!allowedClasses.has(operation.operationClass)) {\n return runnerFailure(\n 'POLICY_VIOLATION',\n `Operation ${operation.id} has class \"${operation.operationClass}\" which is not allowed by policy.`,\n {\n why: `Policy only allows: ${policy.allowedOperationClasses.join(', ')}.`,\n meta: {\n operationId: operation.id,\n operationClass: operation.operationClass,\n allowedClasses: policy.allowedOperationClasses,\n },\n },\n );\n }\n }\n return okVoid();\n }\n\n private ensureMarkerCompatibility(\n marker: ContractMarkerRecord | null,\n plan: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['plan'],\n ): Result<void, SqlMigrationRunnerFailure> {\n const origin = plan.origin ?? null;\n if (!origin) {\n // No origin assertion on the plan — the caller does not want origin validation.\n // This is the case for `db update`, which introspects the live schema and does not\n // rely on marker continuity. `db init` handles its own marker checks before the runner.\n return okVoid();\n }\n\n if (!marker) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Missing contract marker: expected origin storage hash ${origin.storageHash}.`,\n {\n meta: {\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (marker.storageHash !== origin.storageHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker (${marker.storageHash}) does not match plan origin (${origin.storageHash}).`,\n {\n meta: {\n markerStorageHash: marker.storageHash,\n expectedOriginStorageHash: origin.storageHash,\n },\n },\n );\n }\n if (origin.profileHash && marker.profileHash !== origin.profileHash) {\n return runnerFailure(\n 'MARKER_ORIGIN_MISMATCH',\n `Existing contract marker profile hash (${marker.profileHash}) does not match plan origin profile hash (${origin.profileHash}).`,\n {\n meta: {\n markerProfileHash: marker.profileHash,\n expectedOriginProfileHash: origin.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private ensurePlanMatchesDestinationContract(\n destination: SqlMigrationPlanContractInfo,\n contract: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['destinationContract'],\n ): Result<void, SqlMigrationRunnerFailure> {\n if (destination.storageHash !== contract.storage.storageHash) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination storage hash (${destination.storageHash}) does not match provided contract storage hash (${contract.storage.storageHash}).`,\n {\n meta: {\n planStorageHash: destination.storageHash,\n contractStorageHash: contract.storage.storageHash,\n },\n },\n );\n }\n if (\n destination.profileHash &&\n contract.profileHash &&\n destination.profileHash !== contract.profileHash\n ) {\n return runnerFailure(\n 'DESTINATION_CONTRACT_MISMATCH',\n `Plan destination profile hash (${destination.profileHash}) does not match provided contract profile hash (${contract.profileHash}).`,\n {\n meta: {\n planProfileHash: destination.profileHash,\n contractProfileHash: contract.profileHash,\n },\n },\n );\n }\n return okVoid();\n }\n\n private async upsertMarker(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n ): Promise<void> {\n const incomingInvariants = options.plan.providedInvariants;\n const writeStatements = buildMergeMarkerStatements({\n storageHash: options.plan.destination.storageHash,\n profileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJson: options.destinationContract,\n canonicalVersion: null,\n meta: {},\n invariants: incomingInvariants,\n });\n const statement = existingMarker ? writeStatements.update : writeStatements.insert;\n await this.executeStatement(driver, statement);\n }\n\n private async recordLedgerEntry(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,\n existingMarker: ContractMarkerRecord | null,\n executedOperations: readonly SqlMigrationPlanOperation<PostgresPlanTargetDetails>[],\n ): Promise<void> {\n const ledgerStatement = buildLedgerInsertStatement({\n originStorageHash: existingMarker?.storageHash ?? null,\n originProfileHash: existingMarker?.profileHash ?? null,\n destinationStorageHash: options.plan.destination.storageHash,\n destinationProfileHash:\n options.plan.destination.profileHash ??\n options.destinationContract.profileHash ??\n options.plan.destination.storageHash,\n contractJsonBefore: existingMarker?.contractJson ?? null,\n contractJsonAfter: options.destinationContract,\n operations: executedOperations,\n });\n await this.executeStatement(driver, ledgerStatement);\n }\n\n private async acquireLock(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n key: string,\n ): Promise<void> {\n await driver.query('select pg_advisory_xact_lock(hashtext($1))', [key]);\n }\n\n private async beginTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('BEGIN');\n }\n\n private async commitTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('COMMIT');\n }\n\n private async rollbackTransaction(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n ): Promise<void> {\n await driver.query('ROLLBACK');\n }\n\n private async executeStatement(\n driver: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>['driver'],\n statement: SqlStatement,\n ): Promise<void> {\n if (statement.params.length > 0) {\n await driver.query(statement.sql, statement.params);\n return;\n }\n await driver.query(statement.sql);\n }\n}\n","import type { ColumnDefault, Contract } from '@prisma-next/contract/types';\nimport type {\n SqlControlFamilyInstance,\n SqlControlTargetDescriptor,\n} from '@prisma-next/family-sql/control';\nimport { contractToSchemaIR, extractCodecControlHooks } from '@prisma-next/family-sql/control';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n ControlTargetInstance,\n MigrationRunner,\n} from '@prisma-next/framework-components/control';\nimport type { SqlStorage, StorageColumn } from '@prisma-next/sql-contract/types';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { postgresTargetDescriptorMeta } from '../core/descriptor-meta';\nimport { createPostgresMigrationPlanner } from '../core/migrations/planner';\nimport { renderDefaultLiteral } from '../core/migrations/planner-ddl-builders';\nimport type { PostgresPlanTargetDetails } from '../core/migrations/planner-target-details';\nimport { createPostgresMigrationRunner } from '../core/migrations/runner';\n\nfunction buildNativeTypeExpander(\n frameworkComponents?: ReadonlyArray<TargetBoundComponentDescriptor<'sql', 'postgres'>>,\n) {\n if (!frameworkComponents) {\n return undefined;\n }\n const codecHooks = extractCodecControlHooks(frameworkComponents);\n return (input: {\n readonly nativeType: string;\n readonly codecId?: string;\n readonly typeParams?: Record<string, unknown>;\n }) => {\n if (!input.typeParams) return input.nativeType;\n // Mirror `renderExpectedNativeType` in verify-sql-schema: when a codec\n // has no `expandNativeType` hook (e.g. `pg/enum@1`, whose typeParams\n // describe the value set rather than a DDL suffix), fall back to the\n // bare native type rather than throwing. Throwing here would reject\n // every plan involving an enum-/values-typed column as soon as its\n // `typeRef` resolved to a `StorageTypeInstance` carrying typeParams.\n if (!input.codecId) return input.nativeType;\n const hooks = codecHooks.get(input.codecId);\n if (!hooks?.expandNativeType) return input.nativeType;\n return hooks.expandNativeType(input);\n };\n}\n\nexport function postgresRenderDefault(def: ColumnDefault, column: StorageColumn): string {\n if (def.kind === 'function') {\n return def.expression;\n }\n return renderDefaultLiteral(def.value, column);\n}\n\nconst postgresTargetDescriptor: SqlControlTargetDescriptor<'postgres', PostgresPlanTargetDetails> =\n {\n ...postgresTargetDescriptorMeta,\n migrations: {\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n createRunner(family) {\n return createPostgresMigrationRunner(family) as MigrationRunner<'sql', 'postgres'>;\n },\n contractToSchema(contract, frameworkComponents) {\n const expander = buildNativeTypeExpander(frameworkComponents);\n return contractToSchemaIR(contract as Contract<SqlStorage> | null, {\n annotationNamespace: 'pg',\n ...ifDefined('expandNativeType', expander),\n renderDefault: postgresRenderDefault,\n frameworkComponents: frameworkComponents ?? [],\n });\n },\n },\n create(): ControlTargetInstance<'sql', 'postgres'> {\n return {\n familyId: 'sql',\n targetId: 'postgres',\n };\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createPlanner() for CLI compatibility.\n */\n createPlanner(_family: SqlControlFamilyInstance) {\n return createPostgresMigrationPlanner();\n },\n /**\n * Direct method for SQL-specific usage.\n * @deprecated Use migrations.createRunner() for CLI compatibility.\n */\n createRunner(family) {\n return createPostgresMigrationRunner(family);\n },\n };\n\nexport default postgresTargetDescriptor;\n"],"mappings":";;;;;;;;;;;;;;AAwCA,MAAMA,iBAA+B,EACnC,eAAe,UAChB;AAED,MAAM,cAAc;AAEpB,SAAS,yBAAyB,IAA2C;AAC3E,QACE,OAAO,OAAO,YACd,OAAO,QACP,oBAAoB,MACnB,GAAkC,mBAAmB,UACtD,UAAU,MACV,WAAW,MACX,SAAS;;;;;;AAQb,SAAS,qBAAwD,OAAa;CAC5E,MAAMC,SAAkC,EAAE;AAC1C,MAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,MAAM,CAC5C,KAAI,QAAQ,QAAQ,QAAQ,OAC1B,QAAO,OAAO;UACL,MAAM,QAAQ,IAAI,CAE3B,QAAO,OAAO,OAAO,OAAO,CAAC,GAAG,IAAI,CAAC;UAC5B,OAAO,QAAQ,SAExB,QAAO,OAAO,qBAAqB,IAA+B;KAGlE,QAAO,OAAO;AAGlB,QAAO,OAAO,OAAO,OAAO;;AAG9B,SAAgB,8BACd,QACA,SAAgC,EAAE,EACa;AAC/C,QAAO,IAAI,wBAAwB,QAAQ;EAAE,GAAG;EAAgB,GAAG;EAAQ,CAAC;;AAG9E,IAAM,0BAAN,MAAuF;CACrF,YACE,AAAiBC,QACjB,AAAiBC,QACjB;EAFiB;EACA;;CAGnB,MAAM,QACJ,SACmC;E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yBAAA;;2BAEL;;eAEZ;kBAEG;UAQR;;;cAaG,mBAAA,SAA4B,yBAAA;;;;;;UAa/B;;;cASG,gBAAA,SAAyB,yBAAA;;;;;;UAa5B;;;;;;;;;;cAoBG,iBAAA,SAA0B,yBAAA;;2BAEZ;;;;kFASP;UAUV;;iCAagC;;KAa9B,qBAAA,GACR,kBACA,gBACA,gBACA,iBACA,sBACA,iBACA,kBACA,iBACA,kBACA,oBACA,oBACA,gBACA,kBACA,gBACA,qBACA,qBACA,oBACA,mBACA,iBACA,aACA,sBACA,mBACA"}
@@ -34,7 +34,7 @@ var PostgresMigrationPlanner = class {
34
34
  this.config = config;
35
35
  }
36
36
  plan(options) {
37
- return this.planSql(options, options.fromHash ?? null);
37
+ return this.planSql(options);
38
38
  }
39
39
  emptyMigration(context) {
40
40
  return new TypeScriptRenderablePostgresMigration([], {
@@ -42,7 +42,7 @@ var PostgresMigrationPlanner = class {
42
42
  to: context.toHash
43
43
  });
44
44
  }
45
- planSql(options, fromHash) {
45
+ planSql(options) {
46
46
  const schemaName = options.schemaName ?? this.config.defaultSchema;
47
47
  const policyResult = this.ensureAdditivePolicy(options.policy);
48
48
  if (policyResult) return policyResult;
@@ -52,7 +52,7 @@ var PostgresMigrationPlanner = class {
52
52
  const result = planIssues({
53
53
  issues: schemaIssues,
54
54
  toContract: options.contract,
55
- fromContract: options.fromContract ?? null,
55
+ fromContract: options.fromContract,
56
56
  schemaName,
57
57
  codecHooks,
58
58
  storageTypes,
@@ -65,7 +65,7 @@ var PostgresMigrationPlanner = class {
65
65
  return Object.freeze({
66
66
  kind: "success",
67
67
  plan: new TypeScriptRenderablePostgresMigration(result.value.calls, {
68
- from: fromHash,
68
+ from: options.fromContract?.storage.storageHash ?? null,
69
69
  to: options.contract.storage.storageHash
70
70
  })
71
71
  });
@@ -95,4 +95,4 @@ var PostgresMigrationPlanner = class {
95
95
 
96
96
  //#endregion
97
97
  export { createPostgresMigrationPlanner as t };
98
- //# sourceMappingURL=planner-BGMG70Ns.mjs.map
98
+ //# sourceMappingURL=planner-B4ZSLHRI.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"planner-B4ZSLHRI.mjs","names":["DEFAULT_PLANNER_CONFIG: PlannerConfig","config: PlannerConfig"],"sources":["../src/core/migrations/planner.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type {\n MigrationOperationPolicy,\n SqlMigrationPlannerPlanOptions,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport { extractCodecControlHooks, plannerFailure } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport { planIssues } from './issue-planner';\nimport { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';\nimport { postgresPlannerStrategies } from './planner-strategies';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0] & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\nconst DEFAULT_PLANNER_CONFIG: PlannerConfig = {\n defaultSchema: 'public',\n};\n\nexport function createPostgresMigrationPlanner(\n config: Partial<PlannerConfig> = {},\n): PostgresMigrationPlanner {\n return new PostgresMigrationPlanner({\n ...DEFAULT_PLANNER_CONFIG,\n ...config,\n });\n}\n\n/**\n * Result of `PostgresMigrationPlanner.plan()`. A discriminated union whose\n * success variant carries a `TypeScriptRenderablePostgresMigration` — a\n * migration object that both the CLI (via `renderTypeScript()`) and the\n * SQL-typed callers (via `operations`, `describe()`, etc.) consume\n * uniformly.\n */\nexport type PostgresPlanResult =\n | { readonly kind: 'success'; readonly plan: TypeScriptRenderablePostgresMigration }\n | SqlPlannerFailureResult;\n\n/**\n * Postgres migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the unified\n * `postgresPlannerStrategies` list: enum-change, NOT-NULL backfill,\n * type-change, nullable-tightening, codec-hook storage types,\n * component-declared dependency installs, and shared-temp-default /\n * empty-table-guarded NOT-NULL add-column. The same strategy list runs for\n * `migration plan`, `db update`, and `db init`; behavior diverges purely on\n * `policy.allowedOperationClasses` (the data-safe strategies short-circuit\n * when `'data'` is excluded). The issue planner applies operation-class\n * policy gates and emits a single `PostgresOpFactoryCall[]` that drives both\n * the runtime-ops view (via `renderOps`) and the `renderTypeScript()`\n * authoring surface.\n */\nexport class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgres'> {\n constructor(private readonly config: PlannerConfig) {}\n\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n /**\n * The \"from\" contract (state the planner assumes the database starts\n * at), or `null` for reconciliation flows. Only `migration plan` ever\n * supplies a non-null value; `db update` / `db init` reconcile against\n * the live schema and pass `null`. When present alongside the\n * `'data'` operation class, strategies that need from/to column-shape\n * comparisons (unsafe type change, nullability tightening) activate.\n *\n * Typed as the framework `Contract | null` to satisfy the\n * `MigrationPlanner` interface contract; `planSql` narrows to the SQL\n * shape via `SqlMigrationPlannerPlanOptions`. Used to populate\n * `describe().from` on the produced plan as\n * `fromContract?.storage.storageHash ?? null`.\n */\n readonly fromContract: Contract | null;\n readonly schemaName?: string;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n }): PostgresPlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions);\n }\n\n emptyMigration(context: MigrationScaffoldContext): MigrationPlanWithAuthoringSurface {\n return new TypeScriptRenderablePostgresMigration([], {\n from: context.fromHash,\n to: context.toHash,\n });\n }\n\n private planSql(options: SqlMigrationPlannerPlanOptions): PostgresPlanResult {\n const schemaName = options.schemaName ?? this.config.defaultSchema;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n const schemaIssues = this.collectSchemaIssues(options);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n\n const result = planIssues({\n issues: schemaIssues,\n toContract: options.contract,\n // `fromContract` is only supplied by `migration plan`. It is `null` for\n // `db update` / `db init`, which means data-safety strategies needing\n // from/to comparisons (unsafe type change, nullable tightening) are\n // inapplicable there — reconciliation falls through to\n // `mapIssueToCall`'s direct destructive handlers.\n fromContract: options.fromContract,\n schemaName,\n codecHooks,\n storageTypes,\n schema: options.schema,\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: postgresPlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n return Object.freeze({\n kind: 'success' as const,\n plan: new TypeScriptRenderablePostgresMigration(result.value.calls, {\n from: options.fromContract?.storage.storageHash ?? null,\n to: options.contract.storage.storageHash,\n }),\n });\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n private collectSchemaIssues(options: PlannerOptionsWithComponents): readonly SchemaIssue[] {\n // `db init` uses additive-only policy and intentionally ignores extra\n // schema objects. Any reconciliation-capable policy (widening or\n // destructive) must inspect extras to reconcile strict equality.\n const allowed = options.policy.allowedOperationClasses;\n const strict = allowed.includes('widening') || allowed.includes('destructive');\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n return verifyResult.schema.issues;\n }\n}\n"],"mappings":";;;;;;;;AAuCA,MAAMA,yBAAwC,EAC5C,eAAe,UAChB;AAED,SAAgB,+BACd,SAAiC,EAAE,EACT;AAC1B,QAAO,IAAI,yBAAyB;EAClC,GAAG;EACH,GAAG;EACJ,CAAC;;;;;;;;;;;;;;;;;;AA8BJ,IAAa,2BAAb,MAAqF;CACnF,YAAY,AAAiBC,QAAuB;EAAvB;;CAE7B,KAAK,SAqBkB;AACrB,SAAO,KAAK,QAAQ,QAA0C;;CAGhE,eAAe,SAAsE;AACnF,SAAO,IAAI,sCAAsC,EAAE,EAAE;GACnD,MAAM,QAAQ;GACd,IAAI,QAAQ;GACb,CAAC;;CAGJ,AAAQ,QAAQ,SAA6D;EAC3E,MAAM,aAAa,QAAQ,cAAc,KAAK,OAAO;EACrD,MAAM,eAAe,KAAK,qBAAqB,QAAQ,OAAO;AAC9D,MAAI,aACF,QAAO;EAGT,MAAM,eAAe,KAAK,oBAAoB,QAAQ;EACtD,MAAM,aAAa,yBAAyB,QAAQ,oBAAoB;EACxE,MAAM,eAAe,QAAQ,SAAS,QAAQ,SAAS,EAAE;EAEzD,MAAM,SAAS,WAAW;GACxB,QAAQ;GACR,YAAY,QAAQ;GAMpB,cAAc,QAAQ;GACtB;GACA;GACA;GACA,QAAQ,QAAQ;GAChB,QAAQ,QAAQ;GAChB,qBAAqB,QAAQ;GAC7B,YAAY;GACb,CAAC;AAEF,MAAI,CAAC,OAAO,GACV,QAAO,eAAe,OAAO,QAAQ;AAGvC,SAAO,OAAO,OAAO;GACnB,MAAM;GACN,MAAM,IAAI,sCAAsC,OAAO,MAAM,OAAO;IAClE,MAAM,QAAQ,cAAc,QAAQ,eAAe;IACnD,IAAI,QAAQ,SAAS,QAAQ;IAC9B,CAAC;GACH,CAAC;;CAGJ,AAAQ,qBAAqB,QAAkC;AAC7D,MAAI,CAAC,OAAO,wBAAwB,SAAS,WAAW,CACtD,QAAO,eAAe,CACpB;GACE,MAAM;GACN,SAAS;GACT,KAAK;GACN,CACF,CAAC;AAEJ,SAAO;;CAGT,AAAQ,oBAAoB,SAA+D;EAIzF,MAAM,UAAU,QAAQ,OAAO;EAC/B,MAAM,SAAS,QAAQ,SAAS,WAAW,IAAI,QAAQ,SAAS,cAAc;AAW9E,SADqB,gBATuC;GAC1D,UAAU,QAAQ;GAClB,QAAQ,QAAQ;GAChB;GACA,sCAAsB,IAAI,KAAK;GAC/B,qBAAqB,QAAQ;GAC7B,kBAAkB;GAClB,qBAAqB;GACtB,CACkD,CAC/B,OAAO"}
@@ -3,6 +3,7 @@ import "./op-factory-call-C3bWXKSP.mjs";
3
3
  import "./postgres-migration-DcfWGqhe.mjs";
4
4
  import { t as TypeScriptRenderablePostgresMigration } from "./planner-produced-postgres-migration-Dw_mPMKt.mjs";
5
5
  import { MigrationOperationPolicy, SqlPlannerFailureResult } from "@prisma-next/family-sql/control";
6
+ import { Contract } from "@prisma-next/contract/types";
6
7
  import { MigrationPlanWithAuthoringSurface, MigrationPlanner, MigrationScaffoldContext } from "@prisma-next/framework-components/control";
7
8
  import { TargetBoundComponentDescriptor } from "@prisma-next/framework-components/components";
8
9
 
@@ -45,16 +46,21 @@ declare class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postg
45
46
  readonly contract: unknown;
46
47
  readonly schema: unknown;
47
48
  readonly policy: MigrationOperationPolicy;
48
- readonly fromHash?: string | null;
49
49
  /**
50
50
  * The "from" contract (state the planner assumes the database starts
51
- * at). Only `migration plan` supplies this; `db update` / `db init`
52
- * reconcile against the live schema with no old contract. When present
53
- * alongside the `'data'` operation class, strategies that need from/to
54
- * column shape comparisons (unsafe type change, nullability tightening)
55
- * activate.
51
+ * at), or `null` for reconciliation flows. Only `migration plan` ever
52
+ * supplies a non-null value; `db update` / `db init` reconcile against
53
+ * the live schema and pass `null`. When present alongside the
54
+ * `'data'` operation class, strategies that need from/to column-shape
55
+ * comparisons (unsafe type change, nullability tightening) activate.
56
+ *
57
+ * Typed as the framework `Contract | null` to satisfy the
58
+ * `MigrationPlanner` interface contract; `planSql` narrows to the SQL
59
+ * shape via `SqlMigrationPlannerPlanOptions`. Used to populate
60
+ * `describe().from` on the produced plan as
61
+ * `fromContract?.storage.storageHash ?? null`.
56
62
  */
57
- readonly fromContract?: unknown;
63
+ readonly fromContract: Contract | null;
58
64
  readonly schemaName?: string;
59
65
  readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
60
66
  }): PostgresPlanResult;
@@ -1 +1 @@
1
- {"version":3,"file":"planner.d.mts","names":[],"sources":["../src/core/migrations/planner.ts"],"sourcesContent":[],"mappings":";;;;;;;;;UAkCU,aAAA;;;iBAQM,8BAAA,UACN,QAAQ,iBACf;;AA3B2F;AAyB9F;;;;;AAgBY,KAAA,kBAAA,GAAkB;EAoBjB,SAAA,IAAA,EAAA,SAAA;EAC0B,SAAA,IAAA,EApBQ,qCAoBR;CAKlB,GAxBjB,uBAwBiB;;;;;;;;;;;;;;;;;cANR,wBAAA,YAAoC;;sBACV;;;;qBAKlB;;;;;;;;;;;;kCAYa,cAAc;MAC1C;0BAIoB,2BAA2B"}
1
+ {"version":3,"file":"planner.d.mts","names":[],"sources":["../src/core/migrations/planner.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;UAmCU,aAAA;;;iBAQM,8BAAA,UACN,QAAQ,iBACf;;AA3B2F;AAyB9F;;;;;AAgBY,KAAA,kBAAA,GAAkB;EAoBjB,SAAA,IAAA,EAAA,SAAA;EAC0B,SAAA,IAAA,EApBQ,qCAoBR;CAKlB,GAxBjB,uBAwBiB;;;;;;;;;;;;;;;;;cANR,wBAAA,YAAoC;;sBACV;;;;qBAKlB;;;;;;;;;;;;;;;2BAeM;;kCAEO,cAAc;MAC1C;0BAIoB,2BAA2B"}
package/dist/planner.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  import "./issue-planner-CFjB0_oO.mjs";
2
- import { t as createPostgresMigrationPlanner } from "./planner-BGMG70Ns.mjs";
2
+ import { t as createPostgresMigrationPlanner } from "./planner-B4ZSLHRI.mjs";
3
3
 
4
4
  export { createPostgresMigrationPlanner };
package/package.json CHANGED
@@ -1,25 +1,25 @@
1
1
  {
2
2
  "name": "@prisma-next/target-postgres",
3
- "version": "0.5.0-dev.30",
3
+ "version": "0.5.0-dev.41",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "description": "Postgres target pack for Prisma Next",
7
7
  "dependencies": {
8
8
  "arktype": "^2.0.0",
9
9
  "pathe": "^2.0.3",
10
- "@prisma-next/cli": "0.5.0-dev.30",
11
- "@prisma-next/errors": "0.5.0-dev.30",
12
- "@prisma-next/migration-tools": "0.5.0-dev.30",
13
- "@prisma-next/family-sql": "0.5.0-dev.30",
14
- "@prisma-next/framework-components": "0.5.0-dev.30",
15
- "@prisma-next/contract": "0.5.0-dev.30",
16
- "@prisma-next/ts-render": "0.5.0-dev.30",
17
- "@prisma-next/sql-operations": "0.5.0-dev.30",
18
- "@prisma-next/sql-contract": "0.5.0-dev.30",
19
- "@prisma-next/sql-errors": "0.5.0-dev.30",
20
- "@prisma-next/sql-relational-core": "0.5.0-dev.30",
21
- "@prisma-next/sql-schema-ir": "0.5.0-dev.30",
22
- "@prisma-next/utils": "0.5.0-dev.30"
10
+ "@prisma-next/cli": "0.5.0-dev.41",
11
+ "@prisma-next/contract": "0.5.0-dev.41",
12
+ "@prisma-next/family-sql": "0.5.0-dev.41",
13
+ "@prisma-next/framework-components": "0.5.0-dev.41",
14
+ "@prisma-next/errors": "0.5.0-dev.41",
15
+ "@prisma-next/migration-tools": "0.5.0-dev.41",
16
+ "@prisma-next/ts-render": "0.5.0-dev.41",
17
+ "@prisma-next/sql-operations": "0.5.0-dev.41",
18
+ "@prisma-next/sql-contract": "0.5.0-dev.41",
19
+ "@prisma-next/sql-relational-core": "0.5.0-dev.41",
20
+ "@prisma-next/sql-schema-ir": "0.5.0-dev.41",
21
+ "@prisma-next/sql-errors": "0.5.0-dev.41",
22
+ "@prisma-next/utils": "0.5.0-dev.41"
23
23
  },
24
24
  "devDependencies": {
25
25
  "tsdown": "0.18.4",
@@ -40,7 +40,6 @@ import {
40
40
  PG_VARBIT_CODEC_ID,
41
41
  PG_VARCHAR_CODEC_ID,
42
42
  } from './codec-ids';
43
- import { renderTypeScriptTypeFromJsonSchema } from './json-schema-type-expression';
44
43
 
45
44
  const lengthParamsSchema = arktype({
46
45
  length: 'number.integer > 0',
@@ -85,19 +84,13 @@ function renderPrecision(typeName: string, typeParams: Record<string, unknown>):
85
84
  return `${typeName}<${precision}>`;
86
85
  }
87
86
 
88
- function renderJsonOutputType(typeParams: Record<string, unknown>): string {
89
- const typeName = typeParams['type'];
90
- if (typeof typeName === 'string' && typeName.trim().length > 0) {
91
- return typeName.trim();
92
- }
93
- const schema = typeParams['schemaJson'];
94
- if (schema && typeof schema === 'object') {
95
- return renderTypeScriptTypeFromJsonSchema(schema);
96
- }
97
- throw new Error(
98
- `renderOutputType: JSON codec typeParams must contain "type" (string) or "schemaJson" (object), got keys: ${Object.keys(typeParams).join(', ')}`,
99
- );
100
- }
87
+ // Phase C: postgres' raw json/jsonb codecs no longer carry a
88
+ // `renderOutputType` slot — the schema-typed JSON surface that drove
89
+ // `typeParams: { schemaJson, type? }` retired in favor of the per-library
90
+ // extension package (`@prisma-next/extension-arktype-json`). Untyped
91
+ // json/jsonb columns have no typeParams; the framework emit path falls
92
+ // through to the generic `CodecTypes['pg/jsonb@1']['output']` accessor
93
+ // (which resolves to `JsonValue` via the codec-types map).
101
94
 
102
95
  function aliasCodec<
103
96
  Id extends string,
@@ -562,7 +555,6 @@ const pgJsonCodec = codec({
562
555
  encode: (value: string | JsonValue): string => JSON.stringify(value),
563
556
  decode: (wire: string | JsonValue): JsonValue =>
564
557
  typeof wire === 'string' ? JSON.parse(wire) : wire,
565
- renderOutputType: renderJsonOutputType,
566
558
  meta: {
567
559
  db: {
568
560
  sql: {
@@ -581,7 +573,6 @@ const pgJsonbCodec = codec({
581
573
  encode: (value: string | JsonValue): string => JSON.stringify(value),
582
574
  decode: (wire: string | JsonValue): JsonValue =>
583
575
  typeof wire === 'string' ? JSON.parse(wire) : wire,
584
- renderOutputType: renderJsonOutputType,
585
576
  meta: {
586
577
  db: {
587
578
  sql: {
@@ -1,3 +1,4 @@
1
+ import type { Contract } from '@prisma-next/contract/types';
1
2
  import type {
2
3
  MigrationOperationPolicy,
3
4
  SqlMigrationPlannerPlanOptions,
@@ -83,20 +84,25 @@ export class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgr
83
84
  readonly contract: unknown;
84
85
  readonly schema: unknown;
85
86
  readonly policy: MigrationOperationPolicy;
86
- readonly fromHash?: string | null;
87
87
  /**
88
88
  * The "from" contract (state the planner assumes the database starts
89
- * at). Only `migration plan` supplies this; `db update` / `db init`
90
- * reconcile against the live schema with no old contract. When present
91
- * alongside the `'data'` operation class, strategies that need from/to
92
- * column shape comparisons (unsafe type change, nullability tightening)
93
- * activate.
89
+ * at), or `null` for reconciliation flows. Only `migration plan` ever
90
+ * supplies a non-null value; `db update` / `db init` reconcile against
91
+ * the live schema and pass `null`. When present alongside the
92
+ * `'data'` operation class, strategies that need from/to column-shape
93
+ * comparisons (unsafe type change, nullability tightening) activate.
94
+ *
95
+ * Typed as the framework `Contract | null` to satisfy the
96
+ * `MigrationPlanner` interface contract; `planSql` narrows to the SQL
97
+ * shape via `SqlMigrationPlannerPlanOptions`. Used to populate
98
+ * `describe().from` on the produced plan as
99
+ * `fromContract?.storage.storageHash ?? null`.
94
100
  */
95
- readonly fromContract?: unknown;
101
+ readonly fromContract: Contract | null;
96
102
  readonly schemaName?: string;
97
103
  readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;
98
104
  }): PostgresPlanResult {
99
- return this.planSql(options as SqlMigrationPlannerPlanOptions, options.fromHash ?? null);
105
+ return this.planSql(options as SqlMigrationPlannerPlanOptions);
100
106
  }
101
107
 
102
108
  emptyMigration(context: MigrationScaffoldContext): MigrationPlanWithAuthoringSurface {
@@ -106,10 +112,7 @@ export class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgr
106
112
  });
107
113
  }
108
114
 
109
- private planSql(
110
- options: SqlMigrationPlannerPlanOptions,
111
- fromHash: string | null,
112
- ): PostgresPlanResult {
115
+ private planSql(options: SqlMigrationPlannerPlanOptions): PostgresPlanResult {
113
116
  const schemaName = options.schemaName ?? this.config.defaultSchema;
114
117
  const policyResult = this.ensureAdditivePolicy(options.policy);
115
118
  if (policyResult) {
@@ -128,7 +131,7 @@ export class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgr
128
131
  // from/to comparisons (unsafe type change, nullable tightening) are
129
132
  // inapplicable there — reconciliation falls through to
130
133
  // `mapIssueToCall`'s direct destructive handlers.
131
- fromContract: options.fromContract ?? null,
134
+ fromContract: options.fromContract,
132
135
  schemaName,
133
136
  codecHooks,
134
137
  storageTypes,
@@ -145,7 +148,7 @@ export class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgr
145
148
  return Object.freeze({
146
149
  kind: 'success' as const,
147
150
  plan: new TypeScriptRenderablePostgresMigration(result.value.calls, {
148
- from: fromHash,
151
+ from: options.fromContract?.storage.storageHash ?? null,
149
152
  to: options.contract.storage.storageHash,
150
153
  }),
151
154
  });
@@ -127,9 +127,14 @@ class PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDe
127
127
  return markerCheck;
128
128
  }
129
129
 
130
- // db update (origin: null) always applies; migration-apply (origin set) skips if marker matches.
130
+ // db update (origin: null) always applies; migration-apply (origin set,
131
+ // origin !== destination) skips if marker already matches destination.
132
+ // Self-edges (origin === destination) intentionally bypass the skip:
133
+ // the migration is data-only, and the data transform's own check
134
+ // decides whether `run` fires.
131
135
  const markerAtDestination = this.markerMatchesDestination(existingMarker, options.plan);
132
- const skipOperations = markerAtDestination && options.plan.origin != null;
136
+ const isSelfEdge = options.plan.origin?.storageHash === options.plan.destination.storageHash;
137
+ const skipOperations = markerAtDestination && options.plan.origin != null && !isSelfEdge;
133
138
  let applyValue: ApplyPlanSuccessValue;
134
139
 
135
140
  if (skipOperations) {
@@ -169,9 +174,39 @@ class PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDe
169
174
  });
170
175
  }
171
176
 
172
- // Record marker and ledger entries
173
- await this.upsertMarker(driver, options, existingMarker);
174
- await this.recordLedgerEntry(driver, options, existingMarker, applyValue.executedOperations);
177
+ // Self-edge no-op detection: a self-edge migration with zero ops in
178
+ // the plan that brings no new invariants produced no observable
179
+ // change. Skip the marker + ledger writes so an idempotent re-apply
180
+ // of a self-edge data transform doesn't churn updatedAt or pile up
181
+ // empty ledger entries. db update no-ops still write a ledger entry
182
+ // as audit trail.
183
+ //
184
+ // TODO(invariant-routing follow-up): `executeDataTransform` always
185
+ // counts every op it visits (including self-skips via `check === true`
186
+ // or empty idempotency probe), so `operationsExecuted === 0` here
187
+ // means "the plan had zero ops" rather than "every op self-skipped".
188
+ // The CLI is unaffected today because `migration-apply.ts` marker-
189
+ // subtraction empties `effectiveRequired` first and short-circuits
190
+ // before we run; the non-CLI re-apply path needs a per-op `executed`
191
+ // flag threaded through `executeDataTransform` to recover the
192
+ // intended check. See review thread A13 / future M5 ADR draft.
193
+ const incomingInvariants = options.plan.providedInvariants;
194
+ const existingInvariants = new Set(existingMarker?.invariants ?? []);
195
+ const incomingIsSubsetOfExisting = incomingInvariants.every((id) =>
196
+ existingInvariants.has(id),
197
+ );
198
+ const isSelfEdgeNoOp =
199
+ isSelfEdge && applyValue.operationsExecuted === 0 && incomingIsSubsetOfExisting;
200
+
201
+ if (!isSelfEdgeNoOp) {
202
+ await this.upsertMarker(driver, options, existingMarker);
203
+ await this.recordLedgerEntry(
204
+ driver,
205
+ options,
206
+ existingMarker,
207
+ applyValue.executedOperations,
208
+ );
209
+ }
175
210
 
176
211
  await this.commitTransaction(driver);
177
212
  committed = true;
@@ -616,9 +651,7 @@ class PostgresMigrationRunner implements SqlMigrationRunner<PostgresPlanTargetDe
616
651
  options: SqlMigrationRunnerExecuteOptions<PostgresPlanTargetDetails>,
617
652
  existingMarker: ContractMarkerRecord | null,
618
653
  ): Promise<void> {
619
- // Sort + dedupe so the INSERT path writes a stable initial value.
620
- // UPDATE merges server-side, so no client-side union is needed.
621
- const incomingInvariants = Array.from(new Set(options.invariants ?? [])).sort();
654
+ const incomingInvariants = options.plan.providedInvariants;
622
655
  const writeStatements = buildMergeMarkerStatements({
623
656
  storageHash: options.plan.destination.storageHash,
624
657
  profileHash:
@@ -1 +0,0 @@
1
- {"version":3,"file":"codecs-OkTYeJQb.mjs","names":["arktype"],"sources":["../src/core/json-schema-type-expression.ts","../src/core/codecs.ts"],"sourcesContent":["type JsonSchemaRecord = Record<string, unknown>;\n\nconst MAX_DEPTH = 32;\n\nfunction isRecord(value: unknown): value is JsonSchemaRecord {\n return typeof value === 'object' && value !== null;\n}\n\nfunction escapeStringLiteral(str: string): string {\n return str\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r');\n}\n\nfunction quotePropertyKey(key: string): string {\n return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : `'${escapeStringLiteral(key)}'`;\n}\n\nfunction renderLiteral(value: unknown): string {\n if (typeof value === 'string') {\n return `'${escapeStringLiteral(value)}'`;\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (value === null) {\n return 'null';\n }\n return 'unknown';\n}\n\nfunction renderUnion(items: readonly unknown[], depth: number): string {\n const rendered = items.map((item) => render(item, depth));\n return rendered.join(' | ');\n}\n\nfunction renderObjectType(schema: JsonSchemaRecord, depth: number): string {\n const properties = isRecord(schema['properties']) ? schema['properties'] : {};\n const required = Array.isArray(schema['required'])\n ? new Set(schema['required'].filter((key): key is string => typeof key === 'string'))\n : new Set<string>();\n const keys = Object.keys(properties).sort((left, right) => left.localeCompare(right));\n\n if (keys.length === 0) {\n const additionalProperties = schema['additionalProperties'];\n if (additionalProperties === true || additionalProperties === undefined) {\n return 'Record<string, unknown>';\n }\n return `Record<string, ${render(additionalProperties, depth)}>`;\n }\n\n const renderedProperties = keys.map((key) => {\n const valueSchema = (properties as JsonSchemaRecord)[key];\n const optionalMarker = required.has(key) ? '' : '?';\n return `${quotePropertyKey(key)}${optionalMarker}: ${render(valueSchema, depth)}`;\n });\n\n return `{ ${renderedProperties.join('; ')} }`;\n}\n\nfunction renderArrayType(schema: JsonSchemaRecord, depth: number): string {\n if (Array.isArray(schema['items'])) {\n return `readonly [${schema['items'].map((item) => render(item, depth)).join(', ')}]`;\n }\n\n if (schema['items'] !== undefined) {\n const itemType = render(schema['items'], depth);\n const needsParens = itemType.includes(' | ') || itemType.includes(' & ');\n return needsParens ? `(${itemType})[]` : `${itemType}[]`;\n }\n\n return 'unknown[]';\n}\n\nfunction render(schema: unknown, depth: number): string {\n if (depth > MAX_DEPTH || !isRecord(schema)) {\n return 'JsonValue';\n }\n\n const nextDepth = depth + 1;\n\n if ('const' in schema) {\n return renderLiteral(schema['const']);\n }\n\n if (Array.isArray(schema['enum'])) {\n return schema['enum'].map((value) => renderLiteral(value)).join(' | ');\n }\n\n if (Array.isArray(schema['oneOf'])) {\n return renderUnion(schema['oneOf'], nextDepth);\n }\n\n if (Array.isArray(schema['anyOf'])) {\n return renderUnion(schema['anyOf'], nextDepth);\n }\n\n if (Array.isArray(schema['allOf'])) {\n return schema['allOf'].map((item) => render(item, nextDepth)).join(' & ');\n }\n\n if (Array.isArray(schema['type'])) {\n return schema['type'].map((item) => render({ ...schema, type: item }, nextDepth)).join(' | ');\n }\n\n switch (schema['type']) {\n case 'string':\n return 'string';\n case 'number':\n case 'integer':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'null':\n return 'null';\n case 'array':\n return renderArrayType(schema, nextDepth);\n case 'object':\n return renderObjectType(schema, nextDepth);\n default:\n break;\n }\n\n return 'JsonValue';\n}\n\nexport function renderTypeScriptTypeFromJsonSchema(schema: unknown): string {\n return render(schema, 0);\n}\n","/**\n * Unified codec definitions for Postgres adapter.\n *\n * This file contains a single source of truth for all codec information:\n * - Scalar names\n * - Type IDs\n * - Codec implementations (runtime)\n * - Type information (compile-time)\n *\n * This structure is used both at runtime (to populate the registry) and\n * at compile time (to derive CodecTypes).\n */\n\nimport type { JsonValue } from '@prisma-next/contract/types';\nimport type { Codec, CodecMeta, CodecTrait } from '@prisma-next/sql-relational-core/ast';\nimport { codec, defineCodecs, sqlCodecDefinitions } from '@prisma-next/sql-relational-core/ast';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { type as arktype } from 'arktype';\nimport {\n PG_BIT_CODEC_ID,\n PG_BOOL_CODEC_ID,\n PG_CHAR_CODEC_ID,\n PG_ENUM_CODEC_ID,\n PG_FLOAT_CODEC_ID,\n PG_FLOAT4_CODEC_ID,\n PG_FLOAT8_CODEC_ID,\n PG_INT_CODEC_ID,\n PG_INT2_CODEC_ID,\n PG_INT4_CODEC_ID,\n PG_INT8_CODEC_ID,\n PG_INTERVAL_CODEC_ID,\n PG_JSON_CODEC_ID,\n PG_JSONB_CODEC_ID,\n PG_NUMERIC_CODEC_ID,\n PG_TEXT_CODEC_ID,\n PG_TIME_CODEC_ID,\n PG_TIMESTAMP_CODEC_ID,\n PG_TIMESTAMPTZ_CODEC_ID,\n PG_TIMETZ_CODEC_ID,\n PG_VARBIT_CODEC_ID,\n PG_VARCHAR_CODEC_ID,\n} from './codec-ids';\nimport { renderTypeScriptTypeFromJsonSchema } from './json-schema-type-expression';\n\nconst lengthParamsSchema = arktype({\n length: 'number.integer > 0',\n});\n\nconst numericParamsSchema = arktype({\n precision: 'number.integer > 0 & number.integer <= 1000',\n 'scale?': 'number.integer >= 0',\n});\n\nconst precisionParamsSchema = arktype({\n 'precision?': 'number.integer >= 0 & number.integer <= 6',\n});\n\nfunction renderLength(typeName: string, typeParams: Record<string, unknown>): string | undefined {\n const length = typeParams['length'];\n if (length === undefined) {\n return undefined;\n }\n if (typeof length !== 'number' || !Number.isFinite(length) || !Number.isInteger(length)) {\n throw new Error(\n `renderOutputType: expected integer \"length\" in typeParams for ${typeName}, got ${String(length)}`,\n );\n }\n return `${typeName}<${length}>`;\n}\n\nfunction renderPrecision(typeName: string, typeParams: Record<string, unknown>): string {\n const precision = typeParams['precision'];\n if (precision === undefined) {\n return typeName;\n }\n if (\n typeof precision !== 'number' ||\n !Number.isFinite(precision) ||\n !Number.isInteger(precision)\n ) {\n throw new Error(\n `renderOutputType: expected integer \"precision\" in typeParams for ${typeName}, got ${String(precision)}`,\n );\n }\n return `${typeName}<${precision}>`;\n}\n\nfunction renderJsonOutputType(typeParams: Record<string, unknown>): string {\n const typeName = typeParams['type'];\n if (typeof typeName === 'string' && typeName.trim().length > 0) {\n return typeName.trim();\n }\n const schema = typeParams['schemaJson'];\n if (schema && typeof schema === 'object') {\n return renderTypeScriptTypeFromJsonSchema(schema);\n }\n throw new Error(\n `renderOutputType: JSON codec typeParams must contain \"type\" (string) or \"schemaJson\" (object), got keys: ${Object.keys(typeParams).join(', ')}`,\n );\n}\n\nfunction aliasCodec<\n Id extends string,\n TTraits extends readonly CodecTrait[],\n TWire,\n TJs,\n TParams,\n THelper,\n>(\n base: Codec<string, TTraits, TWire, TJs, TParams, THelper>,\n options: {\n readonly typeId: Id;\n readonly targetTypes: readonly string[];\n readonly meta?: CodecMeta;\n },\n): Codec<Id, TTraits, TWire, TJs, TParams, THelper> {\n return {\n id: options.typeId,\n targetTypes: options.targetTypes,\n ...ifDefined('meta', options.meta),\n ...ifDefined('paramsSchema', base.paramsSchema),\n ...ifDefined('init', base.init),\n ...ifDefined('encode', base.encode),\n ...ifDefined('traits', base.traits),\n ...ifDefined('renderOutputType', base.renderOutputType),\n decode: base.decode,\n encodeJson: base.encodeJson,\n decodeJson: base.decodeJson,\n } as Codec<Id, TTraits, TWire, TJs, TParams, THelper>;\n}\n\nconst sqlCharCodec = sqlCodecDefinitions.char.codec;\nconst sqlVarcharCodec = sqlCodecDefinitions.varchar.codec;\nconst sqlIntCodec = sqlCodecDefinitions.int.codec;\nconst sqlFloatCodec = sqlCodecDefinitions.float.codec;\nconst sqlTextCodec = sqlCodecDefinitions.text.codec;\nconst sqlTimestampCodec = sqlCodecDefinitions.timestamp.codec;\n\n// Create individual codec instances\nconst pgTextCodec = codec({\n typeId: PG_TEXT_CODEC_ID,\n targetTypes: ['text'],\n traits: ['equality', 'order', 'textual'],\n encode: (value: string): string => value,\n decode: (wire: string): string => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'text',\n },\n },\n },\n },\n});\n\nconst pgCharCodec = aliasCodec(sqlCharCodec, {\n typeId: PG_CHAR_CODEC_ID,\n targetTypes: ['character'],\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'character',\n },\n },\n },\n },\n});\n\nconst pgVarcharCodec = aliasCodec(sqlVarcharCodec, {\n typeId: PG_VARCHAR_CODEC_ID,\n targetTypes: ['character varying'],\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'character varying',\n },\n },\n },\n },\n});\n\nconst pgIntCodec = aliasCodec(sqlIntCodec, {\n typeId: PG_INT_CODEC_ID,\n targetTypes: ['int4'],\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'integer',\n },\n },\n },\n },\n});\n\nconst pgFloatCodec = aliasCodec(sqlFloatCodec, {\n typeId: PG_FLOAT_CODEC_ID,\n targetTypes: ['float8'],\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'double precision',\n },\n },\n },\n },\n});\n\nconst pgInt4Codec = codec({\n typeId: PG_INT4_CODEC_ID,\n targetTypes: ['int4'],\n traits: ['equality', 'order', 'numeric'],\n encode: (value: number): number => value,\n decode: (wire: number): number => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'integer',\n },\n },\n },\n },\n});\n\nconst pgNumericCodec = codec<\n typeof PG_NUMERIC_CODEC_ID,\n readonly ['equality', 'order', 'numeric'],\n string,\n string\n>({\n typeId: PG_NUMERIC_CODEC_ID,\n targetTypes: ['numeric', 'decimal'],\n traits: ['equality', 'order', 'numeric'],\n encode: (value: string): string => value,\n decode: (wire: string | number): string => {\n if (typeof wire === 'number') return String(wire);\n return wire;\n },\n paramsSchema: numericParamsSchema,\n renderOutputType: (typeParams) => {\n const precision = typeParams['precision'];\n if (precision === undefined) return undefined;\n if (\n typeof precision !== 'number' ||\n !Number.isFinite(precision) ||\n !Number.isInteger(precision)\n ) {\n throw new Error(\n `renderOutputType: expected integer \"precision\" in typeParams for Numeric, got ${String(precision)}`,\n );\n }\n const scale = typeParams['scale'];\n return typeof scale === 'number' ? `Numeric<${precision}, ${scale}>` : `Numeric<${precision}>`;\n },\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'numeric',\n },\n },\n },\n },\n});\n\nconst pgInt2Codec = codec({\n typeId: PG_INT2_CODEC_ID,\n targetTypes: ['int2'],\n traits: ['equality', 'order', 'numeric'],\n encode: (value: number): number => value,\n decode: (wire: number): number => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'smallint',\n },\n },\n },\n },\n});\n\nconst pgInt8Codec = codec({\n typeId: PG_INT8_CODEC_ID,\n targetTypes: ['int8'],\n traits: ['equality', 'order', 'numeric'],\n encode: (value: number): number => value,\n decode: (wire: number): number => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'bigint',\n },\n },\n },\n },\n});\n\nconst pgFloat4Codec = codec({\n typeId: PG_FLOAT4_CODEC_ID,\n targetTypes: ['float4'],\n traits: ['equality', 'order', 'numeric'],\n encode: (value: number): number => value,\n decode: (wire: number): number => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'real',\n },\n },\n },\n },\n});\n\nconst pgFloat8Codec = codec({\n typeId: PG_FLOAT8_CODEC_ID,\n targetTypes: ['float8'],\n traits: ['equality', 'order', 'numeric'],\n encode: (value: number): number => value,\n decode: (wire: number): number => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'double precision',\n },\n },\n },\n },\n});\n\nconst pgTimestampCodec = codec<\n typeof PG_TIMESTAMP_CODEC_ID,\n readonly ['equality', 'order'],\n Date,\n Date\n>({\n typeId: PG_TIMESTAMP_CODEC_ID,\n targetTypes: ['timestamp'],\n traits: ['equality', 'order'],\n encode: (value: Date): Date => value,\n decode: (wire: Date): Date => wire,\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') {\n throw new Error(`Expected ISO date string for pg/timestamp@1, got ${typeof json}`);\n }\n const date = new Date(json);\n if (Number.isNaN(date.getTime())) {\n throw new Error(`Invalid ISO date string for pg/timestamp@1: ${json}`);\n }\n return date;\n },\n paramsSchema: precisionParamsSchema,\n renderOutputType: (typeParams) => renderPrecision('Timestamp', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'timestamp without time zone',\n },\n },\n },\n },\n});\n\nconst pgTimestamptzCodec = codec<\n typeof PG_TIMESTAMPTZ_CODEC_ID,\n readonly ['equality', 'order'],\n Date,\n Date\n>({\n typeId: PG_TIMESTAMPTZ_CODEC_ID,\n targetTypes: ['timestamptz'],\n traits: ['equality', 'order'],\n encode: (value: Date): Date => value,\n decode: (wire: Date): Date => wire,\n encodeJson: (value: Date) => value.toISOString(),\n decodeJson: (json) => {\n if (typeof json !== 'string') {\n throw new Error(`Expected ISO date string for pg/timestamptz@1, got ${typeof json}`);\n }\n const date = new Date(json);\n if (Number.isNaN(date.getTime())) {\n throw new Error(`Invalid ISO date string for pg/timestamptz@1: ${json}`);\n }\n return date;\n },\n paramsSchema: precisionParamsSchema,\n renderOutputType: (typeParams) => renderPrecision('Timestamptz', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'timestamp with time zone',\n },\n },\n },\n },\n});\n\nconst pgTimeCodec = codec<typeof PG_TIME_CODEC_ID, readonly ['equality', 'order'], string, string>({\n typeId: PG_TIME_CODEC_ID,\n targetTypes: ['time'],\n traits: ['equality', 'order'],\n encode: (value: string): string => value,\n decode: (wire: string): string => wire,\n paramsSchema: precisionParamsSchema,\n renderOutputType: (typeParams) => renderPrecision('Time', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'time',\n },\n },\n },\n },\n});\n\nconst pgTimetzCodec = codec<\n typeof PG_TIMETZ_CODEC_ID,\n readonly ['equality', 'order'],\n string,\n string\n>({\n typeId: PG_TIMETZ_CODEC_ID,\n targetTypes: ['timetz'],\n traits: ['equality', 'order'],\n encode: (value: string): string => value,\n decode: (wire: string): string => wire,\n paramsSchema: precisionParamsSchema,\n renderOutputType: (typeParams) => renderPrecision('Timetz', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'timetz',\n },\n },\n },\n },\n});\n\nconst pgBoolCodec = codec({\n typeId: PG_BOOL_CODEC_ID,\n targetTypes: ['bool'],\n traits: ['equality', 'boolean'],\n encode: (value: boolean): boolean => value,\n decode: (wire: boolean): boolean => wire,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'boolean',\n },\n },\n },\n },\n});\n\nconst pgBitCodec = codec<typeof PG_BIT_CODEC_ID, readonly ['equality', 'order'], string, string>({\n typeId: PG_BIT_CODEC_ID,\n targetTypes: ['bit'],\n traits: ['equality', 'order'],\n encode: (value: string): string => value,\n decode: (wire: string): string => wire,\n paramsSchema: lengthParamsSchema,\n renderOutputType: (typeParams) => renderLength('Bit', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'bit',\n },\n },\n },\n },\n});\n\nconst pgVarbitCodec = codec<\n typeof PG_VARBIT_CODEC_ID,\n readonly ['equality', 'order'],\n string,\n string\n>({\n typeId: PG_VARBIT_CODEC_ID,\n targetTypes: ['bit varying'],\n traits: ['equality', 'order'],\n encode: (value: string): string => value,\n decode: (wire: string): string => wire,\n paramsSchema: lengthParamsSchema,\n renderOutputType: (typeParams) => renderLength('VarBit', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'bit varying',\n },\n },\n },\n },\n});\n\nconst pgEnumCodec = codec({\n typeId: PG_ENUM_CODEC_ID,\n targetTypes: ['enum'],\n traits: ['equality', 'order'],\n encode: (value: string): string => value,\n decode: (wire: string): string => wire,\n renderOutputType: (typeParams) => {\n const values = typeParams['values'];\n if (!Array.isArray(values)) {\n throw new Error(\n `renderOutputType: expected array \"values\" in typeParams for enum, got ${typeof values}`,\n );\n }\n return values\n .map((value) => `'${String(value).replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`)\n .join(' | ');\n },\n});\n\nconst pgIntervalCodec = codec<\n typeof PG_INTERVAL_CODEC_ID,\n readonly ['equality', 'order'],\n string | Record<string, unknown>,\n string\n>({\n typeId: PG_INTERVAL_CODEC_ID,\n targetTypes: ['interval'],\n traits: ['equality', 'order'],\n encode: (value: string): string => value,\n decode: (wire: string | Record<string, unknown>): string => {\n if (typeof wire === 'string') return wire;\n return JSON.stringify(wire);\n },\n paramsSchema: precisionParamsSchema,\n renderOutputType: (typeParams) => renderPrecision('Interval', typeParams),\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'interval',\n },\n },\n },\n },\n});\n\nconst pgJsonCodec = codec({\n typeId: PG_JSON_CODEC_ID,\n targetTypes: ['json'],\n traits: [],\n encode: (value: string | JsonValue): string => JSON.stringify(value),\n decode: (wire: string | JsonValue): JsonValue =>\n typeof wire === 'string' ? JSON.parse(wire) : wire,\n renderOutputType: renderJsonOutputType,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'json',\n },\n },\n },\n },\n});\n\nconst pgJsonbCodec = codec({\n typeId: PG_JSONB_CODEC_ID,\n targetTypes: ['jsonb'],\n traits: ['equality'],\n encode: (value: string | JsonValue): string => JSON.stringify(value),\n decode: (wire: string | JsonValue): JsonValue =>\n typeof wire === 'string' ? JSON.parse(wire) : wire,\n renderOutputType: renderJsonOutputType,\n meta: {\n db: {\n sql: {\n postgres: {\n nativeType: 'jsonb',\n },\n },\n },\n },\n});\n\n// Build codec definitions using the builder DSL\nconst codecs = defineCodecs()\n .add('char', sqlCharCodec)\n .add('varchar', sqlVarcharCodec)\n .add('int', sqlIntCodec)\n .add('float', sqlFloatCodec)\n .add('sql-text', sqlTextCodec)\n .add('sql-timestamp', sqlTimestampCodec)\n .add('text', pgTextCodec)\n .add('character', pgCharCodec)\n .add('character varying', pgVarcharCodec)\n .add('integer', pgIntCodec)\n .add('double precision', pgFloatCodec)\n .add('int4', pgInt4Codec)\n .add('int2', pgInt2Codec)\n .add('int8', pgInt8Codec)\n .add('float4', pgFloat4Codec)\n .add('float8', pgFloat8Codec)\n .add('numeric', pgNumericCodec)\n .add('timestamp', pgTimestampCodec)\n .add('timestamptz', pgTimestamptzCodec)\n .add('time', pgTimeCodec)\n .add('timetz', pgTimetzCodec)\n .add('bool', pgBoolCodec)\n .add('bit', pgBitCodec)\n .add('bit varying', pgVarbitCodec)\n .add('interval', pgIntervalCodec)\n .add('enum', pgEnumCodec)\n .add('json', pgJsonCodec)\n .add('jsonb', pgJsonbCodec);\n\n// Export derived structures directly from codecs builder\nexport const codecDefinitions = codecs.codecDefinitions;\nexport const dataTypes = codecs.dataTypes;\n\nexport type CodecTypes = typeof codecs.CodecTypes;\n"],"mappings":";;;;;;AAEA,MAAM,YAAY;AAElB,SAAS,SAAS,OAA2C;AAC3D,QAAO,OAAO,UAAU,YAAY,UAAU;;AAGhD,SAAS,oBAAoB,KAAqB;AAChD,QAAO,IACJ,QAAQ,OAAO,OAAO,CACtB,QAAQ,MAAM,MAAM,CACpB,QAAQ,OAAO,MAAM,CACrB,QAAQ,OAAO,MAAM;;AAG1B,SAAS,iBAAiB,KAAqB;AAC7C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names":["DEFAULT_PLANNER_CONFIG: PlannerConfig","config: PlannerConfig"],"sources":["../src/core/migrations/planner.ts"],"sourcesContent":["import type {\n MigrationOperationPolicy,\n SqlMigrationPlannerPlanOptions,\n SqlPlannerFailureResult,\n} from '@prisma-next/family-sql/control';\nimport { extractCodecControlHooks, plannerFailure } from '@prisma-next/family-sql/control';\nimport { verifySqlSchema } from '@prisma-next/family-sql/schema-verify';\nimport type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';\nimport type {\n MigrationPlanner,\n MigrationPlanWithAuthoringSurface,\n MigrationScaffoldContext,\n SchemaIssue,\n} from '@prisma-next/framework-components/control';\nimport { parsePostgresDefault } from '../default-normalizer';\nimport { normalizeSchemaNativeType } from '../native-type-normalizer';\nimport { planIssues } from './issue-planner';\nimport { TypeScriptRenderablePostgresMigration } from './planner-produced-postgres-migration';\nimport { postgresPlannerStrategies } from './planner-strategies';\n\ntype PlannerFrameworkComponents = SqlMigrationPlannerPlanOptions extends {\n readonly frameworkComponents: infer T;\n}\n ? T\n : ReadonlyArray<unknown>;\n\ntype PlannerOptionsWithComponents = SqlMigrationPlannerPlanOptions & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ntype VerifySqlSchemaOptionsWithComponents = Parameters<typeof verifySqlSchema>[0] & {\n readonly frameworkComponents: PlannerFrameworkComponents;\n};\n\ninterface PlannerConfig {\n readonly defaultSchema: string;\n}\n\nconst DEFAULT_PLANNER_CONFIG: PlannerConfig = {\n defaultSchema: 'public',\n};\n\nexport function createPostgresMigrationPlanner(\n config: Partial<PlannerConfig> = {},\n): PostgresMigrationPlanner {\n return new PostgresMigrationPlanner({\n ...DEFAULT_PLANNER_CONFIG,\n ...config,\n });\n}\n\n/**\n * Result of `PostgresMigrationPlanner.plan()`. A discriminated union whose\n * success variant carries a `TypeScriptRenderablePostgresMigration` — a\n * migration object that both the CLI (via `renderTypeScript()`) and the\n * SQL-typed callers (via `operations`, `describe()`, etc.) consume\n * uniformly.\n */\nexport type PostgresPlanResult =\n | { readonly kind: 'success'; readonly plan: TypeScriptRenderablePostgresMigration }\n | SqlPlannerFailureResult;\n\n/**\n * Postgres migration planner — a thin wrapper over `planIssues`.\n *\n * `plan()` verifies the live schema against the target contract (producing\n * `SchemaIssue[]`) and delegates to `planIssues` with the unified\n * `postgresPlannerStrategies` list: enum-change, NOT-NULL backfill,\n * type-change, nullable-tightening, codec-hook storage types,\n * component-declared dependency installs, and shared-temp-default /\n * empty-table-guarded NOT-NULL add-column. The same strategy list runs for\n * `migration plan`, `db update`, and `db init`; behavior diverges purely on\n * `policy.allowedOperationClasses` (the data-safe strategies short-circuit\n * when `'data'` is excluded). The issue planner applies operation-class\n * policy gates and emits a single `PostgresOpFactoryCall[]` that drives both\n * the runtime-ops view (via `renderOps`) and the `renderTypeScript()`\n * authoring surface.\n */\nexport class PostgresMigrationPlanner implements MigrationPlanner<'sql', 'postgres'> {\n constructor(private readonly config: PlannerConfig) {}\n\n plan(options: {\n readonly contract: unknown;\n readonly schema: unknown;\n readonly policy: MigrationOperationPolicy;\n readonly fromHash?: string | null;\n /**\n * The \"from\" contract (state the planner assumes the database starts\n * at). Only `migration plan` supplies this; `db update` / `db init`\n * reconcile against the live schema with no old contract. When present\n * alongside the `'data'` operation class, strategies that need from/to\n * column shape comparisons (unsafe type change, nullability tightening)\n * activate.\n */\n readonly fromContract?: unknown;\n readonly schemaName?: string;\n readonly frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<'sql', string>>;\n }): PostgresPlanResult {\n return this.planSql(options as SqlMigrationPlannerPlanOptions, options.fromHash ?? null);\n }\n\n emptyMigration(context: MigrationScaffoldContext): MigrationPlanWithAuthoringSurface {\n return new TypeScriptRenderablePostgresMigration([], {\n from: context.fromHash,\n to: context.toHash,\n });\n }\n\n private planSql(\n options: SqlMigrationPlannerPlanOptions,\n fromHash: string | null,\n ): PostgresPlanResult {\n const schemaName = options.schemaName ?? this.config.defaultSchema;\n const policyResult = this.ensureAdditivePolicy(options.policy);\n if (policyResult) {\n return policyResult;\n }\n\n const schemaIssues = this.collectSchemaIssues(options);\n const codecHooks = extractCodecControlHooks(options.frameworkComponents);\n const storageTypes = options.contract.storage.types ?? {};\n\n const result = planIssues({\n issues: schemaIssues,\n toContract: options.contract,\n // `fromContract` is only supplied by `migration plan`. It is `null` for\n // `db update` / `db init`, which means data-safety strategies needing\n // from/to comparisons (unsafe type change, nullable tightening) are\n // inapplicable there — reconciliation falls through to\n // `mapIssueToCall`'s direct destructive handlers.\n fromContract: options.fromContract ?? null,\n schemaName,\n codecHooks,\n storageTypes,\n schema: options.schema,\n policy: options.policy,\n frameworkComponents: options.frameworkComponents,\n strategies: postgresPlannerStrategies,\n });\n\n if (!result.ok) {\n return plannerFailure(result.failure);\n }\n\n return Object.freeze({\n kind: 'success' as const,\n plan: new TypeScriptRenderablePostgresMigration(result.value.calls, {\n from: fromHash,\n to: options.contract.storage.storageHash,\n }),\n });\n }\n\n private ensureAdditivePolicy(policy: MigrationOperationPolicy) {\n if (!policy.allowedOperationClasses.includes('additive')) {\n return plannerFailure([\n {\n kind: 'unsupportedOperation',\n summary: 'Migration planner requires additive operations be allowed',\n why: 'The planner requires the \"additive\" operation class to be allowed in the policy.',\n },\n ]);\n }\n return null;\n }\n\n private collectSchemaIssues(options: PlannerOptionsWithComponents): readonly SchemaIssue[] {\n // `db init` uses additive-only policy and intentionally ignores extra\n // schema objects. Any reconciliation-capable policy (widening or\n // destructive) must inspect extras to reconcile strict equality.\n const allowed = options.policy.allowedOperationClasses;\n const strict = allowed.includes('widening') || allowed.includes('destructive');\n const verifyOptions: VerifySqlSchemaOptionsWithComponents = {\n contract: options.contract,\n schema: options.schema,\n strict,\n typeMetadataRegistry: new Map(),\n frameworkComponents: options.frameworkComponents,\n normalizeDefault: parsePostgresDefault,\n normalizeNativeType: normalizeSchemaNativeType,\n };\n const verifyResult = verifySqlSchema(verifyOptions);\n return verifyResult.schema.issues;\n }\n}\n"],"mappings":";;;;;;;;AAsCA,M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T,AAAQ,oBAAoB,SAA+D;EAIzF,MAAM,UAAU,QAAQ,OAAO;EAC/B,MAAM,SAAS,QAAQ,SAAS,WAAW,IAAI,QAAQ,SAAS,cAAc;AAW9E,SADqB,gBATuC;GAC1D,UAAU,QAAQ;GAClB,QAAQ,QAAQ;GAChB;GACA,sCAAsB,IAAI,KAAK;GAC/B,qBAAqB,QAAQ;GAC7B,kBAAkB;GAClB,qBAAqB;GACtB,CACkD,CAC/B,OAAO"}
@@ -1,131 +0,0 @@
1
- type JsonSchemaRecord = Record<string, unknown>;
2
-
3
- const MAX_DEPTH = 32;
4
-
5
- function isRecord(value: unknown): value is JsonSchemaRecord {
6
- return typeof value === 'object' && value !== null;
7
- }
8
-
9
- function escapeStringLiteral(str: string): string {
10
- return str
11
- .replace(/\\/g, '\\\\')
12
- .replace(/'/g, "\\'")
13
- .replace(/\n/g, '\\n')
14
- .replace(/\r/g, '\\r');
15
- }
16
-
17
- function quotePropertyKey(key: string): string {
18
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : `'${escapeStringLiteral(key)}'`;
19
- }
20
-
21
- function renderLiteral(value: unknown): string {
22
- if (typeof value === 'string') {
23
- return `'${escapeStringLiteral(value)}'`;
24
- }
25
- if (typeof value === 'number' || typeof value === 'boolean') {
26
- return String(value);
27
- }
28
- if (value === null) {
29
- return 'null';
30
- }
31
- return 'unknown';
32
- }
33
-
34
- function renderUnion(items: readonly unknown[], depth: number): string {
35
- const rendered = items.map((item) => render(item, depth));
36
- return rendered.join(' | ');
37
- }
38
-
39
- function renderObjectType(schema: JsonSchemaRecord, depth: number): string {
40
- const properties = isRecord(schema['properties']) ? schema['properties'] : {};
41
- const required = Array.isArray(schema['required'])
42
- ? new Set(schema['required'].filter((key): key is string => typeof key === 'string'))
43
- : new Set<string>();
44
- const keys = Object.keys(properties).sort((left, right) => left.localeCompare(right));
45
-
46
- if (keys.length === 0) {
47
- const additionalProperties = schema['additionalProperties'];
48
- if (additionalProperties === true || additionalProperties === undefined) {
49
- return 'Record<string, unknown>';
50
- }
51
- return `Record<string, ${render(additionalProperties, depth)}>`;
52
- }
53
-
54
- const renderedProperties = keys.map((key) => {
55
- const valueSchema = (properties as JsonSchemaRecord)[key];
56
- const optionalMarker = required.has(key) ? '' : '?';
57
- return `${quotePropertyKey(key)}${optionalMarker}: ${render(valueSchema, depth)}`;
58
- });
59
-
60
- return `{ ${renderedProperties.join('; ')} }`;
61
- }
62
-
63
- function renderArrayType(schema: JsonSchemaRecord, depth: number): string {
64
- if (Array.isArray(schema['items'])) {
65
- return `readonly [${schema['items'].map((item) => render(item, depth)).join(', ')}]`;
66
- }
67
-
68
- if (schema['items'] !== undefined) {
69
- const itemType = render(schema['items'], depth);
70
- const needsParens = itemType.includes(' | ') || itemType.includes(' & ');
71
- return needsParens ? `(${itemType})[]` : `${itemType}[]`;
72
- }
73
-
74
- return 'unknown[]';
75
- }
76
-
77
- function render(schema: unknown, depth: number): string {
78
- if (depth > MAX_DEPTH || !isRecord(schema)) {
79
- return 'JsonValue';
80
- }
81
-
82
- const nextDepth = depth + 1;
83
-
84
- if ('const' in schema) {
85
- return renderLiteral(schema['const']);
86
- }
87
-
88
- if (Array.isArray(schema['enum'])) {
89
- return schema['enum'].map((value) => renderLiteral(value)).join(' | ');
90
- }
91
-
92
- if (Array.isArray(schema['oneOf'])) {
93
- return renderUnion(schema['oneOf'], nextDepth);
94
- }
95
-
96
- if (Array.isArray(schema['anyOf'])) {
97
- return renderUnion(schema['anyOf'], nextDepth);
98
- }
99
-
100
- if (Array.isArray(schema['allOf'])) {
101
- return schema['allOf'].map((item) => render(item, nextDepth)).join(' & ');
102
- }
103
-
104
- if (Array.isArray(schema['type'])) {
105
- return schema['type'].map((item) => render({ ...schema, type: item }, nextDepth)).join(' | ');
106
- }
107
-
108
- switch (schema['type']) {
109
- case 'string':
110
- return 'string';
111
- case 'number':
112
- case 'integer':
113
- return 'number';
114
- case 'boolean':
115
- return 'boolean';
116
- case 'null':
117
- return 'null';
118
- case 'array':
119
- return renderArrayType(schema, nextDepth);
120
- case 'object':
121
- return renderObjectType(schema, nextDepth);
122
- default:
123
- break;
124
- }
125
-
126
- return 'JsonValue';
127
- }
128
-
129
- export function renderTypeScriptTypeFromJsonSchema(schema: unknown): string {
130
- return render(schema, 0);
131
- }