@prisma-next/adapter-postgres 0.13.0-dev.3 → 0.13.0-dev.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/{adapter-CAlWA4ug.mjs → adapter-CmADcToh.mjs} +3 -3
  2. package/dist/adapter-CmADcToh.mjs.map +1 -0
  3. package/dist/adapter.d.mts +1 -1
  4. package/dist/adapter.d.mts.map +1 -1
  5. package/dist/adapter.mjs +1 -1
  6. package/dist/column-types.d.mts +1 -6
  7. package/dist/column-types.d.mts.map +1 -1
  8. package/dist/column-types.mjs +2 -17
  9. package/dist/column-types.mjs.map +1 -1
  10. package/dist/{control-adapter-ZWrjGBq7.mjs → control-adapter-DmSBWLEm.mjs} +216 -223
  11. package/dist/control-adapter-DmSBWLEm.mjs.map +1 -0
  12. package/dist/control.d.mts +25 -22
  13. package/dist/control.d.mts.map +1 -1
  14. package/dist/control.mjs +3 -3
  15. package/dist/control.mjs.map +1 -1
  16. package/dist/{descriptor-meta-NBwpqHS7.mjs → descriptor-meta-DOgMfoqm.mjs} +10 -3
  17. package/dist/descriptor-meta-DOgMfoqm.mjs.map +1 -0
  18. package/dist/runtime.d.mts +1 -1
  19. package/dist/runtime.mjs +2 -2
  20. package/dist/{types-Dv7M8jx8.d.mts → types-KXRwRZU8.d.mts} +3 -3
  21. package/dist/types-KXRwRZU8.d.mts.map +1 -0
  22. package/dist/types.d.mts +1 -1
  23. package/package.json +22 -22
  24. package/src/core/adapter.ts +5 -4
  25. package/src/core/codec-lookup.ts +5 -5
  26. package/src/core/control-adapter.ts +261 -86
  27. package/src/core/control-codecs.ts +25 -0
  28. package/src/core/descriptor-meta.ts +3 -0
  29. package/src/core/marker-ledger.ts +2 -18
  30. package/src/core/sql-renderer.ts +133 -5
  31. package/src/core/types.ts +2 -2
  32. package/src/exports/column-types.ts +0 -20
  33. package/src/exports/control.ts +1 -0
  34. package/dist/adapter-CAlWA4ug.mjs.map +0 -1
  35. package/dist/control-adapter-ZWrjGBq7.mjs.map +0 -1
  36. package/dist/descriptor-meta-NBwpqHS7.mjs.map +0 -1
  37. package/dist/types-Dv7M8jx8.d.mts.map +0 -1
  38. package/src/core/ddl-renderer.ts +0 -155
  39. package/src/core/enum-control-hooks.ts +0 -141
