@arivie/db-postgres 0.1.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ ## 0.0.0
2
+
3
+ - Initial Postgres adapter (Sprint 0 / C04).
package/LICENSE ADDED
@@ -0,0 +1,204 @@
1
+ Copyright 2026 Arivie Contributors
2
+
3
+
4
+ Apache License
5
+ Version 2.0, January 2004
6
+ http://www.apache.org/licenses/
7
+
8
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
9
+
10
+ 1. Definitions.
11
+
12
+ "License" shall mean the terms and conditions for use, reproduction,
13
+ and distribution as defined by Sections 1 through 9 of this document.
14
+
15
+ "Licensor" shall mean the copyright owner or entity authorized by
16
+ the copyright owner that is granting the License.
17
+
18
+ "Legal Entity" shall mean the union of the acting entity and all
19
+ other entities that control, are controlled by, or are under common
20
+ control with that entity. For the purposes of this definition,
21
+ "control" means (i) the power, direct or indirect, to cause the
22
+ direction or management of such entity, whether by contract or
23
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
24
+ outstanding shares, or (iii) beneficial ownership of such entity.
25
+
26
+ "You" (or "Your") shall mean an individual or Legal Entity
27
+ exercising permissions granted by this License.
28
+
29
+ "Source" form shall mean the preferred form for making modifications,
30
+ including but not limited to software source code, documentation
31
+ source, and configuration files.
32
+
33
+ "Object" form shall mean any form resulting from mechanical
34
+ transformation or translation of a Source form, including but
35
+ not limited to compiled object code, generated documentation,
36
+ and conversions to other media types.
37
+
38
+ "Work" shall mean the work of authorship, whether in Source or
39
+ Object form, made available under the License, as indicated by a
40
+ copyright notice that is included in or attached to the work
41
+ (an example is provided in the Appendix below).
42
+
43
+ "Derivative Works" shall mean any work, whether in Source or Object
44
+ form, that is based on (or derived from) the Work and for which the
45
+ editorial revisions, annotations, elaborations, or other modifications
46
+ represent, as a whole, an original work of authorship. For the purposes
47
+ of this License, Derivative Works shall not include works that remain
48
+ separable from, or merely link (or bind by name) to the interfaces of,
49
+ the Work and Derivative Works thereof.
50
+
51
+ "Contribution" shall mean any work of authorship, including
52
+ the original version of the Work and any modifications or additions
53
+ to that Work or Derivative Works thereof, that is intentionally
54
+ submitted to Licensor for inclusion in the Work by the copyright owner
55
+ or by an individual or Legal Entity authorized to submit on behalf of
56
+ the copyright owner. For the purposes of this definition, "submitted"
57
+ means any form of electronic, verbal, or written communication sent
58
+ to the Licensor or its representatives, including but not limited to
59
+ communication on electronic mailing lists, source code control systems,
60
+ and issue tracking systems that are managed by, or on behalf of, the
61
+ Licensor for the purpose of discussing and improving the Work, but
62
+ excluding communication that is conspicuously marked or otherwise
63
+ designated in writing by the copyright owner as "Not a Contribution."
64
+
65
+ "Contributor" shall mean Licensor and any individual or Legal Entity
66
+ on behalf of whom a Contribution has been received by Licensor and
67
+ subsequently incorporated within the Work.
68
+
69
+ 2. Grant of Copyright License. Subject to the terms and conditions of
70
+ this License, each Contributor hereby grants to You a perpetual,
71
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
72
+ copyright license to reproduce, prepare Derivative Works of,
73
+ publicly display, publicly perform, sublicense, and distribute the
74
+ Work and such Derivative Works in Source or Object form.
75
+
76
+ 3. Grant of Patent License. Subject to the terms and conditions of
77
+ this License, each Contributor hereby grants to You a perpetual,
78
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79
+ (except as stated in this section) patent license to make, have made,
80
+ use, offer to sell, sell, import, and otherwise transfer the Work,
81
+ where such license applies only to those patent claims licensable
82
+ by such Contributor that are necessarily infringed by their
83
+ Contribution(s) alone or by combination of their Contribution(s)
84
+ with the Work to which such Contribution(s) was submitted. If You
85
+ institute patent litigation against any entity (including a
86
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
87
+ or a Contribution incorporated within the Work constitutes direct
88
+ or contributory patent infringement, then any patent licenses
89
+ granted to You under this License for that Work shall terminate
90
+ as of the date such litigation is filed.
91
+
92
+ 4. Redistribution. You may reproduce and distribute copies of the
93
+ Work or Derivative Works thereof in any medium, with or without
94
+ modifications, and in Source or Object form, provided that You
95
+ meet the following conditions:
96
+
97
+ (a) You must give any other recipients of the Work or
98
+ Derivative Works a copy of this License; and
99
+
100
+ (b) You must cause any modified files to carry prominent notices
101
+ stating that You changed the files; and
102
+
103
+ (c) You must retain, in the Source form of any Derivative Works
104
+ that You distribute, all copyright, patent, trademark, and
105
+ attribution notices from the Source form of the Work,
106
+ excluding those notices that do not pertain to any part of
107
+ the Derivative Works; and
108
+
109
+ (d) If the Work includes a "NOTICE" text file as part of its
110
+ distribution, then any Derivative Works that You distribute must
111
+ include a readable copy of the attribution notices contained
112
+ within such NOTICE file, excluding those notices that do not
113
+ pertain to any part of the Derivative Works, in at least one
114
+ of the following places: within a NOTICE text file distributed
115
+ as part of the Derivative Works; within the Source form or
116
+ documentation, if provided along with the Derivative Works; or,
117
+ within a display generated by the Derivative Works, if and
118
+ wherever such third-party notices normally appear. The contents
119
+ of the NOTICE file are for informational purposes only and
120
+ do not modify the License. You may add Your own attribution
121
+ notices within Derivative Works that You distribute, alongside
122
+ or as an addendum to the NOTICE text from the Work, provided
123
+ that such additional attribution notices cannot be construed
124
+ as modifying the License.
125
+
126
+ You may add Your own copyright statement to Your modifications and
127
+ may provide additional or different license terms and conditions
128
+ for use, reproduction, or distribution of Your modifications, or
129
+ for any such Derivative Works as a whole, provided Your use,
130
+ reproduction, and distribution of the Work otherwise complies with
131
+ the conditions stated in this License.
132
+
133
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
134
+ any Contribution intentionally submitted for inclusion in the Work
135
+ by You to the Licensor shall be under the terms and conditions of
136
+ this License, without any additional terms or conditions.
137
+ Notwithstanding the above, nothing herein shall supersede or modify
138
+ the terms of any separate license agreement you may have executed
139
+ with Licensor regarding such Contributions.
140
+
141
+ 6. Trademarks. This License does not grant permission to use the trade
142
+ names, trademarks, service marks, or product names of the Licensor,
143
+ except as required for reasonable and customary use in describing the
144
+ origin of the Work and reproducing the content of the NOTICE file.
145
+
146
+ 7. Disclaimer of Warranty. Unless required by applicable law or
147
+ agreed to in writing, Licensor provides the Work (and each
148
+ Contributor provides its Contributions) on an "AS IS" BASIS,
149
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150
+ implied, including, without limitation, any warranties or conditions
151
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152
+ PARTICULAR PURPOSE. You are solely responsible for determining the
153
+ appropriateness of using or redistributing the Work and assume any
154
+ risks associated with Your exercise of permissions under this License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as a
162
+ result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor
166
+ has been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. While redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ APPENDIX: How to apply the Apache License to your work.
182
+
183
+ To apply the Apache License to your work, attach the following
184
+ boilerplate notice, with the fields enclosed by brackets "[]"
185
+ replaced with your own identifying information. (Don't include
186
+ the brackets!) The text should be enclosed in the appropriate
187
+ comment syntax for the file format. We also recommend that a
188
+ file or class name and description of purpose be included on the
189
+ same "printed page" as the copyright notice for easier
190
+ identification within third-party archives.
191
+
192
+ Copyright [yyyy] [name of copyright owner]
193
+
194
+ Licensed under the Apache License, Version 2.0 (the "License");
195
+ you may not use this file except in compliance with the License.
196
+ You may obtain a copy of the License at
197
+
198
+ http://www.apache.org/licenses/LICENSE-2.0
199
+
200
+ Unless required by applicable law or agreed to in writing, software
201
+ distributed under the License is distributed on an "AS IS" BASIS,
202
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203
+ See the License for the specific language governing permissions and
204
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # @arivie/db-postgres
2
+
3
+ Postgres connection adapter for Arivie: role-scoped `execute` (optional `params?: readonly unknown[]` threaded to `sql.unsafe(query, params)` for `$1`/`$2` placeholders), schema `introspect`, owner-identity verification, and idempotent read-only role setup.
4
+
5
+ Full contract: [RFC-002 §4.5](../../../.research/07-rfc/RFC-002-concrete-tech-implementation/02-requirements-interfaces.md#45-anaclipdb-postgres--postgres-adapter).
@@ -0,0 +1,84 @@
1
+ import { SourceAdapterExecuteOpts, SourceAdapterCompileMetricOpts, SourceAdapterCompileMetricResult } from '@arivie/core/types';
2
+ export { ArivieBoundaryError } from '@arivie/core/types';
3
+ import postgres from 'postgres';
4
+
5
+ interface PostgresAdapterOptions {
6
+ url: string;
7
+ readOnlyRole?: string;
8
+ allowedSchemas?: string[];
9
+ maxConnections?: number;
10
+ idleTimeoutMs?: number;
11
+ }
12
+ interface PostgresAdapter {
13
+ readonly kind: "postgres";
14
+ readonly id: string;
15
+ /** Connection URL used to construct the underlying client (for Mastra PostgresStore). */
16
+ readonly url: string;
17
+ sql: postgres.Sql;
18
+ execute(opts: SourceAdapterExecuteOpts<string>): Promise<ExecuteResult>;
19
+ introspect(): Promise<TableMetadata[]>;
20
+ verifyOwnerIdentity(expectedOwnerId: string): Promise<void>;
21
+ setupRole(role: string, options?: {
22
+ allowedTables?: string[];
23
+ }): Promise<void>;
24
+ compileMetric?(opts: SourceAdapterCompileMetricOpts): SourceAdapterCompileMetricResult<string>;
25
+ close?(): Promise<void>;
26
+ }
27
+ interface ExecuteResult {
28
+ rows: Record<string, unknown>[];
29
+ rowCount: number;
30
+ durationMs: number;
31
+ truncated: boolean;
32
+ }
33
+ interface TableMetadata {
34
+ schema: string;
35
+ name: string;
36
+ columns: {
37
+ name: string;
38
+ type: string;
39
+ nullable: boolean;
40
+ comment?: string;
41
+ isPii?: boolean;
42
+ }[];
43
+ primary_key: string[];
44
+ foreign_keys: {
45
+ column: string;
46
+ references: {
47
+ table: string;
48
+ column: string;
49
+ };
50
+ }[];
51
+ row_count: number;
52
+ }
53
+
54
+ declare function postgresAdapter(opts: PostgresAdapterOptions): PostgresAdapter;
55
+
56
+ /**
57
+ * Compiles a semantic-layer measure on a Postgres-bound entity to parameterised SQL.
58
+ */
59
+ declare function compileMetricForPostgres(opts: SourceAdapterCompileMetricOpts): {
60
+ query: string;
61
+ params?: (string | number | boolean | null)[];
62
+ };
63
+
64
+ type ToolErrorKind = "sql-invalid" | "sql-blocked" | "sql-permission-denied" | "sql-timeout" | "metric-not-found" | "metric-ambiguous" | "dimension-not-found" | "segment-not-found" | "join-ambiguous" | "filter-invalid" | "cross-source-too-large" | "cross-source-output-too-large" | "cross-source-not-wired" | "source-not-found" | "source-no-compile" | "join-invalid";
65
+ declare class ToolError extends Error {
66
+ readonly kind: ToolErrorKind;
67
+ readonly code: "ARIVIE_TOOL_ERROR";
68
+ constructor(kind: ToolErrorKind, message?: string);
69
+ }
70
+
71
+ /**
72
+ * Validate a SQL query for the agent's `execute` tool.
73
+ *
74
+ * Throws `ToolError` on rejection; returns void on accept.
75
+ *
76
+ * Rejection conditions (Sprint 1 KI-1-05):
77
+ * - First keyword is not SELECT or WITH.
78
+ * - Query contains `;` outside literals/comments (multi-statement).
79
+ * - Query contains any DML/DDL/session-mutation keyword outside literals/comments.
80
+ * - Query references `pg_catalog` / `information_schema` (system catalog block).
81
+ */
82
+ declare function validateExecuteSql(sql: string): void;
83
+
84
+ export { type ExecuteResult, type PostgresAdapter, type PostgresAdapterOptions, type TableMetadata, ToolError, type ToolErrorKind, compileMetricForPostgres, postgresAdapter, validateExecuteSql };
package/dist/index.js ADDED
@@ -0,0 +1,597 @@
1
+ import { createHash } from 'crypto';
2
+ import postgres from 'postgres';
3
+ import { ArivieBoundaryError } from '@arivie/core/types';
4
+ export { ArivieBoundaryError } from '@arivie/core/types';
5
+
6
+ // src/adapter.ts
7
+ var ToolError = class extends Error {
8
+ constructor(kind, message) {
9
+ super(message ?? kind);
10
+ this.kind = kind;
11
+ this.name = "ToolError";
12
+ }
13
+ kind;
14
+ code = "ARIVIE_TOOL_ERROR";
15
+ };
16
+
17
+ // src/compile-metric.ts
18
+ var FILTER_COL_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)?$/;
19
+ var ENTITY_COL_REF = /\b([a-zA-Z_][a-zA-Z0-9_]*)\.([a-zA-Z_][a-zA-Z0-9_]*)\b/g;
20
+ function isFilterPrimitive(v) {
21
+ return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || v === null;
22
+ }
23
+ function collectEntityRefs(text) {
24
+ const refs = /* @__PURE__ */ new Set();
25
+ for (const match of text.matchAll(ENTITY_COL_REF)) {
26
+ refs.add(match[1]);
27
+ }
28
+ return refs;
29
+ }
30
+ function detectJoinsNeeded(entity, dimensionSqls, filterKeys) {
31
+ const joinTargets = new Set((entity.joins ?? []).map((j) => j.to));
32
+ const refs = /* @__PURE__ */ new Set();
33
+ for (const sql of dimensionSqls) {
34
+ for (const ref of collectEntityRefs(sql)) {
35
+ if (joinTargets.has(ref) && ref !== entity.name) {
36
+ refs.add(ref);
37
+ }
38
+ }
39
+ }
40
+ for (const key of filterKeys) {
41
+ const dot = key.indexOf(".");
42
+ if (dot > 0) {
43
+ const refEntity = key.slice(0, dot);
44
+ if (joinTargets.has(refEntity) && refEntity !== entity.name) {
45
+ refs.add(refEntity);
46
+ }
47
+ }
48
+ }
49
+ return refs;
50
+ }
51
+ function buildJoinClauses(entity, joinsNeeded) {
52
+ const clauses = [];
53
+ for (const otherEntity of joinsNeeded) {
54
+ const matching = (entity.joins ?? []).filter((j) => j.to === otherEntity);
55
+ if (matching.length === 0) {
56
+ continue;
57
+ }
58
+ if (matching.length > 1) {
59
+ throw new ToolError(
60
+ "join-ambiguous",
61
+ `multiple join paths to '${otherEntity}'; specify entityHint to disambiguate`
62
+ );
63
+ }
64
+ const join = matching[0];
65
+ clauses.push(`LEFT JOIN ${join.to} ON ${join.on}`);
66
+ }
67
+ return clauses;
68
+ }
69
+ function compileMetricForPostgres(opts) {
70
+ const { entity, metric } = opts;
71
+ const measure = entity.measures?.find((m) => m.name === metric);
72
+ if (measure == null) {
73
+ throw new ToolError(
74
+ "metric-not-found",
75
+ `metric '${metric}' not found on entity '${entity.name}'`
76
+ );
77
+ }
78
+ const dimensionNames = opts.dimensions ?? [];
79
+ const selectExprs = [`(${measure.sql}) AS "${measure.name}"`];
80
+ const dimensionSqls = [];
81
+ for (const dimName of dimensionNames) {
82
+ const dim = entity.dimensions?.find((d) => d.name === dimName);
83
+ if (dim == null) {
84
+ throw new ToolError(
85
+ "dimension-not-found",
86
+ `dimension '${dimName}' not found on entity '${entity.name}'`
87
+ );
88
+ }
89
+ selectExprs.push(`(${dim.sql}) AS "${dim.name}"`);
90
+ dimensionSqls.push(dim.sql);
91
+ }
92
+ const filterKeys = Object.keys(opts.filters ?? {});
93
+ const joinsNeeded = detectJoinsNeeded(entity, dimensionSqls, filterKeys);
94
+ const joinClauses = buildJoinClauses(entity, joinsNeeded);
95
+ const whereClauses = [];
96
+ const params = [];
97
+ for (const segName of opts.segments ?? []) {
98
+ const seg = entity.segments?.find((s) => s.name === segName);
99
+ if (seg == null) {
100
+ throw new ToolError(
101
+ "segment-not-found",
102
+ `segment '${segName}' not found on entity '${entity.name}'`
103
+ );
104
+ }
105
+ whereClauses.push(`(${seg.sql})`);
106
+ }
107
+ for (const [col, value] of Object.entries(opts.filters ?? {})) {
108
+ if (!FILTER_COL_PATTERN.test(col)) {
109
+ throw new ToolError(
110
+ "filter-invalid",
111
+ `filter column '${col}' must be a plain identifier`
112
+ );
113
+ }
114
+ if (!isFilterPrimitive(value)) {
115
+ throw new ToolError(
116
+ "filter-invalid",
117
+ `filter value for '${col}' must be string|number|boolean|null`
118
+ );
119
+ }
120
+ if (value === null) {
121
+ whereClauses.push(`${col} IS NULL`);
122
+ } else {
123
+ whereClauses.push(`${col} = $${params.length + 1}`);
124
+ params.push(value);
125
+ }
126
+ }
127
+ const fromTable = typeof entity.source === "string" ? entity.source : entity.name;
128
+ const parts = [`SELECT ${selectExprs.join(", ")}`, `FROM ${fromTable}`];
129
+ if (joinClauses.length > 0) {
130
+ parts.push(...joinClauses);
131
+ }
132
+ if (whereClauses.length > 0) {
133
+ parts.push(`WHERE ${whereClauses.join(" AND ")}`);
134
+ }
135
+ if (dimensionNames.length > 0) {
136
+ parts.push(
137
+ `GROUP BY ${dimensionNames.map((d) => `"${d}"`).join(", ")}`
138
+ );
139
+ }
140
+ const query = parts.join(" ");
141
+ return params.length > 0 ? { query, params } : { query };
142
+ }
143
+
144
+ // src/identifier.ts
145
+ var IDENT_RE = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
146
+ function escapeIdent(name) {
147
+ if (!IDENT_RE.test(name)) {
148
+ throw new ToolError("sql-invalid", `invalid identifier: ${name}`);
149
+ }
150
+ return `"${name}"`;
151
+ }
152
+
153
+ // src/execute.ts
154
+ function isPostgresError(err) {
155
+ return typeof err === "object" && err !== null && "code" in err;
156
+ }
157
+ async function executeImpl(sql, opts) {
158
+ const startedAt = Date.now();
159
+ if (!Number.isFinite(opts.timeoutMs) || !Number.isInteger(opts.timeoutMs) || opts.timeoutMs <= 0) {
160
+ throw new ToolError(
161
+ "sql-invalid",
162
+ `timeoutMs must be a positive integer; got ${String(opts.timeoutMs)}`
163
+ );
164
+ }
165
+ if (!Number.isFinite(opts.rowLimit) || !Number.isInteger(opts.rowLimit) || opts.rowLimit <= 0) {
166
+ throw new ToolError(
167
+ "sql-invalid",
168
+ `rowLimit must be a positive integer; got ${String(opts.rowLimit)}`
169
+ );
170
+ }
171
+ if (opts.runAsRole == null || opts.runAsRole === "") {
172
+ throw new ToolError("sql-invalid", "runAsRole is required");
173
+ }
174
+ const runAsRole = opts.runAsRole;
175
+ try {
176
+ const rows = await sql.begin(async (tx) => {
177
+ await tx.unsafe(`SET LOCAL ROLE ${escapeIdent(runAsRole)}`);
178
+ await tx.unsafe(
179
+ `SET LOCAL statement_timeout = ${opts.timeoutMs}`
180
+ );
181
+ let queryParams;
182
+ if (opts.params != null) {
183
+ const copy = [...opts.params];
184
+ for (let i = 0; i < copy.length; i++) {
185
+ const v = copy[i];
186
+ if (v !== null && typeof v !== "string" && typeof v !== "number" && typeof v !== "boolean") {
187
+ throw new ToolError(
188
+ "sql-invalid",
189
+ `params[${i}] must be string|number|boolean|null; got ${typeof v}`
190
+ );
191
+ }
192
+ }
193
+ queryParams = copy;
194
+ }
195
+ return await tx.unsafe(opts.query, queryParams);
196
+ });
197
+ const truncated = rows.length > opts.rowLimit;
198
+ const limited = rows.slice(0, opts.rowLimit);
199
+ return {
200
+ rows: limited,
201
+ rowCount: limited.length,
202
+ durationMs: Date.now() - startedAt,
203
+ truncated
204
+ };
205
+ } catch (err) {
206
+ if (isPostgresError(err)) {
207
+ if (err.code === "42501") {
208
+ throw new ToolError(
209
+ "sql-permission-denied",
210
+ "permission denied for SQL operation"
211
+ );
212
+ }
213
+ if (err.code === "57014") {
214
+ throw new ToolError("sql-timeout", "statement timeout");
215
+ }
216
+ }
217
+ throw err;
218
+ }
219
+ }
220
+
221
+ // src/introspect.ts
222
+ var PII_RE = /email|phone|ssn|address|dob|password|secret|token|card/i;
223
+ async function introspect(sql) {
224
+ const tables = await sql`
225
+ SELECT table_name
226
+ FROM information_schema.tables
227
+ WHERE table_schema = 'public'
228
+ AND table_type = 'BASE TABLE'
229
+ ORDER BY table_name
230
+ `;
231
+ const result = [];
232
+ for (const { table_name } of tables) {
233
+ const columns = await sql`
234
+ SELECT
235
+ c.column_name,
236
+ c.data_type,
237
+ c.is_nullable,
238
+ pgd.description AS comment
239
+ FROM information_schema.columns c
240
+ LEFT JOIN pg_catalog.pg_statio_all_tables st
241
+ ON st.schemaname = c.table_schema
242
+ AND st.relname = c.table_name
243
+ LEFT JOIN pg_catalog.pg_description pgd
244
+ ON pgd.objoid = st.relid
245
+ AND pgd.objsubid = c.ordinal_position
246
+ WHERE c.table_schema = 'public'
247
+ AND c.table_name = ${table_name}
248
+ ORDER BY c.ordinal_position
249
+ `;
250
+ const pkRows = await sql`
251
+ SELECT kcu.column_name
252
+ FROM information_schema.table_constraints tc
253
+ JOIN information_schema.key_column_usage kcu
254
+ ON tc.constraint_name = kcu.constraint_name
255
+ AND tc.table_schema = kcu.table_schema
256
+ AND tc.table_name = kcu.table_name
257
+ WHERE tc.table_schema = 'public'
258
+ AND tc.table_name = ${table_name}
259
+ AND tc.constraint_type = 'PRIMARY KEY'
260
+ ORDER BY kcu.ordinal_position
261
+ `;
262
+ const fkRows = await sql`
263
+ SELECT
264
+ kcu.column_name,
265
+ ccu.table_name AS references_table,
266
+ ccu.column_name AS references_column
267
+ FROM information_schema.table_constraints tc
268
+ JOIN information_schema.key_column_usage kcu
269
+ ON tc.constraint_name = kcu.constraint_name
270
+ AND tc.table_schema = kcu.table_schema
271
+ AND tc.table_name = kcu.table_name
272
+ JOIN information_schema.constraint_column_usage ccu
273
+ ON ccu.constraint_name = tc.constraint_name
274
+ AND ccu.table_schema = tc.table_schema
275
+ WHERE tc.table_schema = 'public'
276
+ AND tc.table_name = ${table_name}
277
+ AND tc.constraint_type = 'FOREIGN KEY'
278
+ ORDER BY kcu.ordinal_position
279
+ `;
280
+ const countRows = await sql`
281
+ SELECT reltuples::bigint AS row_count
282
+ FROM pg_class
283
+ WHERE relname = ${table_name}
284
+ `;
285
+ const rowCountRaw = countRows[0]?.row_count;
286
+ const row_count = rowCountRaw === null || rowCountRaw === void 0 ? 0 : Number(rowCountRaw);
287
+ result.push({
288
+ schema: "public",
289
+ name: table_name,
290
+ columns: columns.map((col) => {
291
+ const column = {
292
+ name: col.column_name,
293
+ type: col.data_type,
294
+ nullable: col.is_nullable === "YES"
295
+ };
296
+ if (col.comment) {
297
+ column.comment = col.comment;
298
+ }
299
+ if (PII_RE.test(col.column_name)) {
300
+ column.isPii = true;
301
+ }
302
+ return column;
303
+ }),
304
+ primary_key: pkRows.map((r) => r.column_name),
305
+ foreign_keys: fkRows.map((r) => ({
306
+ column: r.column_name,
307
+ references: {
308
+ table: r.references_table,
309
+ column: r.references_column
310
+ }
311
+ })),
312
+ row_count
313
+ });
314
+ }
315
+ return result;
316
+ }
317
+
318
+ // src/setup-role.ts
319
+ var SETUP_ROLE_LOCK_KEY = 982374623;
320
+ function isDuplicateRoleError(err) {
321
+ return err != null && typeof err === "object" && "code" in err && err.code === "42710";
322
+ }
323
+ async function setupRole(sql, role, options) {
324
+ const roleIdent = escapeIdent(role);
325
+ await sql.unsafe(`SELECT pg_advisory_lock(${SETUP_ROLE_LOCK_KEY})`);
326
+ try {
327
+ try {
328
+ await sql.unsafe(`CREATE ROLE ${roleIdent} LOGIN`);
329
+ } catch (err) {
330
+ if (!isDuplicateRoleError(err)) {
331
+ throw err;
332
+ }
333
+ }
334
+ await sql.unsafe(`
335
+ CREATE TABLE IF NOT EXISTS arivie_owner_identity (
336
+ key TEXT PRIMARY KEY,
337
+ value TEXT NOT NULL
338
+ );
339
+ `);
340
+ await sql.unsafe(`GRANT USAGE ON SCHEMA public TO ${roleIdent}`);
341
+ const allowedTables = options?.allowedTables;
342
+ if (allowedTables && allowedTables.length > 0) {
343
+ for (const table of allowedTables) {
344
+ await sql.unsafe(
345
+ `GRANT SELECT ON TABLE public.${escapeIdent(table)} TO ${roleIdent}`
346
+ );
347
+ }
348
+ } else {
349
+ await sql.unsafe(
350
+ `GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${roleIdent}`
351
+ );
352
+ }
353
+ await sql.unsafe(
354
+ `ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO ${roleIdent}`
355
+ );
356
+ } finally {
357
+ await sql.unsafe(`SELECT pg_advisory_unlock(${SETUP_ROLE_LOCK_KEY})`);
358
+ }
359
+ }
360
+
361
+ // src/verify.ts
362
+ async function verifyOwnerIdentity(sql, expectedOwnerId) {
363
+ const rows = await sql`
364
+ SELECT value FROM arivie_owner_identity WHERE key = 'owner_id'
365
+ `;
366
+ if (rows.length === 0) {
367
+ throw new ArivieBoundaryError(
368
+ {
369
+ reason: "identity-table-missing",
370
+ expected: expectedOwnerId
371
+ },
372
+ "arivie_owner_identity table missing or empty; run 'arivie setup' first"
373
+ );
374
+ }
375
+ const dbValue = rows[0]?.value;
376
+ if (dbValue !== expectedOwnerId) {
377
+ throw new ArivieBoundaryError(
378
+ {
379
+ reason: "identity-mismatch",
380
+ dbValue,
381
+ expected: expectedOwnerId
382
+ },
383
+ `owner identity mismatch: database has '${String(dbValue)}', expected '${expectedOwnerId}'`
384
+ );
385
+ }
386
+ }
387
+
388
+ // src/adapter.ts
389
+ function derivePostgresAdapterId(url) {
390
+ try {
391
+ const parsed = new URL(url);
392
+ const host = parsed.hostname || "localhost";
393
+ const db = parsed.pathname.replace(/^\//, "") || "postgres";
394
+ return `postgres:${host}/${db}`;
395
+ } catch {
396
+ const hash = createHash("sha256").update(url).digest("hex").slice(0, 12);
397
+ return `postgres:${hash}`;
398
+ }
399
+ }
400
+ function postgresAdapter(opts) {
401
+ const sql = postgres(opts.url, {
402
+ max: opts.maxConnections ?? 10,
403
+ idle_timeout: (opts.idleTimeoutMs ?? 3e4) / 1e3,
404
+ onnotice: () => {
405
+ }
406
+ });
407
+ return {
408
+ kind: "postgres",
409
+ id: derivePostgresAdapterId(opts.url),
410
+ url: opts.url,
411
+ sql,
412
+ execute: (executeOpts) => executeImpl(sql, executeOpts),
413
+ introspect: () => introspect(sql),
414
+ verifyOwnerIdentity: (expectedOwnerId) => verifyOwnerIdentity(sql, expectedOwnerId),
415
+ setupRole: (role, options) => setupRole(sql, role, options),
416
+ compileMetric: compileMetricForPostgres,
417
+ close: async () => {
418
+ await sql.end();
419
+ }
420
+ };
421
+ }
422
+
423
+ // src/sql-guard.ts
424
+ var FORBIDDEN_KEYWORDS = [
425
+ "INSERT",
426
+ "UPDATE",
427
+ "DELETE",
428
+ "MERGE",
429
+ "TRUNCATE",
430
+ "DROP",
431
+ "CREATE",
432
+ "ALTER",
433
+ "GRANT",
434
+ "REVOKE",
435
+ "REINDEX",
436
+ "VACUUM",
437
+ "CLUSTER",
438
+ "COPY",
439
+ "CALL",
440
+ "DO",
441
+ "LOCK",
442
+ "COMMENT",
443
+ "REFRESH",
444
+ "REASSIGN",
445
+ "EXECUTE",
446
+ "PREPARE",
447
+ "DEALLOCATE",
448
+ "DISCARD",
449
+ "LISTEN",
450
+ "NOTIFY",
451
+ "UNLISTEN",
452
+ "SET",
453
+ "RESET"
454
+ ];
455
+ var SYSTEM_CATALOG_PATTERN = /\b(pg_catalog|information_schema)\b/i;
456
+ var FORBIDDEN_PATTERN = new RegExp(
457
+ `\\b(${FORBIDDEN_KEYWORDS.join("|")})\\b`,
458
+ "i"
459
+ );
460
+ function stripLiteralsAndComments(sql) {
461
+ const out = [];
462
+ let i = 0;
463
+ const n = sql.length;
464
+ while (i < n) {
465
+ const c = sql[i];
466
+ if (c === void 0) {
467
+ break;
468
+ }
469
+ const next = i + 1 < n ? sql[i + 1] : "";
470
+ if (c === "-" && next === "-") {
471
+ while (i < n && sql[i] !== "\n") {
472
+ out.push(" ");
473
+ i += 1;
474
+ }
475
+ continue;
476
+ }
477
+ if (c === "/" && next === "*") {
478
+ out.push(" ");
479
+ i += 2;
480
+ while (i < n) {
481
+ if (sql[i] === "*" && i + 1 < n && sql[i + 1] === "/") {
482
+ out.push(" ");
483
+ i += 2;
484
+ break;
485
+ }
486
+ out.push(" ");
487
+ i += 1;
488
+ }
489
+ continue;
490
+ }
491
+ if (c === "'") {
492
+ out.push("'");
493
+ i += 1;
494
+ while (i < n) {
495
+ if (sql[i] === "'") {
496
+ if (i + 1 < n && sql[i + 1] === "'") {
497
+ out.push(" ");
498
+ i += 2;
499
+ continue;
500
+ }
501
+ out.push("'");
502
+ i += 1;
503
+ break;
504
+ }
505
+ out.push(" ");
506
+ i += 1;
507
+ }
508
+ continue;
509
+ }
510
+ if (c === '"') {
511
+ out.push('"');
512
+ i += 1;
513
+ while (i < n) {
514
+ if (sql[i] === '"') {
515
+ if (i + 1 < n && sql[i + 1] === '"') {
516
+ out.push(" ");
517
+ i += 2;
518
+ continue;
519
+ }
520
+ out.push('"');
521
+ i += 1;
522
+ break;
523
+ }
524
+ out.push(" ");
525
+ i += 1;
526
+ }
527
+ continue;
528
+ }
529
+ if (c === "$") {
530
+ const tagMatch = /^\$([A-Za-z_][A-Za-z_0-9]*)?\$/.exec(sql.slice(i));
531
+ if (tagMatch != null) {
532
+ const tag = tagMatch[0];
533
+ out.push(" ".repeat(tag.length));
534
+ i += tag.length;
535
+ const end = sql.indexOf(tag, i);
536
+ if (end === -1) {
537
+ while (i < n) {
538
+ out.push(" ");
539
+ i += 1;
540
+ }
541
+ continue;
542
+ }
543
+ while (i < end) {
544
+ out.push(" ");
545
+ i += 1;
546
+ }
547
+ out.push(" ".repeat(tag.length));
548
+ i += tag.length;
549
+ continue;
550
+ }
551
+ }
552
+ out.push(c);
553
+ i += 1;
554
+ }
555
+ return out.join("");
556
+ }
557
+ function firstKeyword(sql) {
558
+ const stripped = stripLiteralsAndComments(sql);
559
+ const m = /\s*\(*\s*([A-Za-z_][A-Za-z_0-9]*)/.exec(stripped);
560
+ return m?.[1] ? m[1].toUpperCase() : null;
561
+ }
562
+ function validateExecuteSql(sql) {
563
+ const trimmed = sql.trim();
564
+ if (trimmed.length === 0) {
565
+ throw new ToolError("sql-invalid", "empty query");
566
+ }
567
+ const stripped = stripLiteralsAndComments(trimmed);
568
+ if (stripped.includes(";")) {
569
+ const lastSemi = stripped.lastIndexOf(";");
570
+ const tail = stripped.slice(lastSemi + 1).trim();
571
+ if (tail.length > 0) {
572
+ throw new ToolError(
573
+ "sql-invalid",
574
+ "multi-statement queries are not allowed"
575
+ );
576
+ }
577
+ }
578
+ const head = firstKeyword(trimmed);
579
+ if (head !== "SELECT" && head !== "WITH") {
580
+ throw new ToolError(
581
+ "sql-invalid",
582
+ "only SELECT and WITH statements are allowed"
583
+ );
584
+ }
585
+ if (SYSTEM_CATALOG_PATTERN.test(stripped)) {
586
+ throw new ToolError("sql-blocked", "system catalog access is blocked");
587
+ }
588
+ const forbidden = FORBIDDEN_PATTERN.exec(stripped);
589
+ if (forbidden != null) {
590
+ throw new ToolError(
591
+ "sql-blocked",
592
+ `forbidden keyword '${forbidden[1]?.toUpperCase()}' in query`
593
+ );
594
+ }
595
+ }
596
+
597
+ export { ToolError, compileMetricForPostgres, postgresAdapter, validateExecuteSql };
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@arivie/db-postgres",
3
+ "version": "0.1.0",
4
+ "description": "Arivie Postgres adapter — role-scoped execute, introspect, owner-identity verification.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/index.js",
12
+ "types": "./dist/index.d.ts"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE",
19
+ "CHANGELOG.md"
20
+ ],
21
+ "dependencies": {
22
+ "@arivie/core": "0.1.0"
23
+ },
24
+ "peerDependencies": {
25
+ "postgres": "^3.4.9"
26
+ },
27
+ "devDependencies": {
28
+ "@types/node": "^22.0.0",
29
+ "@testcontainers/postgresql": "^11.0.0",
30
+ "postgres": "^3.4.9",
31
+ "testcontainers": "^11.0.0",
32
+ "tsup": "^8.5.1",
33
+ "typescript": "^6.0.0",
34
+ "vitest": "^4.1.0",
35
+ "@arivie/semantic": "0.1.0"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "registry": "https://registry.npmjs.org/"
40
+ },
41
+ "scripts": {
42
+ "build": "tsup",
43
+ "test": "vitest run",
44
+ "typecheck": "tsc --noEmit",
45
+ "lint": "echo no-lint-yet"
46
+ }
47
+ }