@prisma-next/adapter-postgres 0.14.0-dev.6 → 0.14.0-dev.61
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-CwkcdpM_.mjs → adapter-Bnsf8eqp.mjs} +4 -3
- package/dist/adapter-Bnsf8eqp.mjs.map +1 -0
- package/dist/adapter.d.mts +1 -1
- package/dist/adapter.d.mts.map +1 -1
- package/dist/adapter.mjs +1 -1
- package/dist/{control-adapter-Dspz5uKp.mjs → control-adapter-DN4MZLIR.mjs} +259 -57
- package/dist/control-adapter-DN4MZLIR.mjs.map +1 -0
- package/dist/control.d.mts +17 -11
- package/dist/control.d.mts.map +1 -1
- package/dist/control.mjs +2 -2
- package/dist/{descriptor-meta-DOgMfoqm.mjs → descriptor-meta-DnWlLrI6.mjs} +3 -2
- package/dist/descriptor-meta-DnWlLrI6.mjs.map +1 -0
- package/dist/runtime.d.mts +1 -1
- package/dist/runtime.mjs +2 -2
- package/dist/runtime.mjs.map +1 -1
- package/dist/{types-KXRwRZU8.d.mts → types-DkGeLfUp.d.mts} +3 -6
- package/dist/types-DkGeLfUp.d.mts.map +1 -0
- package/dist/types.d.mts +1 -1
- package/package.json +23 -22
- package/src/core/adapter.ts +1 -0
- package/src/core/codec-lookup.ts +2 -1
- package/src/core/control-adapter.ts +386 -84
- package/src/core/descriptor-meta.ts +1 -0
- package/src/core/sql-renderer.ts +32 -6
- package/src/core/types.ts +2 -3
- package/src/exports/runtime.ts +2 -5
- package/dist/adapter-CwkcdpM_.mjs.map +0 -1
- package/dist/control-adapter-Dspz5uKp.mjs.map +0 -1
- package/dist/descriptor-meta-DOgMfoqm.mjs.map +0 -1
- package/dist/types-KXRwRZU8.d.mts.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as renderLoweredSql, r as createPostgresBuiltinCodecLookup, t as PostgresControlAdapter } from "./control-adapter-
|
|
1
|
+
import { n as renderLoweredSql, r as createPostgresBuiltinCodecLookup, t as PostgresControlAdapter } from "./control-adapter-DN4MZLIR.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
|
|
@@ -15,7 +15,8 @@ const defaultCapabilities = Object.freeze({
|
|
|
15
15
|
enums: true,
|
|
16
16
|
returning: true,
|
|
17
17
|
defaultInInsert: true,
|
|
18
|
-
lateral: true
|
|
18
|
+
lateral: true,
|
|
19
|
+
scalarList: true
|
|
19
20
|
}
|
|
20
21
|
});
|
|
21
22
|
var PostgresAdapterImpl = class {
|
|
@@ -62,4 +63,4 @@ function createPostgresAdapter(options) {
|
|
|
62
63
|
//#endregion
|
|
63
64
|
export { postgresRawCodecInferer as n, createPostgresAdapter as t };
|
|
64
65
|
|
|
65
|
-
//# sourceMappingURL=adapter-
|
|
66
|
+
//# sourceMappingURL=adapter-Bnsf8eqp.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapter-Bnsf8eqp.mjs","names":[],"sources":["../src/core/adapter.ts"],"sourcesContent":["import type { CodecRegistry } 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 scalarList: 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: CodecRegistry;\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;EACT,YAAY;CACd;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
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as PostgresContract, l as PostgresLoweredStatement, s as PostgresAdapterOptions } from "./types-
|
|
1
|
+
import { c as PostgresContract, l as PostgresLoweredStatement, s as PostgresAdapterOptions } from "./types-DkGeLfUp.mjs";
|
|
2
2
|
import { Adapter, AdapterProfile, AnyQueryAst, LowererContext } from "@prisma-next/sql-relational-core/ast";
|
|
3
3
|
import { RawCodecInferer } from "@prisma-next/sql-relational-core/expression";
|
|
4
4
|
import { PostgresDdlNode } from "@prisma-next/target-postgres/ddl";
|
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":";;;;;;cAoCM,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-Bnsf8eqp.mjs";
|
|
2
2
|
export { createPostgresAdapter, postgresRawCodecInferer };
|
|
@@ -8,7 +8,9 @@ import { REFERENTIAL_ACTION_SQL } from "@prisma-next/sql-contract/referential-ac
|
|
|
8
8
|
import { buildControlTableBootstrapQueries, buildSignMarkerBootstrapQueries, int4, int8, jsonb, pgTable, text, textArray, timestamptz } from "@prisma-next/target-postgres/contract-free";
|
|
9
9
|
import { parsePostgresDefault } from "@prisma-next/target-postgres/default-normalizer";
|
|
10
10
|
import { normalizeSchemaNativeType } from "@prisma-next/target-postgres/native-type-normalizer";
|
|
11
|
+
import { parseRlsPolicyWireName } from "@prisma-next/target-postgres/rls-canonicalize";
|
|
11
12
|
import { escapeLiteral, quoteIdentifier } from "@prisma-next/target-postgres/sql-utils";
|
|
13
|
+
import { PostgresDatabaseSchemaNode, PostgresNamespaceSchemaNode, PostgresPolicySchemaNode, PostgresRoleSchemaNode, PostgresTableSchemaNode } from "@prisma-next/target-postgres/types";
|
|
12
14
|
import { blindCast } from "@prisma-next/utils/casts";
|
|
13
15
|
import { ifDefined } from "@prisma-next/utils/defined";
|
|
14
16
|
import { createAstCodecRegistry, deriveParamMetadata, encodeParamsWithMetadata } from "@prisma-next/sql-runtime";
|
|
@@ -143,15 +145,19 @@ const POSTGRES_INFERRABLE_NATIVE_TYPES = new Set([
|
|
|
143
145
|
"bit",
|
|
144
146
|
"bit varying"
|
|
145
147
|
]);
|
|
146
|
-
function renderTypedParam(index, codecId, codecLookup) {
|
|
148
|
+
function renderTypedParam(index, codecId, codecLookup, many, typeParams) {
|
|
147
149
|
if (codecId === void 0) return `$${index}`;
|
|
148
|
-
const meta = codecLookup.metaFor(codecId);
|
|
150
|
+
const meta = codecLookup.metaFor(codecId, typeParams);
|
|
149
151
|
if (!(codecLookup.get(codecId) !== void 0 || meta !== void 0 || codecLookup.targetTypesFor(codecId) !== void 0)) throw new Error(`Postgres lowering: ParamRef carries codecId "${codecId}" but the assembled codec lookup has no entry for it. This usually indicates a missing extension pack in the runtime stack — register the pack that contributes this codec (e.g. \`extensionPacks: [pgvectorRuntime]\`), or use the codec directly from \`@prisma-next/target-postgres/codecs\` if it's a builtin.`);
|
|
150
152
|
const dbRecord = meta?.db;
|
|
151
153
|
const sqlBlock = isRecord(dbRecord) ? dbRecord["sql"] : void 0;
|
|
152
154
|
const dialectBlock = isRecord(sqlBlock) ? sqlBlock["postgres"] : void 0;
|
|
153
155
|
const nativeType = isRecord(dialectBlock) ? dialectBlock["nativeType"] : void 0;
|
|
154
|
-
if (typeof nativeType === "string"
|
|
156
|
+
if (typeof nativeType === "string") {
|
|
157
|
+
const arraySuffix = many ? "[]" : "";
|
|
158
|
+
if (!POSTGRES_INFERRABLE_NATIVE_TYPES.has(nativeType)) return `$${index}::${nativeType}${arraySuffix}`;
|
|
159
|
+
if (many) return `$${index}::${nativeType}${arraySuffix}`;
|
|
160
|
+
}
|
|
155
161
|
return `$${index}`;
|
|
156
162
|
}
|
|
157
163
|
function isRecord(value) {
|
|
@@ -497,12 +503,12 @@ function renderExpr(expr, contract, pim) {
|
|
|
497
503
|
function renderParamRef(ref, pim) {
|
|
498
504
|
const index = pim.indexMap.get(ref);
|
|
499
505
|
if (index === void 0) throw new Error("ParamRef not found in index map");
|
|
500
|
-
if (ref.kind === "prepared-param-ref") return renderTypedParam(index, ref.codec.codecId, pim.codecLookup);
|
|
506
|
+
if (ref.kind === "prepared-param-ref") return renderTypedParam(index, ref.codec.codecId, pim.codecLookup, ref.codec.many, ref.codec.typeParams);
|
|
501
507
|
if (ref.codec === void 0) throw runtimeError("RUNTIME.PARAM_REF_MISSING_CODEC", "Postgres renderer: ParamRef reached lowering without a bound CodecRef. Every column-bound ParamRef must carry a codec under the AST-bound codec contract. This usually indicates a builder path that constructed a ParamRef without threading the column codec.", {
|
|
502
508
|
paramIndex: index,
|
|
503
509
|
...ifDefined("name", ref.name)
|
|
504
510
|
});
|
|
505
|
-
return renderTypedParam(index, ref.codec.codecId, pim.codecLookup);
|
|
511
|
+
return renderTypedParam(index, ref.codec.codecId, pim.codecLookup, ref.codec.many, ref.codec.typeParams);
|
|
506
512
|
}
|
|
507
513
|
function renderLiteral(expr) {
|
|
508
514
|
if (typeof expr.value === "string") return `'${escapeLiteral(expr.value)}'`;
|
|
@@ -887,20 +893,34 @@ var PostgresControlAdapter = class {
|
|
|
887
893
|
*/
|
|
888
894
|
async introspect(driver, contract, schema = "public") {
|
|
889
895
|
const declaredNamespaces = extractContractNamespaceIds(contract);
|
|
890
|
-
const
|
|
891
|
-
const
|
|
892
|
-
|
|
893
|
-
const
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
};
|
|
896
|
+
const resolvedSchemas = declaredNamespaces.length > 0 ? await this.resolveNamespaceSchemas(driver, declaredNamespaces) : [schema];
|
|
897
|
+
const namespaces = {};
|
|
898
|
+
let pgVersion = "unknown";
|
|
899
|
+
for (const resolved of resolvedSchemas) {
|
|
900
|
+
const { namespace, pgVersion: version } = await this.introspectSchema(driver, resolved);
|
|
901
|
+
namespaces[resolved] = namespace;
|
|
902
|
+
pgVersion = version;
|
|
903
|
+
}
|
|
904
|
+
return new PostgresDatabaseSchemaNode({
|
|
905
|
+
namespaces,
|
|
906
|
+
roles: await this.introspectRoles(driver),
|
|
907
|
+
existingSchemas: await this.listExistingSchemas(driver),
|
|
908
|
+
pgVersion
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Reads cluster-scoped database roles. Roles are not schema-qualified, so
|
|
913
|
+
* this is queried once for the whole database rather than per namespace.
|
|
914
|
+
*/
|
|
915
|
+
async introspectRoles(driver) {
|
|
916
|
+
return (await driver.query(`SELECT rolname
|
|
917
|
+
FROM pg_catalog.pg_roles
|
|
918
|
+
WHERE rolname NOT LIKE 'pg_%'
|
|
919
|
+
AND rolname != 'postgres'
|
|
920
|
+
ORDER BY rolname`)).rows.map((row) => new PostgresRoleSchemaNode({
|
|
921
|
+
name: row.rolname,
|
|
922
|
+
namespaceId: UNBOUND_NAMESPACE_ID
|
|
923
|
+
}));
|
|
904
924
|
}
|
|
905
925
|
/**
|
|
906
926
|
* Lists every non-system schema present in the connected database.
|
|
@@ -919,36 +939,24 @@ var PostgresControlAdapter = class {
|
|
|
919
939
|
ORDER BY nspname`)).rows.map((row) => row.nspname);
|
|
920
940
|
}
|
|
921
941
|
/**
|
|
922
|
-
*
|
|
923
|
-
* the connection's `current_schema()
|
|
924
|
-
*
|
|
925
|
-
*
|
|
926
|
-
*
|
|
942
|
+
* Resolves the declared namespace ids to their live DDL schema names,
|
|
943
|
+
* mapping `UNBOUND_NAMESPACE_ID` to the connection's `current_schema()`
|
|
944
|
+
* and de-duplicating. The caller introspects one namespace node per
|
|
945
|
+
* resolved schema — there is no flat cross-schema merge, so two schemas
|
|
946
|
+
* holding a same-named table no longer collide.
|
|
927
947
|
*/
|
|
928
|
-
async
|
|
948
|
+
async resolveNamespaceSchemas(driver, namespaceIds) {
|
|
929
949
|
const resolvedSchemas = [];
|
|
930
950
|
for (const id of namespaceIds) if (id === UNBOUND_NAMESPACE_ID) {
|
|
931
951
|
const { rows } = await driver.query("SELECT current_schema() AS current_schema");
|
|
932
952
|
resolvedSchemas.push(rows[0]?.current_schema ?? "public");
|
|
933
953
|
} else resolvedSchemas.push(id);
|
|
934
|
-
|
|
935
|
-
const perSchema = [];
|
|
936
|
-
for (const schema of uniqueSchemas) perSchema.push(await this.introspectSchema(driver, schema));
|
|
937
|
-
const mergedTables = {};
|
|
938
|
-
for (const ir of perSchema) for (const [tableName, table] of Object.entries(ir.tables)) mergedTables[tableName] = table;
|
|
939
|
-
const firstAnnotations = perSchema[0]?.annotations;
|
|
940
|
-
const firstPg = blindCast(firstAnnotations?.["pg"]) ?? {};
|
|
941
|
-
return {
|
|
942
|
-
tables: mergedTables,
|
|
943
|
-
...ifDefined("annotations", {
|
|
944
|
-
...firstAnnotations,
|
|
945
|
-
pg: { ...firstPg }
|
|
946
|
-
})
|
|
947
|
-
};
|
|
954
|
+
return Array.from(new Set(resolvedSchemas));
|
|
948
955
|
}
|
|
949
956
|
/**
|
|
950
|
-
* Introspects a single Postgres schema and returns
|
|
951
|
-
*
|
|
957
|
+
* Introspects a single Postgres schema and returns the namespace node for
|
|
958
|
+
* that schema (its tables, their policies, and its native enum type names),
|
|
959
|
+
* alongside the cluster-scoped Postgres version. Used by `introspect` as
|
|
952
960
|
* the per-namespace walk.
|
|
953
961
|
*/
|
|
954
962
|
async introspectSchema(driver, schema) {
|
|
@@ -1091,7 +1099,7 @@ var PostgresControlAdapter = class {
|
|
|
1091
1099
|
}
|
|
1092
1100
|
constraints.add(row.constraint_name);
|
|
1093
1101
|
}
|
|
1094
|
-
const
|
|
1102
|
+
const tableInputs = {};
|
|
1095
1103
|
for (const tableRow of tablesResult.rows) {
|
|
1096
1104
|
const tableName = tableRow.table_name;
|
|
1097
1105
|
const columns = {};
|
|
@@ -1105,11 +1113,18 @@ var PostgresControlAdapter = class {
|
|
|
1105
1113
|
else if (colRow.numeric_precision) nativeType = `${colRow.data_type}(${colRow.numeric_precision})`;
|
|
1106
1114
|
else nativeType = colRow.data_type;
|
|
1107
1115
|
else nativeType = colRow.udt_name || colRow.data_type;
|
|
1116
|
+
const many = nativeType.endsWith("[]") ? true : void 0;
|
|
1117
|
+
if (many) nativeType = normalizeSchemaNativeType(nativeType.slice(0, -2));
|
|
1118
|
+
const resolvedNativeType = `${normalizeSchemaNativeType(nativeType)}${many ? "[]" : ""}`;
|
|
1119
|
+
const rawDefault = colRow.column_default ?? void 0;
|
|
1108
1120
|
columns[colRow.column_name] = {
|
|
1109
1121
|
name: colRow.column_name,
|
|
1110
1122
|
nativeType,
|
|
1111
1123
|
nullable: colRow.is_nullable === "YES",
|
|
1112
|
-
...ifDefined("default",
|
|
1124
|
+
...ifDefined("default", rawDefault),
|
|
1125
|
+
...ifDefined("many", many),
|
|
1126
|
+
resolvedNativeType,
|
|
1127
|
+
...ifDefined("resolvedDefault", rawDefault !== void 0 ? parsePostgresDefault(rawDefault, resolvedNativeType) : void 0)
|
|
1113
1128
|
};
|
|
1114
1129
|
}
|
|
1115
1130
|
const pkRows = [...pksByTable.get(tableName) ?? []];
|
|
@@ -1191,7 +1206,7 @@ var PostgresControlAdapter = class {
|
|
|
1191
1206
|
permittedValues: parsed.permittedValues
|
|
1192
1207
|
});
|
|
1193
1208
|
}
|
|
1194
|
-
|
|
1209
|
+
tableInputs[tableName] = {
|
|
1195
1210
|
name: tableName,
|
|
1196
1211
|
columns,
|
|
1197
1212
|
...ifDefined("primaryKey", primaryKey),
|
|
@@ -1201,19 +1216,64 @@ var PostgresControlAdapter = class {
|
|
|
1201
1216
|
...ifDefined("checks", checksForTable.length > 0 ? checksForTable : void 0)
|
|
1202
1217
|
};
|
|
1203
1218
|
}
|
|
1204
|
-
const
|
|
1219
|
+
const nativeEnums = (await driver.query(`SELECT t.typname, array_agg(e.enumlabel ORDER BY e.enumsortorder) AS enumvalues
|
|
1205
1220
|
FROM pg_catalog.pg_type t
|
|
1206
1221
|
JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
|
|
1222
|
+
JOIN pg_catalog.pg_enum e ON e.enumtypid = t.oid
|
|
1207
1223
|
WHERE t.typtype = 'e'
|
|
1208
1224
|
AND n.nspname = $1
|
|
1209
|
-
|
|
1225
|
+
GROUP BY t.typname
|
|
1226
|
+
ORDER BY t.typname`, [schema])).rows.map((r) => ({
|
|
1227
|
+
typeName: r.typname,
|
|
1228
|
+
values: parsePgNameArray(r.enumvalues)
|
|
1229
|
+
}));
|
|
1230
|
+
const nativeEnumTypeNames = nativeEnums.map((e) => e.typeName);
|
|
1231
|
+
const policiesResult = await driver.query(`SELECT schemaname, tablename, policyname, cmd, roles, qual, with_check, permissive
|
|
1232
|
+
FROM pg_catalog.pg_policies
|
|
1233
|
+
WHERE schemaname = $1
|
|
1234
|
+
ORDER BY tablename, policyname`, [schema]);
|
|
1235
|
+
const policiesByTable = /* @__PURE__ */ new Map();
|
|
1236
|
+
for (const row of policiesResult.rows) {
|
|
1237
|
+
const operation = mapPgCmd(row.cmd);
|
|
1238
|
+
const policyRoles = [...new Set(parsePgNameArray(row.roles).map((r) => r.toLowerCase()))].sort();
|
|
1239
|
+
const permissive = row.permissive.toUpperCase() === "PERMISSIVE";
|
|
1240
|
+
const prefix = parseRlsPolicyWireName(row.policyname)?.prefix ?? row.policyname;
|
|
1241
|
+
const policy = new PostgresPolicySchemaNode({
|
|
1242
|
+
name: row.policyname,
|
|
1243
|
+
prefix,
|
|
1244
|
+
tableName: row.tablename,
|
|
1245
|
+
namespaceId: row.schemaname,
|
|
1246
|
+
operation,
|
|
1247
|
+
roles: policyRoles,
|
|
1248
|
+
...row.qual !== null ? { using: row.qual } : {},
|
|
1249
|
+
...row.with_check !== null ? { withCheck: row.with_check } : {},
|
|
1250
|
+
permissive
|
|
1251
|
+
});
|
|
1252
|
+
const list = policiesByTable.get(row.tablename) ?? [];
|
|
1253
|
+
list.push(policy);
|
|
1254
|
+
policiesByTable.set(row.tablename, list);
|
|
1255
|
+
}
|
|
1256
|
+
const rlsEnabledResult = await driver.query(`SELECT c.relname AS tablename, c.relrowsecurity AS rls_enabled
|
|
1257
|
+
FROM pg_catalog.pg_class c
|
|
1258
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
1259
|
+
WHERE n.nspname = $1
|
|
1260
|
+
AND c.relkind IN ('r', 'p')
|
|
1261
|
+
ORDER BY c.relname`, [schema]);
|
|
1262
|
+
const rlsEnabledByTable = new Map(rlsEnabledResult.rows.map((row) => [row.tablename, row.rls_enabled]));
|
|
1263
|
+
const tables = {};
|
|
1264
|
+
for (const [tableName, input] of Object.entries(tableInputs)) tables[tableName] = new PostgresTableSchemaNode({
|
|
1265
|
+
...input,
|
|
1266
|
+
policies: policiesByTable.get(tableName) ?? [],
|
|
1267
|
+
rlsEnabled: rlsEnabledByTable.get(tableName) ?? false
|
|
1268
|
+
});
|
|
1210
1269
|
return {
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
}
|
|
1270
|
+
namespace: new PostgresNamespaceSchemaNode({
|
|
1271
|
+
schemaName: schema,
|
|
1272
|
+
tables,
|
|
1273
|
+
nativeEnumTypeNames,
|
|
1274
|
+
nativeEnums
|
|
1275
|
+
}),
|
|
1276
|
+
pgVersion: await this.getPostgresVersion(driver)
|
|
1217
1277
|
};
|
|
1218
1278
|
}
|
|
1219
1279
|
/**
|
|
@@ -1224,6 +1284,86 @@ var PostgresControlAdapter = class {
|
|
|
1224
1284
|
}
|
|
1225
1285
|
};
|
|
1226
1286
|
/**
|
|
1287
|
+
* Normalises a `name[]` column value from `pg_policies.roles`.
|
|
1288
|
+
*
|
|
1289
|
+
* The `pg` client's type-parser registry handles `text[]` (OID 1009) but not
|
|
1290
|
+
* `name[]` (OID 1003). When the parser is absent the raw Postgres text-array
|
|
1291
|
+
* literal (`{role1,role2}`) is returned as a string instead of a JS array.
|
|
1292
|
+
* This function accepts either form and returns a plain string array.
|
|
1293
|
+
*
|
|
1294
|
+
* The string branch honors Postgres array-literal quoting: an element
|
|
1295
|
+
* containing a comma, quote, backslash, brace, or significant whitespace is
|
|
1296
|
+
* emitted double-quoted with `\"` / `\\` escapes, and unquoted elements are
|
|
1297
|
+
* whitespace-trimmed — so a label like `in progress` or `say "hi"` parses to
|
|
1298
|
+
* its true value instead of being split or kept escaped.
|
|
1299
|
+
*/
|
|
1300
|
+
function parsePgNameArray(value) {
|
|
1301
|
+
if (Array.isArray(value)) return value.map(String);
|
|
1302
|
+
if (typeof value !== "string") return [];
|
|
1303
|
+
const trimmed = value.trim();
|
|
1304
|
+
if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return [];
|
|
1305
|
+
const inner = trimmed.slice(1, -1);
|
|
1306
|
+
if (inner === "") return [];
|
|
1307
|
+
const elements = [];
|
|
1308
|
+
let current = "";
|
|
1309
|
+
let inQuotes = false;
|
|
1310
|
+
let wasQuoted = false;
|
|
1311
|
+
const pushCurrent = () => {
|
|
1312
|
+
elements.push(wasQuoted ? current : current.trim());
|
|
1313
|
+
current = "";
|
|
1314
|
+
wasQuoted = false;
|
|
1315
|
+
};
|
|
1316
|
+
let i = 0;
|
|
1317
|
+
while (i < inner.length) {
|
|
1318
|
+
const char = inner.charAt(i);
|
|
1319
|
+
if (inQuotes) {
|
|
1320
|
+
if (char === "\\") {
|
|
1321
|
+
current += inner[i + 1] ?? "";
|
|
1322
|
+
i += 2;
|
|
1323
|
+
continue;
|
|
1324
|
+
}
|
|
1325
|
+
if (char === "\"") {
|
|
1326
|
+
inQuotes = false;
|
|
1327
|
+
i++;
|
|
1328
|
+
continue;
|
|
1329
|
+
}
|
|
1330
|
+
current += char;
|
|
1331
|
+
i++;
|
|
1332
|
+
continue;
|
|
1333
|
+
}
|
|
1334
|
+
if (char === "\"") {
|
|
1335
|
+
inQuotes = true;
|
|
1336
|
+
wasQuoted = true;
|
|
1337
|
+
i++;
|
|
1338
|
+
continue;
|
|
1339
|
+
}
|
|
1340
|
+
if (char === ",") {
|
|
1341
|
+
pushCurrent();
|
|
1342
|
+
i++;
|
|
1343
|
+
continue;
|
|
1344
|
+
}
|
|
1345
|
+
current += char;
|
|
1346
|
+
i++;
|
|
1347
|
+
}
|
|
1348
|
+
if (inQuotes) return [];
|
|
1349
|
+
pushCurrent();
|
|
1350
|
+
return elements;
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* Maps `pg_policies.cmd` text values to the `RlsPolicyOperation` union.
|
|
1354
|
+
* The `pg_policies` view renders the internal command code as an uppercase
|
|
1355
|
+
* English keyword; this function lowercases to match the IR type.
|
|
1356
|
+
*/
|
|
1357
|
+
function mapPgCmd(cmd) {
|
|
1358
|
+
switch (cmd.toUpperCase()) {
|
|
1359
|
+
case "SELECT": return "select";
|
|
1360
|
+
case "INSERT": return "insert";
|
|
1361
|
+
case "UPDATE": return "update";
|
|
1362
|
+
case "DELETE": return "delete";
|
|
1363
|
+
default: return "all";
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
/**
|
|
1227
1367
|
* Extracts the namespace coordinate ids declared on a contract's storage,
|
|
1228
1368
|
* or returns an empty array when no contract (or no storage / namespaces)
|
|
1229
1369
|
* is present. Used by `PostgresControlAdapter.introspect` to decide
|
|
@@ -1238,6 +1378,7 @@ function extractContractNamespaceIds(contract) {
|
|
|
1238
1378
|
return Object.keys(namespaces);
|
|
1239
1379
|
}
|
|
1240
1380
|
function normalizeFormattedType(formattedType, dataType, udtName) {
|
|
1381
|
+
if (formattedType.endsWith("[]")) return `${normalizeFormattedType(formattedType.slice(0, -2), dataType, udtName)}[]`;
|
|
1241
1382
|
if (formattedType === "integer") return "int4";
|
|
1242
1383
|
if (formattedType === "smallint") return "int2";
|
|
1243
1384
|
if (formattedType === "bigint") return "int8";
|
|
@@ -1383,6 +1524,16 @@ function extractQuotedLiterals(listBody) {
|
|
|
1383
1524
|
function pgIsTextLikeNativeType(nativeType) {
|
|
1384
1525
|
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(");
|
|
1385
1526
|
}
|
|
1527
|
+
function pgRenderArrayElement(el) {
|
|
1528
|
+
if (el === null) return "NULL";
|
|
1529
|
+
if (typeof el === "number" || typeof el === "boolean") return String(el);
|
|
1530
|
+
if (typeof el === "string") return `'${escapeLiteral(el)}'`;
|
|
1531
|
+
return `'${escapeLiteral(JSON.stringify(el))}'`;
|
|
1532
|
+
}
|
|
1533
|
+
function pgRenderArrayLiteral(elements) {
|
|
1534
|
+
if (elements.length === 0) return "'{}'";
|
|
1535
|
+
return `ARRAY[${elements.map(pgRenderArrayElement).join(", ")}]`;
|
|
1536
|
+
}
|
|
1386
1537
|
function pgInlineLiteral(wire, nativeType) {
|
|
1387
1538
|
if (wire === null) return "NULL";
|
|
1388
1539
|
if (typeof wire === "boolean") return wire ? "true" : "false";
|
|
@@ -1401,6 +1552,7 @@ function pgInlineLiteral(wire, nativeType) {
|
|
|
1401
1552
|
return pgIsTextLikeNativeType(nativeType) ? quoted : `${quoted}::${nativeType}`;
|
|
1402
1553
|
}
|
|
1403
1554
|
if (wire instanceof Uint8Array) return `'\\x${Array.from(wire).map((b) => b.toString(16).padStart(2, "0")).join("")}'::${nativeType}`;
|
|
1555
|
+
if (Array.isArray(wire) && nativeType.endsWith("[]")) return pgRenderArrayLiteral(wire);
|
|
1404
1556
|
if (typeof wire === "object") return `${`'${escapeLiteral(JSON.stringify(wire))}'`}::${nativeType}`;
|
|
1405
1557
|
throw new Error(`pgRenderDdlExecuteRequest: unexpected wire type "${typeof wire}" for native type "${nativeType}"`);
|
|
1406
1558
|
}
|
|
@@ -1438,6 +1590,7 @@ function pgRenderDdlConstraint(constraint) {
|
|
|
1438
1590
|
if (constraint.name !== void 0) sql = `CONSTRAINT ${quoteIdentifier(constraint.name)} ${sql}`;
|
|
1439
1591
|
return sql;
|
|
1440
1592
|
}
|
|
1593
|
+
if (constraint.kind === "check-expression") return `CONSTRAINT ${quoteIdentifier(constraint.name)} CHECK (${constraint.expression})`;
|
|
1441
1594
|
const cols = constraint.columns.map(quoteIdentifier).join(", ");
|
|
1442
1595
|
if (constraint.name !== void 0) return `CONSTRAINT ${quoteIdentifier(constraint.name)} UNIQUE (${cols})`;
|
|
1443
1596
|
return `UNIQUE (${cols})`;
|
|
@@ -1460,22 +1613,71 @@ function pgRenderCreateSchema(node) {
|
|
|
1460
1613
|
}
|
|
1461
1614
|
async function pgRenderAlterTable(node, codecLookup) {
|
|
1462
1615
|
const tableRef = node.schema ? `${quoteIdentifier(node.schema)}.${quoteIdentifier(node.table)}` : quoteIdentifier(node.table);
|
|
1463
|
-
const actionVisitor = {
|
|
1464
|
-
|
|
1465
|
-
|
|
1616
|
+
const actionVisitor = {
|
|
1617
|
+
async addColumn(action) {
|
|
1618
|
+
return `ADD COLUMN ${await pgRenderDdlColumn(action.column, codecLookup)}`;
|
|
1619
|
+
},
|
|
1620
|
+
dropDefault(action) {
|
|
1621
|
+
return Promise.resolve(`ALTER COLUMN ${quoteIdentifier(action.columnName)} DROP DEFAULT`);
|
|
1622
|
+
}
|
|
1623
|
+
};
|
|
1466
1624
|
return {
|
|
1467
1625
|
sql: `ALTER TABLE ${tableRef} ${(await Promise.all(node.actions.map((a) => a.accept(actionVisitor)))).join(", ")}`,
|
|
1468
1626
|
params: []
|
|
1469
1627
|
};
|
|
1470
1628
|
}
|
|
1629
|
+
const POLICY_OPERATION_SQL = {
|
|
1630
|
+
select: "SELECT",
|
|
1631
|
+
insert: "INSERT",
|
|
1632
|
+
update: "UPDATE",
|
|
1633
|
+
delete: "DELETE",
|
|
1634
|
+
all: "ALL"
|
|
1635
|
+
};
|
|
1636
|
+
function pgRenderCreatePolicy(node) {
|
|
1637
|
+
const tableRef = `${quoteIdentifier(node.schema)}.${quoteIdentifier(node.table)}`;
|
|
1638
|
+
const permissiveness = node.permissive ? "PERMISSIVE" : "RESTRICTIVE";
|
|
1639
|
+
const command = POLICY_OPERATION_SQL[node.operation];
|
|
1640
|
+
const roles = node.roles.length === 0 ? "PUBLIC" : node.roles.join(", ");
|
|
1641
|
+
let sql = `CREATE POLICY ${quoteIdentifier(node.name)} ON ${tableRef} AS ${permissiveness} FOR ${command} TO ${roles}`;
|
|
1642
|
+
if (node.using !== void 0) sql += ` USING (${node.using})`;
|
|
1643
|
+
if (node.withCheck !== void 0) sql += ` WITH CHECK (${node.withCheck})`;
|
|
1644
|
+
return {
|
|
1645
|
+
sql,
|
|
1646
|
+
params: []
|
|
1647
|
+
};
|
|
1648
|
+
}
|
|
1649
|
+
function pgRenderDropPolicy(node) {
|
|
1650
|
+
const tableRef = `${quoteIdentifier(node.schema)}.${quoteIdentifier(node.table)}`;
|
|
1651
|
+
return {
|
|
1652
|
+
sql: `DROP POLICY ${quoteIdentifier(node.name)} ON ${tableRef}`,
|
|
1653
|
+
params: []
|
|
1654
|
+
};
|
|
1655
|
+
}
|
|
1656
|
+
function pgRenderAlterPolicyRename(node) {
|
|
1657
|
+
const tableRef = `${quoteIdentifier(node.schema)}.${quoteIdentifier(node.table)}`;
|
|
1658
|
+
return {
|
|
1659
|
+
sql: `ALTER POLICY ${quoteIdentifier(node.name)} ON ${tableRef} RENAME TO ${quoteIdentifier(node.newName)}`,
|
|
1660
|
+
params: []
|
|
1661
|
+
};
|
|
1662
|
+
}
|
|
1663
|
+
function pgRenderDisableRowLevelSecurity(node) {
|
|
1664
|
+
return {
|
|
1665
|
+
sql: `ALTER TABLE ${`${quoteIdentifier(node.schema)}.${quoteIdentifier(node.table)}`} DISABLE ROW LEVEL SECURITY`,
|
|
1666
|
+
params: []
|
|
1667
|
+
};
|
|
1668
|
+
}
|
|
1471
1669
|
async function pgRenderDdlExecuteRequest(ast, codecLookup) {
|
|
1472
1670
|
return ast.accept({
|
|
1473
1671
|
createTable: (node) => pgRenderCreateTable(node, codecLookup),
|
|
1474
1672
|
createSchema: (node) => Promise.resolve(pgRenderCreateSchema(node)),
|
|
1475
|
-
alterTable: (node) => pgRenderAlterTable(node, codecLookup)
|
|
1673
|
+
alterTable: (node) => pgRenderAlterTable(node, codecLookup),
|
|
1674
|
+
createPolicy: (node) => Promise.resolve(pgRenderCreatePolicy(node)),
|
|
1675
|
+
dropPolicy: (node) => Promise.resolve(pgRenderDropPolicy(node)),
|
|
1676
|
+
alterPolicyRename: (node) => Promise.resolve(pgRenderAlterPolicyRename(node)),
|
|
1677
|
+
disableRowLevelSecurity: (node) => Promise.resolve(pgRenderDisableRowLevelSecurity(node))
|
|
1476
1678
|
});
|
|
1477
1679
|
}
|
|
1478
1680
|
//#endregion
|
|
1479
1681
|
export { renderLoweredSql as n, createPostgresBuiltinCodecLookup as r, PostgresControlAdapter as t };
|
|
1480
1682
|
|
|
1481
|
-
//# sourceMappingURL=control-adapter-
|
|
1683
|
+
//# sourceMappingURL=control-adapter-DN4MZLIR.mjs.map
|