@@ -0,0 +1 @@
1
+ {"version":3,"file":"descriptor-meta-DOgMfoqm.mjs","names":[],"sources":["../src/core/descriptor-meta.ts"],"sourcesContent":["import type { CodecControlHooks, ExpandNativeTypeInput } from '@prisma-next/family-sql/control';\nimport {\n buildOperation,\n type CodecExpression,\n type Expression,\n type TraitExpression,\n toExpr,\n} from '@prisma-next/sql-relational-core/expression';\nimport {\n PG_BIT_CODEC_ID,\n PG_BOOL_CODEC_ID,\n PG_BYTEA_CODEC_ID,\n PG_CHAR_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_UUID_CODEC_ID,\n PG_VARBIT_CODEC_ID,\n PG_VARCHAR_CODEC_ID,\n SQL_CHAR_CODEC_ID,\n SQL_FLOAT_CODEC_ID,\n SQL_INT_CODEC_ID,\n SQL_TEXT_CODEC_ID,\n SQL_TIMESTAMP_CODEC_ID,\n SQL_VARCHAR_CODEC_ID,\n} from '@prisma-next/target-postgres/codec-ids';\nimport { postgresCodecRegistry } from '@prisma-next/target-postgres/codecs';\nimport type { QueryOperationTypes } from '../types/operation-types';\n\n// ============================================================================ Helper functions for reducing boilerplate ============================================================================\n\n/** Creates a type import spec for codec types */\nconst codecTypeImport = (named: string) =>\n ({\n package: '@prisma-next/target-postgres/codec-types',\n named,\n alias: named,\n }) as const;\n\nfunction isPositiveInteger(value: unknown): value is number {\n return (\n typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value) && value > 0\n );\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return (\n typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value) && value >= 0\n );\n}\n\nfunction expandLength({ nativeType, typeParams }: ExpandNativeTypeInput): string {\n if (!typeParams || !('length' in typeParams)) {\n return nativeType;\n }\n const length = typeParams['length'];\n if (!isPositiveInteger(length)) {\n throw new Error(\n `Invalid \"length\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(length)}`,\n );\n }\n return `${nativeType}(${length})`;\n}\n\nfunction expandPrecision({ nativeType, typeParams }: ExpandNativeTypeInput): string {\n if (!typeParams || !('precision' in typeParams)) {\n return nativeType;\n }\n const precision = typeParams['precision'];\n if (!isPositiveInteger(precision)) {\n throw new Error(\n `Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`,\n );\n }\n return `${nativeType}(${precision})`;\n}\n\nfunction expandNumeric({ nativeType, typeParams }: ExpandNativeTypeInput): string {\n const hasPrecision = typeParams && 'precision' in typeParams;\n const hasScale = typeParams && 'scale' in typeParams;\n\n if (!hasPrecision && !hasScale) {\n return nativeType;\n }\n\n if (!hasPrecision && hasScale) {\n throw new Error(\n `Invalid type parameters for \"${nativeType}\": \"scale\" requires \"precision\" to be specified`,\n );\n }\n\n if (hasPrecision) {\n const precision = typeParams['precision'];\n if (!isPositiveInteger(precision)) {\n throw new Error(\n `Invalid \"precision\" type parameter for \"${nativeType}\": expected a positive integer, got ${JSON.stringify(precision)}`,\n );\n }\n if (hasScale) {\n const scale = typeParams['scale'];\n if (!isNonNegativeInteger(scale)) {\n throw new Error(\n `Invalid \"scale\" type parameter for \"${nativeType}\": expected a non-negative integer, got ${JSON.stringify(scale)}`,\n );\n }\n return `${nativeType}(${precision},${scale})`;\n }\n return `${nativeType}(${precision})`;\n }\n\n return nativeType;\n}\n\nconst lengthHooks: CodecControlHooks = { expandNativeType: expandLength };\nconst precisionHooks: CodecControlHooks = { expandNativeType: expandPrecision };\nconst numericHooks: CodecControlHooks = { expandNativeType: expandNumeric };\nconst identityHooks: CodecControlHooks = { expandNativeType: ({ nativeType }) => nativeType };\n\n// ============================================================================ Descriptor metadata ============================================================================\n\ntype CodecTypesBase = Record<string, { readonly input: unknown; readonly output: unknown }>;\n\nexport function postgresQueryOperations<CT extends CodecTypesBase>(): QueryOperationTypes<CT> {\n return {\n ilike: {\n self: { traits: ['textual'] },\n impl: (\n self: TraitExpression<readonly ['textual'], false, CT>,\n pattern: CodecExpression<'pg/text@1', false, CT>,\n ): Expression<{ codecId: 'pg/bool@1'; nullable: false }> => {\n return buildOperation({\n method: 'ilike',\n args: [toExpr(self), toExpr(pattern, { codecId: PG_TEXT_CODEC_ID })],\n returns: { codecId: PG_BOOL_CODEC_ID, nullable: false },\n lowering: { targetFamily: 'sql', strategy: 'infix', template: '{{self}} ILIKE {{arg0}}' },\n });\n },\n },\n };\n}\n\nexport const postgresAdapterDescriptorMeta = {\n kind: 'adapter',\n familyId: 'sql',\n targetId: 'postgres',\n id: 'postgres',\n version: '0.0.1',\n capabilities: {\n postgres: {\n orderBy: true,\n limit: true,\n lateral: true,\n jsonAgg: true,\n returning: true,\n distinctOn: true,\n },\n sql: {\n enums: true,\n returning: true,\n defaultInInsert: true,\n lateral: true,\n },\n },\n types: {\n codecTypes: {\n codecDescriptors: Array.from(postgresCodecRegistry.values()),\n import: {\n package: '@prisma-next/target-postgres/codec-types',\n named: 'CodecTypes',\n alias: 'PgTypes',\n },\n typeImports: [\n {\n package: '@prisma-next/target-postgres/codec-types',\n named: 'JsonValue',\n alias: 'JsonValue',\n },\n codecTypeImport('Char'),\n codecTypeImport('Varchar'),\n codecTypeImport('Numeric'),\n codecTypeImport('Bit'),\n codecTypeImport('VarBit'),\n codecTypeImport('Timestamp'),\n codecTypeImport('Timestamptz'),\n codecTypeImport('Time'),\n codecTypeImport('Timetz'),\n codecTypeImport('Interval'),\n ],\n controlPlaneHooks: {\n [SQL_CHAR_CODEC_ID]: lengthHooks,\n [SQL_VARCHAR_CODEC_ID]: lengthHooks,\n [SQL_TIMESTAMP_CODEC_ID]: precisionHooks,\n [PG_CHAR_CODEC_ID]: lengthHooks,\n [PG_VARCHAR_CODEC_ID]: lengthHooks,\n [PG_NUMERIC_CODEC_ID]: numericHooks,\n [PG_BIT_CODEC_ID]: lengthHooks,\n [PG_VARBIT_CODEC_ID]: lengthHooks,\n [PG_TIMESTAMP_CODEC_ID]: precisionHooks,\n [PG_TIMESTAMPTZ_CODEC_ID]: precisionHooks,\n [PG_TIME_CODEC_ID]: precisionHooks,\n [PG_TIMETZ_CODEC_ID]: precisionHooks,\n [PG_INTERVAL_CODEC_ID]: precisionHooks,\n [PG_JSON_CODEC_ID]: identityHooks,\n [PG_JSONB_CODEC_ID]: identityHooks,\n [PG_BYTEA_CODEC_ID]: identityHooks,\n [PG_UUID_CODEC_ID]: identityHooks,\n },\n },\n storage: [\n { typeId: PG_TEXT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'text' },\n { typeId: SQL_TEXT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'text' },\n { typeId: SQL_CHAR_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'character' },\n {\n typeId: SQL_VARCHAR_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'character varying',\n },\n { typeId: SQL_INT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int4' },\n { typeId: SQL_FLOAT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'float8' },\n {\n typeId: SQL_TIMESTAMP_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'timestamp',\n },\n { typeId: PG_CHAR_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'character' },\n {\n typeId: PG_VARCHAR_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'character varying',\n },\n { typeId: PG_INT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int4' },\n { typeId: PG_FLOAT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'float8' },\n { typeId: PG_INT4_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int4' },\n { typeId: PG_INT2_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int2' },\n { typeId: PG_INT8_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'int8' },\n { typeId: PG_FLOAT4_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'float4' },\n { typeId: PG_FLOAT8_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'float8' },\n { typeId: PG_NUMERIC_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'numeric' },\n {\n typeId: PG_TIMESTAMP_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'timestamp',\n },\n {\n typeId: PG_TIMESTAMPTZ_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'timestamptz',\n },\n { typeId: PG_TIME_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'time' },\n { typeId: PG_TIMETZ_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'timetz' },\n { typeId: PG_BOOL_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'bool' },\n { typeId: PG_BIT_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'bit' },\n {\n typeId: PG_VARBIT_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'bit varying',\n },\n {\n typeId: PG_INTERVAL_CODEC_ID,\n familyId: 'sql',\n targetId: 'postgres',\n nativeType: 'interval',\n },\n { typeId: PG_JSON_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'json' },\n { typeId: PG_JSONB_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'jsonb' },\n { typeId: PG_BYTEA_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'bytea' },\n { typeId: PG_UUID_CODEC_ID, familyId: 'sql', targetId: 'postgres', nativeType: 'uuid' },\n ],\n queryOperationTypes: {\n import: {\n package: '@prisma-next/adapter-postgres/operation-types',\n named: 'QueryOperationTypes',\n alias: 'PgAdapterQueryOps',\n },\n },\n },\n} as const;\n"],"mappings":";;;;;AA6CA,MAAM,mBAAmB,WACtB;CACC,SAAS;CACT;CACA,OAAO;AACT;AAEF,SAAS,kBAAkB,OAAiC;CAC1D,OACE,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,OAAO,UAAU,KAAK,KAAK,QAAQ;AAE9F;AAEA,SAAS,qBAAqB,OAAiC;CAC7D,OACE,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,OAAO,UAAU,KAAK,KAAK,SAAS;AAE/F;AAEA,SAAS,aAAa,EAAE,YAAY,cAA6C;CAC/E,IAAI,CAAC,cAAc,EAAE,YAAY,aAC/B,OAAO;CAET,MAAM,SAAS,WAAW;CAC1B,IAAI,CAAC,kBAAkB,MAAM,GAC3B,MAAM,IAAI,MACR,wCAAwC,WAAW,sCAAsC,KAAK,UAAU,MAAM,GAChH;CAEF,OAAO,GAAG,WAAW,GAAG,OAAO;AACjC;AAEA,SAAS,gBAAgB,EAAE,YAAY,cAA6C;CAClF,IAAI,CAAC,cAAc,EAAE,eAAe,aAClC,OAAO;CAET,MAAM,YAAY,WAAW;CAC7B,IAAI,CAAC,kBAAkB,SAAS,GAC9B,MAAM,IAAI,MACR,2CAA2C,WAAW,sCAAsC,KAAK,UAAU,SAAS,GACtH;CAEF,OAAO,GAAG,WAAW,GAAG,UAAU;AACpC;AAEA,SAAS,cAAc,EAAE,YAAY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AAmB,UAAU;IAAO,UAAU;IAAY,YAAY;GAAQ;GACxF;IAAE,QAAQ;IAAkB,UAAU;IAAO,UAAU;IAAY,YAAY;GAAO;EACxF;EACA,qBAAqB,EACnB,QAAQ;GACN,SAAS;GACT,OAAO;GACP,OAAO;EACT,EACF;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { c as PostgresContract, l as PostgresLoweredStatement } from "./types-Dv7M8jx8.mjs";
1
+ import { c as PostgresContract, l as PostgresLoweredStatement } from "./types-KXRwRZU8.mjs";
2
2
  import { Adapter, AnyQueryAst } from "@prisma-next/sql-relational-core/ast";
3
3
  import { SqlRuntimeAdapterDescriptor } from "@prisma-next/sql-runtime";
4
4
  import { RuntimeAdapterInstance } from "@prisma-next/framework-components/execution";
package/dist/runtime.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { n as postgresRawCodecInferer, t as createPostgresAdapter } from "./adapter-CAlWA4ug.mjs";
2
- import { n as postgresQueryOperations, t as postgresAdapterDescriptorMeta } from "./descriptor-meta-NBwpqHS7.mjs";
1
+ import { n as postgresRawCodecInferer, t as createPostgresAdapter } from "./adapter-CmADcToh.mjs";
2
+ import { n as postgresQueryOperations, t as postgresAdapterDescriptorMeta } from "./descriptor-meta-DOgMfoqm.mjs";
3
3
  import { extractCodecLookup } from "@prisma-next/framework-components/control";
4
4
  import { postgresCodecRegistry } from "@prisma-next/target-postgres/codecs";
5
5
  import { builtinGeneratorIds } from "@prisma-next/ids";
@@ -1,6 +1,6 @@
1
1
  import { BinaryExpr, ColumnRef, DefaultValueExpr, Direction, LoweredStatement, ParamRef, SelectAst } from "@prisma-next/sql-relational-core/ast";
2
2
  import { Contract } from "@prisma-next/contract/types";
3
- import { CodecLookup } from "@prisma-next/framework-components/codec";
3
+ import { CodecRegistry } from "@prisma-next/framework-components/codec";
4
4
  import { SqlStorage, StorageColumn, StorageTable } from "@prisma-next/sql-contract/types";
5
5
 
6
6
  //#region src/core/types.d.ts
@@ -15,7 +15,7 @@ interface PostgresAdapterOptions {
15
15
  * `SqlControlAdapterDescriptor.create(stack)`) supply the assembled stack
16
16
  * lookup so extension codecs are visible to the renderer.
17
17
  */
18
- readonly codecLookup?: CodecLookup;
18
+ readonly codecLookup?: CodecRegistry;
19
19
  }
