@prisma-next/adapter-postgres 0.13.0-dev.15 → 0.13.0-dev.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-u3NV_jRl.mjs → adapter-C1mmw92x.mjs} +3 -3
- package/dist/adapter-C1mmw92x.mjs.map +1 -0
- package/dist/adapter.d.mts.map +1 -1
- package/dist/adapter.mjs +1 -1
- package/dist/{control-adapter-Xq5__09s.mjs → control-adapter-CkTZadCF.mjs} +112 -83
- package/dist/control-adapter-CkTZadCF.mjs.map +1 -0
- package/dist/control.d.mts +9 -1
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +1 -1
- package/dist/runtime.mjs +1 -1
- package/package.json +22 -22
- package/src/core/adapter.ts +3 -2
- package/src/core/control-adapter.ts +207 -3
- package/src/core/control-codecs.ts +25 -0
- package/src/core/marker-ledger.ts +2 -18
- package/dist/adapter-u3NV_jRl.mjs.map +0 -1
- package/dist/control-adapter-Xq5__09s.mjs.map +0 -1
- package/src/core/ddl-renderer.ts +0 -155
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as renderLoweredSql, r as createPostgresBuiltinCodecLookup, t as PostgresControlAdapter } from "./control-adapter-CkTZadCF.mjs";
|
|
2
2
|
import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
|
|
3
3
|
import { isDdlNode } from "@prisma-next/sql-relational-core/ast";
|
|
4
4
|
//#region src/core/adapter.ts
|
|
@@ -41,7 +41,7 @@ var PostgresAdapterImpl = class {
|
|
|
41
41
|
});
|
|
42
42
|
}
|
|
43
43
|
lower(ast, context) {
|
|
44
|
-
if (isDdlNode(ast))
|
|
44
|
+
if (isDdlNode(ast)) throw new Error("lower() does not lower DDL on the runtime adapter — DDL lowering is a control-plane concern handled by the control adapter.");
|
|
45
45
|
return renderLoweredSql(ast, context.contract, this.codecLookup);
|
|
46
46
|
}
|
|
47
47
|
};
|
|
@@ -62,4 +62,4 @@ function createPostgresAdapter(options) {
|
|
|
62
62
|
//#endregion
|
|
63
63
|
export { postgresRawCodecInferer as n, createPostgresAdapter as t };
|
|
64
64
|
|
|
65
|
-
//# sourceMappingURL=adapter-
|
|
65
|
+
//# sourceMappingURL=adapter-C1mmw92x.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter-C1mmw92x.mjs","names":[],"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { CodecLookup } from '@prisma-next/framework-components/codec';\nimport { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport type {\n Adapter,\n AdapterProfile,\n AnyQueryAst,\n LowererContext,\n RawSqlLiteral,\n SqlQueryable,\n} from '@prisma-next/sql-relational-core/ast';\nimport { isDdlNode } from '@prisma-next/sql-relational-core/ast';\nimport type { RawCodecInferer } from '@prisma-next/sql-relational-core/expression';\nimport type { PostgresDdlNode } from '@prisma-next/target-postgres/ddl';\nimport { createPostgresBuiltinCodecLookup } from './codec-lookup';\nimport { PostgresControlAdapter } from './control-adapter';\nimport { renderLoweredSql } from './sql-renderer';\nimport type { PostgresAdapterOptions, PostgresContract, PostgresLoweredStatement } from './types';\n\nconst defaultCapabilities = Object.freeze({\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\nclass PostgresAdapterImpl\n implements Adapter<AnyQueryAst, PostgresContract, PostgresLoweredStatement>\n{\n // These fields make the adapter instance structurally compatible with RuntimeAdapterInstance<'sql', 'postgres'> without introducing a runtime-plane dependency.\n readonly familyId = 'sql' as const;\n readonly targetId = 'postgres' as const;\n\n readonly profile: AdapterProfile<'postgres'>;\n private readonly codecLookup: CodecLookup;\n\n constructor(options?: PostgresAdapterOptions) {\n this.codecLookup = options?.codecLookup ?? createPostgresBuiltinCodecLookup();\n const controlAdapter = new PostgresControlAdapter(this.codecLookup);\n this.profile = Object.freeze({\n id: options?.profileId ?? 'postgres/default@1',\n target: 'postgres',\n capabilities: defaultCapabilities,\n readMarker: (queryable: SqlQueryable) =>\n controlAdapter.readMarkerDiscriminated(\n {\n familyId: 'sql',\n targetId: 'postgres',\n query: async <Row = Record<string, unknown>>(\n sql: string,\n params?: readonly unknown[],\n ) => {\n const result = await queryable.query<Row>(sql, params);\n return { rows: [...result.rows] };\n },\n close: async () => {},\n },\n APP_SPACE_ID,\n ),\n });\n }\n\n lower(\n ast: AnyQueryAst | PostgresDdlNode,\n context: LowererContext<PostgresContract>,\n ): PostgresLoweredStatement {\n if (isDdlNode(ast)) {\n throw new Error(\n 'lower() does not lower DDL on the runtime adapter — DDL lowering is a control-plane concern handled by the control adapter.',\n );\n }\n return renderLoweredSql(ast, context.contract, this.codecLookup);\n }\n}\n\n/** Codec-id lookup for bare-literal interpolations used by `fns.raw` on a postgres client. Contributed as the descriptor's static `rawCodecInferer` slot. */\nexport const postgresRawCodecInferer: RawCodecInferer = {\n inferCodec(value: RawSqlLiteral): string {\n switch (typeof value) {\n case 'number':\n return Number.isSafeInteger(value) && value % 1 === 0 ? 'pg/int4' : 'pg/float8';\n case 'bigint':\n return 'pg/int8';\n case 'string':\n return 'pg/text';\n case 'boolean':\n return 'pg/bool';\n case 'object':\n if (value instanceof Uint8Array) return 'pg/bytea';\n }\n throw new Error(\n 'unsupported JS value type for raw-SQL interpolation: wrap this value in `param(...)` with an explicit codec',\n );\n },\n};\n\nexport function createPostgresAdapter(options?: PostgresAdapterOptions) {\n return Object.freeze(new PostgresAdapterImpl(options));\n}\n"],"mappings":";;;;AAkBA,MAAM,sBAAsB,OAAO,OAAO;CACxC,UAAU;EACR,SAAS;EACT,OAAO;EACP,SAAS;EACT,SAAS;EACT,WAAW;EACX,YAAY;CACd;CACA,KAAK;EACH,OAAO;EACP,WAAW;EACX,iBAAiB;EACjB,SAAS;CACX;AACF,CAAC;AAED,IAAM,sBAAN,MAEA;CAEE,WAAoB;CACpB,WAAoB;CAEpB;CACA;CAEA,YAAY,SAAkC;EAC5C,KAAK,cAAc,SAAS,eAAe,iCAAiC;EAC5E,MAAM,iBAAiB,IAAI,uBAAuB,KAAK,WAAW;EAClE,KAAK,UAAU,OAAO,OAAO;GAC3B,IAAI,SAAS,aAAa;GAC1B,QAAQ;GACR,cAAc;GACd,aAAa,cACX,eAAe,wBACb;IACE,UAAU;IACV,UAAU;IACV,OAAO,OACL,KACA,WACG;KAEH,OAAO,EAAE,MAAM,CAAC,IAAG,MADE,UAAU,MAAW,KAAK,MAAM,EAAA,CAC3B,IAAI,EAAE;IAClC;IACA,OAAO,YAAY,CAAC;GACtB,GACA,YACF;EACJ,CAAC;CACH;CAEA,MACE,KACA,SAC0B;EAC1B,IAAI,UAAU,GAAG,GACf,MAAM,IAAI,MACR,6HACF;EAEF,OAAO,iBAAiB,KAAK,QAAQ,UAAU,KAAK,WAAW;CACjE;AACF;;AAGA,MAAa,0BAA2C,EACtD,WAAW,OAA8B;CACvC,QAAQ,OAAO,OAAf;EACE,KAAK,UACH,OAAO,OAAO,cAAc,KAAK,KAAK,QAAQ,MAAM,IAAI,YAAY;EACtE,KAAK,UACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,UACH,IAAI,iBAAiB,YAAY,OAAO;CAC5C;CACA,MAAM,IAAI,MACR,6GACF;AACF,EACF;AAEA,SAAgB,sBAAsB,SAAkC;CACtE,OAAO,OAAO,OAAO,IAAI,oBAAoB,OAAO,CAAC;AACvD"}
|
package/dist/adapter.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.d.mts","names":[],"sources":["../src/core/adapter.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"adapter.d.mts","names":[],"sources":["../src/core/adapter.ts"],"mappings":";;;;;;cAmCM,mBAAA,YACO,OAAA,CAAQ,WAAA,EAAa,gBAAA,EAAkB,wBAAA;EAAA,SAGzC,QAAA;EAAA,SACA,QAAA;EAAA,SAEA,OAAA,EAAS,cAAA;EAAA,iBACD,WAAA;cAEL,OAAA,GAAU,sBAAA;EA0BtB,KAAA,CACE,GAAA,EAAK,WAAA,GAAc,eAAA,EACnB,OAAA,EAAS,cAAA,CAAe,gBAAA,IACvB,wBAAA;AAAA;;cAWQ,uBAAA,EAAyB,eAkBrC;AAAA,iBAEe,qBAAA,CAAsB,OAAA,GAAU,sBAAA,GAAsB,QAAA,CAAA,mBAAA"}
|
package/dist/adapter.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as postgresRawCodecInferer, t as createPostgresAdapter } from "./adapter-
|
|
1
|
+
import { n as postgresRawCodecInferer, t as createPostgresAdapter } from "./adapter-C1mmw92x.mjs";
|
|
2
2
|
export { createPostgresAdapter, postgresRawCodecInferer };
|
|
@@ -4,16 +4,16 @@ import { postgresCodecRegistry } from "@prisma-next/target-postgres/codecs";
|
|
|
4
4
|
import { parseMarkerRowSafely, rethrowMarkerReadError, withMarkerReadErrorHandling } from "@prisma-next/errors/execution";
|
|
5
5
|
import { parseContractMarkerRow } from "@prisma-next/family-sql/verify";
|
|
6
6
|
import { UNBOUND_NAMESPACE_ID } from "@prisma-next/framework-components/ir";
|
|
7
|
+
import { REFERENTIAL_ACTION_SQL } from "@prisma-next/sql-contract/referential-action-sql";
|
|
7
8
|
import { PostgresTableSource, buildControlTableBootstrapQueries, buildSignMarkerBootstrapQueries, int4, int8, jsonb, pgTable, text, textArray, timestamptz } from "@prisma-next/target-postgres/contract-free";
|
|
8
9
|
import { parsePostgresDefault } from "@prisma-next/target-postgres/default-normalizer";
|
|
9
10
|
import { createResolveExistingEnumValues, readExistingEnumValues, readPostgresSchemaIrAnnotations } from "@prisma-next/target-postgres/enum-planning";
|
|
10
11
|
import { normalizeSchemaNativeType } from "@prisma-next/target-postgres/native-type-normalizer";
|
|
12
|
+
import { escapeLiteral, quoteIdentifier } from "@prisma-next/target-postgres/sql-utils";
|
|
11
13
|
import { blindCast } from "@prisma-next/utils/casts";
|
|
12
14
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
13
|
-
import { REFERENTIAL_ACTION_SQL } from "@prisma-next/sql-contract/referential-action-sql";
|
|
14
|
-
import { escapeLiteral, quoteIdentifier } from "@prisma-next/target-postgres/sql-utils";
|
|
15
|
-
import { PG_ENUM_CODEC_ID, PG_TIMESTAMPTZ_CODEC_ID } from "@prisma-next/target-postgres/codec-ids";
|
|
16
15
|
import { createAstCodecRegistry, deriveParamMetadata, encodeParamsWithMetadata } from "@prisma-next/sql-runtime";
|
|
16
|
+
import { PG_ENUM_CODEC_ID, PG_TIMESTAMPTZ_CODEC_ID } from "@prisma-next/target-postgres/codec-ids";
|
|
17
17
|
import { runtimeError } from "@prisma-next/framework-components/runtime";
|
|
18
18
|
//#region src/core/codec-lookup.ts
|
|
19
19
|
/**
|
|
@@ -36,78 +36,13 @@ function ledgerOriginFromStored(originCoreHash) {
|
|
|
36
36
|
return originCoreHash;
|
|
37
37
|
}
|
|
38
38
|
//#endregion
|
|
39
|
-
//#region src/core/
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
return `PRIMARY KEY (${cols})`;
|
|
47
|
-
}
|
|
48
|
-
function renderForeignKeyConstraint(constraint) {
|
|
49
|
-
const cols = constraint.columns.map(quoteIdentifier).join(", ");
|
|
50
|
-
const refCols = constraint.refColumns.map(quoteIdentifier).join(", ");
|
|
51
|
-
let sql = `FOREIGN KEY (${cols}) REFERENCES ${quoteQualifiedIdentifier(constraint.refTable)} (${refCols})`;
|
|
52
|
-
if (constraint.onDelete !== void 0) sql += ` ON DELETE ${REFERENTIAL_ACTION_SQL[constraint.onDelete]}`;
|
|
53
|
-
if (constraint.onUpdate !== void 0) sql += ` ON UPDATE ${REFERENTIAL_ACTION_SQL[constraint.onUpdate]}`;
|
|
54
|
-
if (constraint.name !== void 0) sql = `CONSTRAINT ${quoteIdentifier(constraint.name)} ${sql}`;
|
|
55
|
-
return sql;
|
|
56
|
-
}
|
|
57
|
-
function renderUniqueConstraint(constraint) {
|
|
58
|
-
const cols = constraint.columns.map(quoteIdentifier).join(", ");
|
|
59
|
-
if (constraint.name !== void 0) return `CONSTRAINT ${quoteIdentifier(constraint.name)} UNIQUE (${cols})`;
|
|
60
|
-
return `UNIQUE (${cols})`;
|
|
61
|
-
}
|
|
62
|
-
function renderTableConstraint(constraint) {
|
|
63
|
-
switch (constraint.kind) {
|
|
64
|
-
case "primary-key": return renderPrimaryKeyConstraint(constraint);
|
|
65
|
-
case "foreign-key": return renderForeignKeyConstraint(constraint);
|
|
66
|
-
case "unique": return renderUniqueConstraint(constraint);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
var PostgresDdlVisitorImpl = class {
|
|
70
|
-
createTable(node) {
|
|
71
|
-
const ifNotExists = node.ifNotExists ? "IF NOT EXISTS " : "";
|
|
72
|
-
const tableRef = node.schema ? `${quoteIdentifier(node.schema)}.${quoteIdentifier(node.table)}` : quoteIdentifier(node.table);
|
|
73
|
-
const columnDefs = node.columns.map((column) => renderColumn$1(column));
|
|
74
|
-
const constraintDefs = node.constraints !== void 0 ? node.constraints.map(renderTableConstraint) : [];
|
|
75
|
-
return `CREATE TABLE ${ifNotExists}${tableRef} (\n ${[...columnDefs, ...constraintDefs].join(",\n ")}\n)`;
|
|
76
|
-
}
|
|
77
|
-
createSchema(node) {
|
|
78
|
-
return `CREATE SCHEMA ${node.ifNotExists ? "IF NOT EXISTS " : ""}${quoteIdentifier(node.schema)}`;
|
|
79
|
-
}
|
|
80
|
-
};
|
|
81
|
-
function isTextLikeNativeType(nativeType) {
|
|
82
|
-
return nativeType === "text" || nativeType === "varchar" || nativeType.startsWith("varchar(") || nativeType === "character varying" || nativeType.startsWith("character varying(") || nativeType === "char" || nativeType.startsWith("char(") || nativeType === "character" || nativeType.startsWith("character(");
|
|
83
|
-
}
|
|
84
|
-
const defaultVisitor = {
|
|
85
|
-
literal(node, ctx) {
|
|
86
|
-
const { value } = node;
|
|
87
|
-
if (typeof value === "number" || typeof value === "boolean") return `DEFAULT ${String(value)}`;
|
|
88
|
-
if (value === null) return "DEFAULT NULL";
|
|
89
|
-
const literal = `'${escapeLiteral(typeof value === "string" ? value : JSON.stringify(value))}'`;
|
|
90
|
-
return isTextLikeNativeType(ctx.nativeType) ? `DEFAULT ${literal}` : `DEFAULT ${literal}::${ctx.nativeType}`;
|
|
91
|
-
},
|
|
92
|
-
function(node, _ctx) {
|
|
93
|
-
if (node.expression === "autoincrement()") return "";
|
|
94
|
-
return `DEFAULT (${node.expression})`;
|
|
95
|
-
}
|
|
96
|
-
};
|
|
97
|
-
function renderColumn$1(column) {
|
|
98
|
-
const parts = [quoteIdentifier(column.name), column.type];
|
|
99
|
-
if (column.notNull) parts.push("NOT NULL");
|
|
100
|
-
if (column.primaryKey) parts.push("PRIMARY KEY");
|
|
101
|
-
const defaultClause = column.default ? column.default.accept(defaultVisitor, { nativeType: column.type }) : "";
|
|
102
|
-
if (defaultClause.length > 0) parts.push(defaultClause);
|
|
103
|
-
return parts.join(" ");
|
|
104
|
-
}
|
|
105
|
-
function renderLoweredDdl(ast) {
|
|
106
|
-
const sql = ast.accept(new PostgresDdlVisitorImpl());
|
|
107
|
-
return Object.freeze({
|
|
108
|
-
sql,
|
|
109
|
-
params: Object.freeze([])
|
|
110
|
-
});
|
|
39
|
+
//#region src/core/control-codecs.ts
|
|
40
|
+
const CONTROL_CODECS = createAstCodecRegistry(postgresCodecRegistry);
|
|
41
|
+
async function encodeControlQueryParams(lowered, ast, codecs = CONTROL_CODECS) {
|
|
42
|
+
return encodeParamsWithMetadata(lowered.params.map((slot) => {
|
|
43
|
+
if (slot.kind === "literal") return slot.value;
|
|
44
|
+
throw new Error(`control query lowered to a bind slot '${slot.name}', which is unsupported`);
|
|
45
|
+
}), deriveParamMetadata(ast), {}, codecs);
|
|
111
46
|
}
|
|
112
47
|
//#endregion
|
|
113
48
|
//#region src/core/enum-control-hooks.ts
|
|
@@ -202,7 +137,6 @@ async function introspectPostgresEnumTypes(options) {
|
|
|
202
137
|
}
|
|
203
138
|
//#endregion
|
|
204
139
|
//#region src/core/marker-ledger.ts
|
|
205
|
-
const CONTROL_CODECS = createAstCodecRegistry(postgresCodecRegistry);
|
|
206
140
|
const marker = pgTable({
|
|
207
141
|
name: "marker",
|
|
208
142
|
schema: "prisma_contract"
|
|
@@ -269,10 +203,7 @@ function mergeInvariants(current, incoming) {
|
|
|
269
203
|
}
|
|
270
204
|
async function execute(lower, driver, query) {
|
|
271
205
|
const lowered = lower(query);
|
|
272
|
-
const encoded = await
|
|
273
|
-
if (slot.kind === "literal") return slot.value;
|
|
274
|
-
throw new Error("Postgres control DML lowered to a bind parameter, which is unsupported");
|
|
275
|
-
}), deriveParamMetadata(query), {}, CONTROL_CODECS);
|
|
206
|
+
const encoded = await encodeControlQueryParams(lowered, query);
|
|
276
207
|
return (await driver.query(lowered.sql, encoded)).rows;
|
|
277
208
|
}
|
|
278
209
|
//#endregion
|
|
@@ -848,10 +779,26 @@ var PostgresControlAdapter = class {
|
|
|
848
779
|
* without instantiating the runtime adapter.
|
|
849
780
|
*/
|
|
850
781
|
lower(ast, context) {
|
|
851
|
-
if (isDdlNode(ast))
|
|
782
|
+
if (isDdlNode(ast)) throw new Error("lower() cannot lower DDL: DDL default literals require inline codec encoding, which is async. Use lowerToExecuteRequest().");
|
|
852
783
|
return renderLoweredSql(ast, context.contract, this.codecLookup);
|
|
853
784
|
}
|
|
854
785
|
/**
|
|
786
|
+
* Lower an AST all the way to a driver-ready statement. For DDL nodes,
|
|
787
|
+
* literal column defaults are formatted as inline SQL with proper quoting and
|
|
788
|
+
* `::nativeType` cast suffixes. For query ASTs, params are kept as `$N`
|
|
789
|
+
* placeholders; wire values go in `params`. Does NOT call `this.lower()` —
|
|
790
|
+
* independent implementation.
|
|
791
|
+
*/
|
|
792
|
+
async lowerToExecuteRequest(ast, context) {
|
|
793
|
+
if (isDdlNode(ast)) return pgRenderDdlExecuteRequest(blindCast(ast), this.codecLookup);
|
|
794
|
+
const lowered = renderLoweredSql(ast, blindCast(context?.contract), this.codecLookup);
|
|
795
|
+
const params = await encodeControlQueryParams(lowered, ast);
|
|
796
|
+
return {
|
|
797
|
+
sql: lowered.sql,
|
|
798
|
+
params
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
855
802
|
* Reads the contract marker from `prisma_contract.marker`. Probes
|
|
856
803
|
* `information_schema.tables` first so a fresh database (where the
|
|
857
804
|
* `prisma_contract` schema doesn't yet exist) returns `null` instead of a
|
|
@@ -1545,7 +1492,89 @@ function extractQuotedLiterals(listBody) {
|
|
|
1545
1492
|
const values = [...listBody.matchAll(/'((?:[^'\\]|\\.|'')*)'/g)].map((m) => (m[1] ?? "").replace(/''/g, "'"));
|
|
1546
1493
|
return values.length > 0 ? values : void 0;
|
|
1547
1494
|
}
|
|
1495
|
+
function pgIsTextLikeNativeType(nativeType) {
|
|
1496
|
+
return nativeType === "text" || nativeType === "varchar" || nativeType.startsWith("varchar(") || nativeType === "character varying" || nativeType.startsWith("character varying(") || nativeType === "char" || nativeType.startsWith("char(") || nativeType === "character" || nativeType.startsWith("character(");
|
|
1497
|
+
}
|
|
1498
|
+
function pgInlineLiteral(wire, nativeType) {
|
|
1499
|
+
if (wire === null) return "NULL";
|
|
1500
|
+
if (typeof wire === "boolean") return wire ? "true" : "false";
|
|
1501
|
+
if (typeof wire === "number") {
|
|
1502
|
+
if (!Number.isFinite(wire)) throw new Error(`pgRenderDdlExecuteRequest: non-finite number wire value ${String(wire)} cannot be emitted as a DEFAULT literal for native type "${nativeType}"`);
|
|
1503
|
+
return String(wire);
|
|
1504
|
+
}
|
|
1505
|
+
if (typeof wire === "bigint") return String(wire);
|
|
1506
|
+
if (wire instanceof Date) {
|
|
1507
|
+
if (Number.isNaN(wire.getTime())) throw new Error(`pgRenderDdlExecuteRequest: invalid Date value cannot be emitted as a DEFAULT literal for native type "${nativeType}"`);
|
|
1508
|
+
const quoted = `'${escapeLiteral(wire.toISOString())}'`;
|
|
1509
|
+
return pgIsTextLikeNativeType(nativeType) ? quoted : `${quoted}::${nativeType}`;
|
|
1510
|
+
}
|
|
1511
|
+
if (typeof wire === "string") {
|
|
1512
|
+
const quoted = `'${escapeLiteral(wire)}'`;
|
|
1513
|
+
return pgIsTextLikeNativeType(nativeType) ? quoted : `${quoted}::${nativeType}`;
|
|
1514
|
+
}
|
|
1515
|
+
if (wire instanceof Uint8Array) return `'\\x${Array.from(wire).map((b) => b.toString(16).padStart(2, "0")).join("")}'::${nativeType}`;
|
|
1516
|
+
if (typeof wire === "object") return `${`'${escapeLiteral(JSON.stringify(wire))}'`}::${nativeType}`;
|
|
1517
|
+
throw new Error(`pgRenderDdlExecuteRequest: unexpected wire type "${typeof wire}" for native type "${nativeType}"`);
|
|
1518
|
+
}
|
|
1519
|
+
async function pgRenderDdlColumnDefault(def, nativeType, codecLookup, codecRef) {
|
|
1520
|
+
if (def.kind === "function") {
|
|
1521
|
+
if (def.expression === "autoincrement()") return "";
|
|
1522
|
+
return `DEFAULT (${def.expression})`;
|
|
1523
|
+
}
|
|
1524
|
+
if (codecRef !== void 0) {
|
|
1525
|
+
const codec = codecLookup.get(codecRef.codecId);
|
|
1526
|
+
if (codec !== void 0) return `DEFAULT ${pgInlineLiteral(await codec.encode(def.value, {}), nativeType)}`;
|
|
1527
|
+
}
|
|
1528
|
+
return `DEFAULT ${pgInlineLiteral(def.value, nativeType)}`;
|
|
1529
|
+
}
|
|
1530
|
+
async function pgRenderDdlColumn(column, codecLookup) {
|
|
1531
|
+
const parts = [quoteIdentifier(column.name), column.type];
|
|
1532
|
+
if (column.notNull) parts.push("NOT NULL");
|
|
1533
|
+
if (column.primaryKey) parts.push("PRIMARY KEY");
|
|
1534
|
+
if (column.default) {
|
|
1535
|
+
const clause = await pgRenderDdlColumnDefault(column.default, column.type, codecLookup, column.codecRef);
|
|
1536
|
+
if (clause.length > 0) parts.push(clause);
|
|
1537
|
+
}
|
|
1538
|
+
return parts.join(" ");
|
|
1539
|
+
}
|
|
1540
|
+
function pgRenderDdlConstraint(constraint) {
|
|
1541
|
+
if (constraint.kind === "primary-key") {
|
|
1542
|
+
const cols = constraint.columns.map(quoteIdentifier).join(", ");
|
|
1543
|
+
if (constraint.name !== void 0) return `CONSTRAINT ${quoteIdentifier(constraint.name)} PRIMARY KEY (${cols})`;
|
|
1544
|
+
return `PRIMARY KEY (${cols})`;
|
|
1545
|
+
}
|
|
1546
|
+
if (constraint.kind === "foreign-key") {
|
|
1547
|
+
let sql = `FOREIGN KEY (${constraint.columns.map(quoteIdentifier).join(", ")}) REFERENCES ${constraint.refTable.split(".").map(quoteIdentifier).join(".")} (${constraint.refColumns.map(quoteIdentifier).join(", ")})`;
|
|
1548
|
+
if (constraint.onDelete !== void 0) sql += ` ON DELETE ${REFERENTIAL_ACTION_SQL[constraint.onDelete]}`;
|
|
1549
|
+
if (constraint.onUpdate !== void 0) sql += ` ON UPDATE ${REFERENTIAL_ACTION_SQL[constraint.onUpdate]}`;
|
|
1550
|
+
if (constraint.name !== void 0) sql = `CONSTRAINT ${quoteIdentifier(constraint.name)} ${sql}`;
|
|
1551
|
+
return sql;
|
|
1552
|
+
}
|
|
1553
|
+
const cols = constraint.columns.map(quoteIdentifier).join(", ");
|
|
1554
|
+
if (constraint.name !== void 0) return `CONSTRAINT ${quoteIdentifier(constraint.name)} UNIQUE (${cols})`;
|
|
1555
|
+
return `UNIQUE (${cols})`;
|
|
1556
|
+
}
|
|
1557
|
+
async function pgRenderCreateTable(node, codecLookup) {
|
|
1558
|
+
const ifNotExists = node.ifNotExists ? "IF NOT EXISTS " : "";
|
|
1559
|
+
const tableRef = node.schema ? `${quoteIdentifier(node.schema)}.${quoteIdentifier(node.table)}` : quoteIdentifier(node.table);
|
|
1560
|
+
const columnDefs = await Promise.all(node.columns.map((col) => pgRenderDdlColumn(col, codecLookup)));
|
|
1561
|
+
const constraintDefs = node.constraints !== void 0 ? node.constraints.map(pgRenderDdlConstraint) : [];
|
|
1562
|
+
return {
|
|
1563
|
+
sql: `CREATE TABLE ${ifNotExists}${tableRef} (\n ${[...columnDefs, ...constraintDefs].join(",\n ")}\n)`,
|
|
1564
|
+
params: []
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
function pgRenderCreateSchema(node) {
|
|
1568
|
+
return {
|
|
1569
|
+
sql: `CREATE SCHEMA ${node.ifNotExists ? "IF NOT EXISTS " : ""}${quoteIdentifier(node.schema)}`,
|
|
1570
|
+
params: []
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
async function pgRenderDdlExecuteRequest(ast, codecLookup) {
|
|
1574
|
+
if (ast.kind === "create-table") return pgRenderCreateTable(blindCast(ast), codecLookup);
|
|
1575
|
+
return pgRenderCreateSchema(blindCast(ast));
|
|
1576
|
+
}
|
|
1548
1577
|
//#endregion
|
|
1549
|
-
export {
|
|
1578
|
+
export { renderLoweredSql as n, createPostgresBuiltinCodecLookup as r, PostgresControlAdapter as t };
|
|
1550
1579
|
|
|
1551
|
-
//# sourceMappingURL=control-adapter-
|
|
1580
|
+
//# sourceMappingURL=control-adapter-CkTZadCF.mjs.map
|