20
20
  type PostgresContract = Contract<SqlStorage> & {
21
21
  readonly target: 'postgres';
@@ -28,4 +28,4 @@ interface OrderClause {
28
28
  type PostgresLoweredStatement = LoweredStatement;
29
29
  //#endregion
30
30
  export { OrderClause as a, PostgresContract as c, StorageColumn as d, StorageTable as f, Expr as i, PostgresLoweredStatement as l, ColumnRef as n, ParamRef as o, Direction as r, PostgresAdapterOptions as s, BinaryExpr as t, SelectAst as u };
31
- //# sourceMappingURL=types-Dv7M8jx8.d.mts.map
31
+ //# sourceMappingURL=types-KXRwRZU8.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-KXRwRZU8.d.mts","names":[],"sources":["../src/core/types.ts"],"mappings":";;;;;;UAoBiB,sBAAA;EAAA,SACN,SAAA;EADM;;;;;;;;AAWqB;EAXrB,SAWN,WAAA,GAAc,aAAa;AAAA;AAAA,KAG1B,gBAAA,GAAmB,QAAQ,CAAC,UAAA;EAAA,SAAyB,MAAA;AAAA;AAAA,KAErD,IAAA,GAAO,SAAA,GAAY,QAAA,GAAW,gBAAA;AAAA,UAEzB,WAAA;EAAA,SACN,IAAA,EAAM,SAAA;EAAA,SACN,GAAA,EAAK,SAAS;AAAA;AAAA,KAGb,wBAAA,GAA2B,gBAAgB"}
package/dist/types.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as OrderClause, c as PostgresContract, d as StorageColumn, f as StorageTable, i as Expr, l as PostgresLoweredStatement, n as ColumnRef, o as ParamRef, r as Direction, s as PostgresAdapterOptions, t as BinaryExpr, u as SelectAst } from "./types-Dv7M8jx8.mjs";
1
+ import { a as OrderClause, c as PostgresContract, d as StorageColumn, f as StorageTable, i as Expr, l as PostgresLoweredStatement, n as ColumnRef, o as ParamRef, r as Direction, s as PostgresAdapterOptions, t as BinaryExpr, u as SelectAst } from "./types-KXRwRZU8.mjs";
2
2
  export type { BinaryExpr, ColumnRef, Direction, Expr, OrderClause, ParamRef, PostgresAdapterOptions, PostgresContract, PostgresLoweredStatement, SelectAst, StorageColumn, StorageTable };
package/package.json CHANGED
@@ -1,34 +1,34 @@
1
1
  {
2
2
  "name": "@prisma-next/adapter-postgres",
3
- "version": "0.13.0-dev.3",
3
+ "version": "0.13.0-dev.30",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "dependencies": {
8
- "@prisma-next/contract": "0.13.0-dev.3",
9
- "@prisma-next/contract-authoring": "0.13.0-dev.3",
10
- "@prisma-next/errors": "0.13.0-dev.3",
11
- "@prisma-next/family-sql": "0.13.0-dev.3",
12
- "@prisma-next/framework-components": "0.13.0-dev.3",
13
- "@prisma-next/ids": "0.13.0-dev.3",
14
- "@prisma-next/sql-contract": "0.13.0-dev.3",
15
- "@prisma-next/sql-contract-psl": "0.13.0-dev.3",
16
- "@prisma-next/sql-contract-ts": "0.13.0-dev.3",
17
- "@prisma-next/sql-operations": "0.13.0-dev.3",
18
- "@prisma-next/sql-relational-core": "0.13.0-dev.3",
19
- "@prisma-next/sql-runtime": "0.13.0-dev.3",
20
- "@prisma-next/sql-schema-ir": "0.13.0-dev.3",
21
- "@prisma-next/target-postgres": "0.13.0-dev.3",
22
- "@prisma-next/utils": "0.13.0-dev.3",
8
+ "@prisma-next/contract": "0.13.0-dev.30",
9
+ "@prisma-next/contract-authoring": "0.13.0-dev.30",
10
+ "@prisma-next/errors": "0.13.0-dev.30",
11
+ "@prisma-next/family-sql": "0.13.0-dev.30",
12
+ "@prisma-next/framework-components": "0.13.0-dev.30",
13
+ "@prisma-next/ids": "0.13.0-dev.30",
14
+ "@prisma-next/sql-contract": "0.13.0-dev.30",
15
+ "@prisma-next/sql-contract-psl": "0.13.0-dev.30",
16
+ "@prisma-next/sql-contract-ts": "0.13.0-dev.30",
17
+ "@prisma-next/sql-operations": "0.13.0-dev.30",
18
+ "@prisma-next/sql-relational-core": "0.13.0-dev.30",
19
+ "@prisma-next/sql-runtime": "0.13.0-dev.30",
20
+ "@prisma-next/sql-schema-ir": "0.13.0-dev.30",
21
+ "@prisma-next/target-postgres": "0.13.0-dev.30",
22
+ "@prisma-next/utils": "0.13.0-dev.30",
23
23
  "arktype": "^2.2.0"
24
24
  },
25
25
  "devDependencies": {
26
- "@prisma-next/cli": "0.13.0-dev.3",
27
- "@prisma-next/driver-postgres": "0.13.0-dev.3",
28
- "@prisma-next/migration-tools": "0.13.0-dev.3",
29
- "@prisma-next/test-utils": "0.13.0-dev.3",
30
- "@prisma-next/tsconfig": "0.13.0-dev.3",
31
- "@prisma-next/tsdown": "0.13.0-dev.3",
26
+ "@prisma-next/cli": "0.13.0-dev.30",
27
+ "@prisma-next/driver-postgres": "0.13.0-dev.30",
28
+ "@prisma-next/migration-tools": "0.13.0-dev.30",
29
+ "@prisma-next/test-utils": "0.13.0-dev.30",
30
+ "@prisma-next/tsconfig": "0.13.0-dev.30",
31
+ "@prisma-next/tsdown": "0.13.0-dev.30",
32
32
  "pathe": "^2.0.3",
33
33
  "tsdown": "0.22.1",
34
34
  "typescript": "5.9.3",
@@ -1,4 +1,4 @@
1
- import type { CodecLookup } from '@prisma-next/framework-components/codec';
1
+ import type { CodecRegistry } from '@prisma-next/framework-components/codec';
2
2
  import { APP_SPACE_ID } from '@prisma-next/framework-components/control';
3
3
  import type {
4
4
  Adapter,
@@ -13,7 +13,6 @@ import type { RawCodecInferer } from '@prisma-next/sql-relational-core/expressio
13
13
  import type { PostgresDdlNode } from '@prisma-next/target-postgres/ddl';
14
14
  import { createPostgresBuiltinCodecLookup } from './codec-lookup';
15
15
  import { PostgresControlAdapter } from './control-adapter';
16
- import { renderLoweredDdl } from './ddl-renderer';
17
16
  import { renderLoweredSql } from './sql-renderer';
18
17
  import type { PostgresAdapterOptions, PostgresContract, PostgresLoweredStatement } from './types';
19
18
 
@@ -42,7 +41,7 @@ class PostgresAdapterImpl
42
41
  readonly targetId = 'postgres' as const;
43
42
 
44
43
  readonly profile: AdapterProfile<'postgres'>;
45
- private readonly codecLookup: CodecLookup;
44
+ private readonly codecLookup: CodecRegistry;
46
45
 
47
46
  constructor(options?: PostgresAdapterOptions) {
48
47
  this.codecLookup = options?.codecLookup ?? createPostgresBuiltinCodecLookup();
@@ -75,7 +74,9 @@ class PostgresAdapterImpl
75
74
  context: LowererContext<PostgresContract>,
76
75
  ): PostgresLoweredStatement {
77
76
  if (isDdlNode(ast)) {
78
- return renderLoweredDdl(ast);
77
+ throw new Error(
78
+ 'lower() does not lower DDL on the runtime adapter — DDL lowering is a control-plane concern handled by the control adapter.',
79
+ );
79
80
  }
80
81
  return renderLoweredSql(ast, context.contract, this.codecLookup);
81
82
  }
@@ -1,15 +1,15 @@
1
- import type { CodecLookup } from '@prisma-next/framework-components/codec';
1
+ import type { CodecRegistry } from '@prisma-next/framework-components/codec';
2
2
  import { extractCodecLookup } from '@prisma-next/framework-components/control';
3
3
  import { postgresCodecRegistry } from '@prisma-next/target-postgres/codecs';
4
4
 
5
5
  /**
6
- * Build a {@link CodecLookup} populated with the Postgres-builtin codec definitions only.
6
+ * Build a {@link CodecRegistry} populated with the Postgres-builtin codec definitions only.
7
7
  *
8
- * This is the default lookup used by `createPostgresAdapter()` and `new PostgresControlAdapter()` when called without a stack-derived lookup (e.g. from tests, or one-off scripts that don't compose a full stack).
8
+ * This is the default registry used by `createPostgresAdapter()` and `new PostgresControlAdapter()` when called without a stack-derived registry (e.g. from tests, or one-off scripts that don't compose a full stack).
9
9
  *
10
- * Extension codecs (e.g. `pg/vector@1` from `@prisma-next/extension-pgvector`) are intentionally NOT included here: a bare adapter cannot see extensions. Stack-composed paths (`SqlControlAdapterDescriptor.create(stack)` / `SqlRuntimeAdapterDescriptor.create(stack)`) supply the broader, extension-inclusive lookup at construction time.
10
+ * Extension codecs (e.g. `pg/vector@1` from `@prisma-next/extension-pgvector`) are intentionally NOT included here: a bare adapter cannot see extensions. Stack-composed paths (`SqlControlAdapterDescriptor.create(stack)` / `SqlRuntimeAdapterDescriptor.create(stack)`) supply the broader, extension-inclusive registry at construction time.
11
11
  */
12
- export function createPostgresBuiltinCodecLookup(): CodecLookup {
12
+ export function createPostgresBuiltinCodecLookup(): CodecRegistry {
13
13
  return extractCodecLookup([
14
14
  {
15
15
  id: 'postgres-builtin-codecs',
@@ -1,8 +1,4 @@
1
- import type {
2
- Contract,
3
- ContractMarkerRecord,
4
- LedgerEntryRecord,
5
- } from '@prisma-next/contract/types';
1
+ import type { ContractMarkerRecord, LedgerEntryRecord } from '@prisma-next/contract/types';
6
2
  import {
7
3
  parseMarkerRowSafely,
8
4
  rethrowMarkerReadError,
@@ -10,21 +6,25 @@ import {
10
6
  } from '@prisma-next/errors/execution';
11
7
  import type { SqlControlAdapter } from '@prisma-next/family-sql/control-adapter';
12
8
  import { parseContractMarkerRow } from '@prisma-next/family-sql/verify';
13
- import type { CodecLookup } from '@prisma-next/framework-components/codec';
9
+ import type { CodecLookup, CodecRegistry } from '@prisma-next/framework-components/codec';
14
10
  import { APP_SPACE_ID } from '@prisma-next/framework-components/control';
15
11
  import { UNBOUND_NAMESPACE_ID } from '@prisma-next/framework-components/ir';
16
12
  import { ledgerOriginFromStored } from '@prisma-next/migration-tools/ledger-origin';
17
- import type {
18
- PostgresEnumStorageEntry,
19
- SqlControlDriverInstance,
20
- SqlStorage,
21
- } from '@prisma-next/sql-contract/types';
13
+ import { REFERENTIAL_ACTION_SQL } from '@prisma-next/sql-contract/referential-action-sql';
14
+ import type { SqlControlDriverInstance } from '@prisma-next/sql-contract/types';
22
15
  import type {
23
16
  AnyQueryAst,
17
+ CodecRef,
18
+ ContractCodecRegistry,
19
+ DdlColumn,
24
20
  DdlNode,
21
+ DdlTableConstraint,
22
+ FunctionColumnDefault,
23
+ LiteralColumnDefault,
25
24
  LoweredStatement,
26
25
  LowererContext,
27
26
  MarkerReadResult,
27
+ SqlExecuteRequest,
28
28
  } from '@prisma-next/sql-relational-core/ast';
29
29
  import { isDdlNode } from '@prisma-next/sql-relational-core/ast';
30
30
  import type {
@@ -42,23 +42,20 @@ import {
42
42
  buildControlTableBootstrapQueries,
43
43
  buildSignMarkerBootstrapQueries,
44
44
  } from '@prisma-next/target-postgres/contract-free';
45
- import type { PostgresDdlNode } from '@prisma-next/target-postgres/ddl';
45
+ import type {
46
+ AddColumnAction,
47
+ AlterTableActionVisitor,
48
+ PostgresAlterTable,
49
+ PostgresCreateSchema,
50
+ PostgresCreateTable,
51
+ PostgresDdlNode,
52
+ } from '@prisma-next/target-postgres/ddl';
46
53
  import { parsePostgresDefault } from '@prisma-next/target-postgres/default-normalizer';
47
- import {
48
- createResolveExistingEnumValues,
49
- enumStorageCompoundKey,
50
- readExistingEnumValues,
51
- readPostgresSchemaIrAnnotations,
52
- } from '@prisma-next/target-postgres/enum-planning';
53
54
  import { normalizeSchemaNativeType } from '@prisma-next/target-postgres/native-type-normalizer';
55
+ import { escapeLiteral, quoteIdentifier } from '@prisma-next/target-postgres/sql-utils';
54
56
  import { blindCast } from '@prisma-next/utils/casts';
55
57
  import { ifDefined } from '@prisma-next/utils/defined';
56
- import { createPostgresBuiltinCodecLookup } from './codec-lookup';
57
- import { renderLoweredDdl } from './ddl-renderer';
58
- import {
59
- introspectPostgresEnumTypes,
60
- type PostgresEnumStorageTypeAnnotation,
61
- } from './enum-control-hooks';
58
+ import { encodeControlQueryParams } from './control-codecs';
62
59
  import {
63
60
  execute,
64
61
  infoSchemaTables,
@@ -92,17 +89,10 @@ export class PostgresControlAdapter implements SqlControlAdapter<'postgres'> {
92
89
  readonly familyId = 'sql' as const;
93
90
  readonly targetId = 'postgres' as const;
94
91
 
95
- private readonly codecLookup: CodecLookup;
92
+ private readonly codecRegistry: CodecRegistry;
96
93
 
97
- /**
98
- * @param codecLookup - Codec lookup used by the SQL renderer to resolve
99
- * per-codec metadata at lower-time. Defaults to a Postgres-builtins-only
100
- * lookup when omitted. Stack-aware callers
101
- * (`SqlControlAdapterDescriptor.create(stack)`) supply
102
- * `stack.codecLookup` so extension codecs are visible to the renderer.
103
- */
104
- constructor(codecLookup?: CodecLookup) {
105
- this.codecLookup = codecLookup ?? createPostgresBuiltinCodecLookup();
94
+ constructor(codecRegistry: CodecRegistry) {
95
+ this.codecRegistry = codecRegistry;
106
96
  }
107
97
 
108
98
  /**
@@ -118,27 +108,6 @@ export class PostgresControlAdapter implements SqlControlAdapter<'postgres'> {
118
108
  */
119
109
  readonly normalizeNativeType = normalizeSchemaNativeType;
120
110
 
121
- /**
122
- * Bridges native `PostgresEnumStorageEntry` IR walks against the Postgres
123
- * introspection shape (`schema.annotations.pg.storageTypes`). Lets
124
- * the family-level schema verifier walk enum types without reaching
125
- * into target-specific annotation layouts itself.
126
- */
127
- readonly resolveExistingEnumValues = (
128
- schema: SqlSchemaIR,
129
- enumType: PostgresEnumStorageEntry,
130
- namespaceId: string,
131
- ): readonly string[] | null => {
132
- const schemaName =
133
- namespaceId === UNBOUND_NAMESPACE_ID
134
- ? (readPostgresSchemaIrAnnotations(schema).schema ?? 'public')
135
- : namespaceId;
136
- return readExistingEnumValues(schema, schemaName, enumType.nativeType);
137
- };
138
-
139
- readonly resolveExistingEnumValuesForContract = (contract: Contract<SqlStorage>) =>
140
- createResolveExistingEnumValues(contract.storage);
141
-
142
111
  bootstrapControlTableQueries(): readonly DdlNode[] {
143
112
  return buildControlTableBootstrapQueries();
144
113
  }
@@ -157,9 +126,46 @@ export class PostgresControlAdapter implements SqlControlAdapter<'postgres'> {
157
126
  */
158
127
  lower(ast: AnyQueryAst | PostgresDdlNode, context: LowererContext<unknown>): LoweredStatement {
159
128
  if (isDdlNode(ast)) {
160
- return renderLoweredDdl(ast);
129
+ throw new Error(
130
+ 'lower() cannot lower DDL: DDL default literals require inline codec encoding, which is async. Use lowerToExecuteRequest().',
131
+ );
132
+ }
133
+ return renderLoweredSql(
134
+ ast,
135
+ blindCast<PostgresContract, 'caller must supply a matching PostgresContract'>(
136
+ context.contract,
137
+ ),
138
+ this.codecRegistry,
139
+ );
140
+ }
141
+
142
+ /**
143
+ * Lower an AST all the way to a driver-ready statement. For DDL nodes,
144
+ * literal column defaults are formatted as inline SQL with proper quoting and
145
+ * `::nativeType` cast suffixes. For query ASTs, params are kept as `$N`
146
+ * placeholders; wire values go in `params`. Does NOT call `this.lower()` —
147
+ * independent implementation.
148
+ */
149
+ async lowerToExecuteRequest(
150
+ ast: AnyQueryAst | PostgresDdlNode,
151
+ context?: LowererContext<unknown>,
152
+ ): Promise<SqlExecuteRequest> {
153
+ if (isDdlNode(ast)) {
154
+ return pgRenderDdlExecuteRequest(
155
+ blindCast<PostgresDdlNode, 'isDdlNode guard'>(ast),
156
+ this.codecRegistry,
157
+ );
161
158
  }
162
- return renderLoweredSql(ast, context.contract as PostgresContract, this.codecLookup);
159
+ const contract = blindCast<PostgresContract, 'Caller must supply matching contract'>(
160
+ context?.contract,
161
+ );
162
+ const lowered = renderLoweredSql(ast, contract, this.codecRegistry);
163
+ const codecRegistry = blindCast<
164
+ ContractCodecRegistry,
165
+ 'framework CodecRegistry: its descriptors materialise SQL codecs; the framework Codec type erases to BaseCodec at this boundary'
166
+ >(this.codecRegistry);
167
+ const params = await encodeControlQueryParams(lowered, ast, codecRegistry);
168
+ return { sql: lowered.sql, params };
163
169
  }
164
170
 
165
171
  /**
@@ -625,19 +631,6 @@ export class PostgresControlAdapter implements SqlControlAdapter<'postgres'> {
625
631
  }
626
632
  }
627
633
 
628
- const mergedStorageTypes: Record<string, PostgresEnumStorageTypeAnnotation> = {};
629
- for (let i = 0; i < perSchema.length; i++) {
630
- const ir = perSchema[i];
631
- const pg = blindCast<
632
- { storageTypes?: Record<string, PostgresEnumStorageTypeAnnotation> } | undefined,
633
- 'pg annotation envelope index slot'
634
- >(ir?.annotations?.['pg'])?.storageTypes;
635
- if (!pg) continue;
636
- for (const [key, value] of Object.entries(pg)) {
637
- mergedStorageTypes[key] = value;
638
- }
639
- }
640
-
641
634
  const firstAnnotations = perSchema[0]?.annotations;
642
635
  const firstPg =
643
636
  blindCast<Record<string, unknown> | undefined, 'pg annotation envelope index slot'>(
@@ -647,13 +640,7 @@ export class PostgresControlAdapter implements SqlControlAdapter<'postgres'> {
647
640
  tables: mergedTables,
648
641
  ...ifDefined('annotations', {
649
642
  ...firstAnnotations,
650
- pg: {
651
- ...firstPg,
652
- ...ifDefined(
653
- 'storageTypes',
654
- Object.keys(mergedStorageTypes).length > 0 ? mergedStorageTypes : undefined,
655
- ),
656
- },
643
+ pg: { ...firstPg },
657
644
  }),
658
645
  };
659
646
  }
@@ -1093,20 +1080,22 @@ export class PostgresControlAdapter implements SqlControlAdapter<'postgres'> {
1093
1080
  };
1094
1081
  }
1095
1082
 
1096
- const rawStorageTypes = await introspectPostgresEnumTypes({ driver, schemaName: schema });
1097
- const storageTypes: Record<string, PostgresEnumStorageTypeAnnotation> = {};
1098
- for (const [typeName, annotation] of Object.entries(rawStorageTypes)) {
1099
- storageTypes[enumStorageCompoundKey(schema, typeName)] = annotation;
1100
- }
1083
+ const nativeEnumResult = await driver.query<{ typname: string }>(
1084
+ `SELECT t.typname
1085
+ FROM pg_catalog.pg_type t
1086
+ JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
1087
+ WHERE t.typtype = 'e'
1088
+ AND n.nspname = $1
1089
+ ORDER BY t.typname`,
1090
+ [schema],
1091
+ );
1092
+ const nativeEnumTypeNames = nativeEnumResult.rows.map((r) => r.typname);
1101
1093
 
1102
1094
  const annotations = {
1103
1095
  pg: {
1104
1096
  schema,
1105
1097
  version: await this.getPostgresVersion(driver),
1106
- ...ifDefined(
1107
- 'storageTypes',
1108
- Object.keys(storageTypes).length > 0 ? storageTypes : undefined,
1109
- ),
1098
+ ...(nativeEnumTypeNames.length > 0 && { nativeEnumTypeNames }),
1110
1099
  },
1111
1100
  };
1112
1101
 
@@ -1368,3 +1357,189 @@ function extractQuotedLiterals(listBody: string): readonly string[] | undefined
1368
1357
  const values = [...listBody.matchAll(pattern)].map((m) => (m[1] ?? '').replace(/''/g, "'"));
1369
1358
  return values.length > 0 ? values : undefined;
1370
1359
  }
1360
+
1361
+ // ---------------------------------------------------------------------------
1362
+ // pgRenderDdlExecuteRequest — independent DDL walker for lowerToExecuteRequest
1363
+ // ---------------------------------------------------------------------------
1364
+
1365
+ function pgIsTextLikeNativeType(nativeType: string): boolean {
1366
+ return (
1367
+ nativeType === 'text' ||
1368
+ nativeType === 'varchar' ||
1369
+ nativeType.startsWith('varchar(') ||
1370
+ nativeType === 'character varying' ||
1371
+ nativeType.startsWith('character varying(') ||
1372
+ nativeType === 'char' ||
1373
+ nativeType.startsWith('char(') ||
1374
+ nativeType === 'character' ||
1375
+ nativeType.startsWith('character(')
1376
+ );
1377
+ }
1378
+
1379
+ function pgInlineLiteral(wire: unknown, nativeType: string): string {
1380
+ if (wire === null) return 'NULL';
1381
+ if (typeof wire === 'boolean') return wire ? 'true' : 'false';
1382
+ if (typeof wire === 'number') {
1383
+ if (!Number.isFinite(wire)) {
1384
+ throw new Error(
1385
+ `pgRenderDdlExecuteRequest: non-finite number wire value ${String(wire)} cannot be emitted as a DEFAULT literal for native type "${nativeType}"`,
1386
+ );
1387
+ }
1388
+ return String(wire);
1389
+ }
1390
+ if (typeof wire === 'bigint') return String(wire);
1391
+ if (wire instanceof Date) {
1392
+ if (Number.isNaN(wire.getTime())) {
1393
+ throw new Error(
1394
+ `pgRenderDdlExecuteRequest: invalid Date value cannot be emitted as a DEFAULT literal for native type "${nativeType}"`,
1395
+ );
1396
+ }
1397
+ const quoted = `'${escapeLiteral(wire.toISOString())}'`;
1398
+ return pgIsTextLikeNativeType(nativeType) ? quoted : `${quoted}::${nativeType}`;
1399
+ }
1400
+ if (typeof wire === 'string') {
1401
+ const quoted = `'${escapeLiteral(wire)}'`;
1402
+ return pgIsTextLikeNativeType(nativeType) ? quoted : `${quoted}::${nativeType}`;
1403
+ }
1404
+ if (wire instanceof Uint8Array) {
1405
+ const hex = Array.from(wire)
1406
+ .map((b) => b.toString(16).padStart(2, '0'))
1407
+ .join('');
1408
+ return `'\\x${hex}'::${nativeType}`;
1409
+ }
1410
+ if (typeof wire === 'object') {
1411
+ const quoted = `'${escapeLiteral(JSON.stringify(wire))}'`;
1412
+ return `${quoted}::${nativeType}`;
1413
+ }
1414
+ throw new Error(
1415
+ `pgRenderDdlExecuteRequest: unexpected wire type "${typeof wire}" for native type "${nativeType}"`,
1416
+ );
1417
+ }
1418
+
1419
+ async function pgRenderDdlColumnDefault(
1420
+ def: LiteralColumnDefault | FunctionColumnDefault,
1421
+ nativeType: string,
1422
+ codecLookup: CodecLookup,
1423
+ codecRef: CodecRef | undefined,
1424
+ ): Promise<string> {
1425
+ if (def.kind === 'function') {
1426
+ if (def.expression === 'autoincrement()') return '';
1427
+ return `DEFAULT (${def.expression})`;
1428
+ }
1429
+ if (codecRef !== undefined) {
1430
+ const codec = codecLookup.get(codecRef.codecId);
1431
+ if (codec !== undefined) {
1432
+ const wire = await codec.encode(def.value, {});
1433
+ return `DEFAULT ${pgInlineLiteral(wire, nativeType)}`;
1434
+ }
1435
+ }
1436
+ // Fallback: codec-less literal defaults follow RawSqlLiteral wire-scalar semantics.
1437
+ return `DEFAULT ${pgInlineLiteral(def.value, nativeType)}`;
1438
+ }
1439
+
1440
+ async function pgRenderDdlColumn(column: DdlColumn, codecLookup: CodecLookup): Promise<string> {
1441
+ const parts = [quoteIdentifier(column.name), column.type];
1442
+ if (column.default) {
1443
+ const clause = await pgRenderDdlColumnDefault(
1444
+ column.default,
1445
+ column.type,
1446
+ codecLookup,
1447
+ column.codecRef,
1448
+ );
1449
+ if (clause.length > 0) parts.push(clause);
1450
+ }
1451
+ if (column.notNull) parts.push('NOT NULL');
1452
+ if (column.primaryKey) parts.push('PRIMARY KEY');
1453
+ return parts.join(' ');
1454
+ }
1455
+
1456
+ function pgRenderDdlConstraint(constraint: DdlTableConstraint): string {
1457
+ if (constraint.kind === 'primary-key') {
1458
+ const cols = constraint.columns.map(quoteIdentifier).join(', ');
1459
+ if (constraint.name !== undefined) {
1460
+ return `CONSTRAINT ${quoteIdentifier(constraint.name)} PRIMARY KEY (${cols})`;
1461
+ }
1462
+ return `PRIMARY KEY (${cols})`;
1463
+ }
1464
+ if (constraint.kind === 'foreign-key') {
1465
+ const cols = constraint.columns.map(quoteIdentifier).join(', ');
1466
+ const refTable = constraint.refTable.split('.').map(quoteIdentifier).join('.');
1467
+ const refCols = constraint.refColumns.map(quoteIdentifier).join(', ');
1468
+ let sql = `FOREIGN KEY (${cols}) REFERENCES ${refTable} (${refCols})`;
1469
+ if (constraint.onDelete !== undefined) {
1470
+ sql += ` ON DELETE ${REFERENTIAL_ACTION_SQL[constraint.onDelete]}`;
1471
+ }
1472
+ if (constraint.onUpdate !== undefined) {
1473
+ sql += ` ON UPDATE ${REFERENTIAL_ACTION_SQL[constraint.onUpdate]}`;
1474
+ }
1475
+ if (constraint.name !== undefined) {
1476
+ sql = `CONSTRAINT ${quoteIdentifier(constraint.name)} ${sql}`;
1477
+ }
1478
+ return sql;
1479
+ }
1480
+ const cols = constraint.columns.map(quoteIdentifier).join(', ');
1481
+ if (constraint.name !== undefined) {
1482
+ return `CONSTRAINT ${quoteIdentifier(constraint.name)} UNIQUE (${cols})`;
1483
+ }
1484
+ return `UNIQUE (${cols})`;
1485
+ }
1486
+
1487
+ async function pgRenderCreateTable(
1488
+ node: PostgresCreateTable,
1489
+ codecLookup: CodecLookup,
1490
+ ): Promise<SqlExecuteRequest> {
1491
+ const ifNotExists = node.ifNotExists ? 'IF NOT EXISTS ' : '';
1492
+ const tableRef = node.schema
1493
+ ? `${quoteIdentifier(node.schema)}.${quoteIdentifier(node.table)}`
1494
+ : quoteIdentifier(node.table);
1495
+ const columnDefs = await Promise.all(
1496
+ node.columns.map((col) => pgRenderDdlColumn(col, codecLookup)),
1497
+ );
1498
+ const constraintDefs =
1499
+ node.constraints !== undefined ? node.constraints.map(pgRenderDdlConstraint) : [];
1500
+ const allDefs = [...columnDefs, ...constraintDefs].join(',\n ');
1501
+ return {
1502
+ sql: `CREATE TABLE ${ifNotExists}${tableRef} (\n ${allDefs}\n)`,
1503
+ params: [],
1504
+ };
1505
+ }
1506
+
1507
+ function pgRenderCreateSchema(node: PostgresCreateSchema): SqlExecuteRequest {
1508
+ const ifNotExists = node.ifNotExists ? 'IF NOT EXISTS ' : '';
1509
+ return {
1510
+ sql: `CREATE SCHEMA ${ifNotExists}${quoteIdentifier(node.schema)}`,
1511
+ params: [],
1512
+ };
1513
+ }
1514
+
1515
+ async function pgRenderAlterTable(
1516
+ node: PostgresAlterTable,
1517
+ codecLookup: CodecLookup,
1518
+ ): Promise<SqlExecuteRequest> {
1519
+ const tableRef = node.schema
1520
+ ? `${quoteIdentifier(node.schema)}.${quoteIdentifier(node.table)}`
1521
+ : quoteIdentifier(node.table);
1522
+ const actionVisitor: AlterTableActionVisitor<Promise<string>> = {
1523
+ async addColumn(action: AddColumnAction): Promise<string> {
1524
+ const colFragment = await pgRenderDdlColumn(action.column, codecLookup);
1525
+ return `ADD COLUMN ${colFragment}`;
1526
+ },
1527
+ };
1528
+ const actionSqls = await Promise.all(node.actions.map((a) => a.accept(actionVisitor)));
1529
+ return {
1530
+ sql: `ALTER TABLE ${tableRef} ${actionSqls.join(', ')}`,
1531
+ params: [],
1532
+ };
1533
+ }
1534
+
1535
+ async function pgRenderDdlExecuteRequest(
1536
+ ast: PostgresDdlNode,
1537
+ codecLookup: CodecLookup,
1538
+ ): Promise<SqlExecuteRequest> {
1539
+ const visitor = {
1540
+ createTable: (node: PostgresCreateTable) => pgRenderCreateTable(node, codecLookup),
1541
+ createSchema: (node: PostgresCreateSchema) => Promise.resolve(pgRenderCreateSchema(node)),
1542
+ alterTable: (node: PostgresAlterTable) => pgRenderAlterTable(node, codecLookup),
1543
+ };
1544
+ return ast.accept(visitor);
1545
+ }
@@ -0,0 +1,25 @@
1
+ import type {
2
+ AnyQueryAst,
3
+ ContractCodecRegistry,
4
+ LoweredStatement,
5
+ } from '@prisma-next/sql-relational-core/ast';
6
+ import {
7
+ createAstCodecRegistry,
8
+ deriveParamMetadata,
9
+ encodeParamsWithMetadata,
10
+ } from '@prisma-next/sql-runtime';
11
+ import { postgresCodecRegistry } from '@prisma-next/target-postgres/codecs';
12
+
13
+ export const CONTROL_CODECS = createAstCodecRegistry(postgresCodecRegistry);
14
+
15
+ export async function encodeControlQueryParams(
16
+ lowered: LoweredStatement,
17
+ ast: AnyQueryAst,
18
+ codecs: ContractCodecRegistry = CONTROL_CODECS,
19
+ ): Promise<readonly unknown[]> {
20
+ const values = lowered.params.map((slot) => {
21
+ if (slot.kind === 'literal') return slot.value;
22
+ throw new Error(`control query lowered to a bind slot '${slot.name}', which is unsupported`);
23
+ });
24
+ return encodeParamsWithMetadata(values, deriveParamMetadata(ast), {}, codecs);
25
+ }