@kosha-ai/integration-postgres 0.8.0 → 0.8.2

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.
@@ -4,9 +4,7 @@ export declare class PostgresConnectionError extends Error {
4
4
  }
5
5
  /**
6
6
  * A Postgres database, reached directly over its own wire protocol rather
7
- * than proxied as HTTP — hence `query`, not `api`. Every call is read-only:
8
- * Kosha has no write path for this integration regardless of what the
9
- * connected database user is otherwise allowed to do.
7
+ * than proxied as HTTP — hence `query`, not `api`.
10
8
  */
11
9
  export declare function postgres(): KoshaIntegration;
12
10
  export default postgres;
@@ -1 +1 @@
1
- {"version":3,"file":"integration-postgres.d.ts","sourceRoot":"","sources":["../../src/lib/integration-postgres.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAIV,gBAAgB,EAEjB,MAAM,2BAA2B,CAAC;AAInC,qBAAa,uBAAwB,SAAQ,KAAK;gBACpC,OAAO,EAAE,MAAM;CAI5B;AAsKD;;;;;GAKG;AACH,wBAAgB,QAAQ,IAAI,gBAAgB,CAgE3C;AAED,eAAe,QAAQ,CAAC"}
1
+ {"version":3,"file":"integration-postgres.d.ts","sourceRoot":"","sources":["../../src/lib/integration-postgres.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAMV,gBAAgB,EAEjB,MAAM,2BAA2B,CAAC;AAInC,qBAAa,uBAAwB,SAAQ,KAAK;gBACpC,OAAO,EAAE,MAAM;CAI5B;AA4KD;;;GAGG;AACH,wBAAgB,QAAQ,IAAI,gBAAgB,CAqH3C;AAED,eAAe,QAAQ,CAAC"}
@@ -1,4 +1,6 @@
1
+ import { pipeline } from 'node:stream/promises';
1
2
  import { Client } from 'pg';
3
+ import { from as copyFrom } from 'pg-copy-streams';
2
4
  import { assertAllowedHost, basic as basicAuth, defineIntegration, packageDirs, } from '@kosha-ai/integration-sdk';
3
5
  const { docsPath, migrationsPath } = packageDirs(import.meta.url);
4
6
  export class PostgresConnectionError extends Error {
@@ -92,8 +94,8 @@ async function connectClient(target) {
92
94
  return plain;
93
95
  }
94
96
  /**
95
- * Opens a fresh connection, runs `fn` inside a read-only transaction, and
96
- * always rolls back — never commits — regardless of how `fn` ends.
97
+ * Opens a fresh connection and runs `fn` inside the configuration's selected
98
+ * transaction mode.
97
99
  *
98
100
  * Read-only is enforced by Postgres itself (`BEGIN READ ONLY` rejects
99
101
  * INSERT/UPDATE/DELETE/DDL/`SELECT ... FOR UPDATE` at the engine level), not
@@ -105,7 +107,7 @@ async function connectClient(target) {
105
107
  * should ever be able to share a session — every other credential this SDK
106
108
  * resolves is similarly per-call rather than cached.
107
109
  */
108
- async function withReadOnlyClient(fields, credential, fn) {
110
+ async function withQueryClient(fields, credential, accessMode, fn) {
109
111
  const target = targetOf(fields, credential);
110
112
  // Re-checked on every call, not only when the configuration was saved: a
111
113
  // hostname that answered publicly yesterday can point inside the network
@@ -119,23 +121,25 @@ async function withReadOnlyClient(fields, credential, fn) {
119
121
  throw new PostgresConnectionError(`Could not connect to ${target.host}:${target.port}/${target.database}: ${error instanceof Error ? error.message : String(error)}`);
120
122
  }
121
123
  try {
122
- await client.query('BEGIN READ ONLY');
124
+ await client.query(accessMode === 'readonly' ? 'BEGIN READ ONLY' : 'BEGIN');
123
125
  await client.query(`SET LOCAL statement_timeout = '${STATEMENT_TIMEOUT}'`);
124
- return await fn(client);
126
+ const result = await fn(client);
127
+ await client.query(accessMode === 'readwrite' ? 'COMMIT' : 'ROLLBACK');
128
+ return result;
125
129
  }
126
130
  finally {
127
- // Always rolled back, even on success: nothing this integration runs is
128
- // ever meant to persist, and a read-only transaction has nothing to
129
- // commit anyway.
131
+ // Roll back on errors and after a read-only transaction. After COMMIT this
132
+ // is harmless and keeps cleanup safe if the client state changes.
130
133
  await client.query('ROLLBACK').catch(() => undefined);
131
134
  await client.end();
132
135
  }
133
136
  }
137
+ function quoteIdent(name) {
138
+ return `"${name.replace(/"/g, '""')}"`;
139
+ }
134
140
  /**
135
141
  * A Postgres database, reached directly over its own wire protocol rather
136
- * than proxied as HTTP — hence `query`, not `api`. Every call is read-only:
137
- * Kosha has no write path for this integration regardless of what the
138
- * connected database user is otherwise allowed to do.
142
+ * than proxied as HTTP — hence `query`, not `api`.
139
143
  */
140
144
  export function postgres() {
141
145
  return defineIntegration({
@@ -158,11 +162,21 @@ export function postgres() {
158
162
  type: 'string',
159
163
  required: true,
160
164
  },
165
+ {
166
+ key: 'accessMode',
167
+ label: 'Access',
168
+ type: 'select',
169
+ options: [
170
+ { label: 'Read only', value: 'readonly' },
171
+ { label: 'Read and write', value: 'readwrite' },
172
+ ],
173
+ help: 'Defaults to read only. Read and write commits changes made by the query.',
174
+ },
161
175
  ],
162
176
  query: {
163
- readOnly: true,
164
- async run({ credential, fields, sql, params }) {
165
- return withReadOnlyClient(fields, credential, async (client) => {
177
+ accessModes: ['readonly', 'readwrite'],
178
+ async run({ credential, fields, accessMode = 'readonly', sql, params, }) {
179
+ return withQueryClient(fields, credential, accessMode, async (client) => {
166
180
  const result = await client.query({ text: sql, values: params });
167
181
  return {
168
182
  rows: result.rows,
@@ -171,6 +185,22 @@ export function postgres() {
171
185
  };
172
186
  });
173
187
  },
188
+ /**
189
+ * Streams the CSV with `COPY ... FROM STDIN`. The statement is built here
190
+ * rather than taken from the caller: COPY can also run programs and read
191
+ * server files, and anything but FROM STDIN would leave the stream
192
+ * waiting. A failed source or row aborts the COPY, so nothing is kept.
193
+ */
194
+ async copy({ credential, fields, accessMode = 'readonly', schema, table, columns, data, }) {
195
+ const target = `${quoteIdent(schema)}.${quoteIdent(table)}`;
196
+ const columnList = columns.map(quoteIdent).join(', ');
197
+ return withQueryClient(fields, credential, accessMode, async (client) => {
198
+ const stream = copyFrom(`COPY ${target} (${columnList}) FROM STDIN WITH (FORMAT csv, HEADER true)`);
199
+ client.query(stream);
200
+ await pipeline(data, stream);
201
+ return { rowCount: stream.rowCount };
202
+ });
203
+ },
174
204
  },
175
205
  identity: {
176
206
  /**
@@ -181,7 +211,7 @@ export function postgres() {
181
211
  async fetchAccount({ accessToken, fields }) {
182
212
  const credential = { accessToken };
183
213
  const { host, database } = targetOf(fields, credential);
184
- const row = await withReadOnlyClient(fields, credential, async (client) => {
214
+ const row = await withQueryClient(fields, credential, 'readonly', async (client) => {
185
215
  const result = await client.query('SELECT current_user');
186
216
  return result.rows[0];
187
217
  });
package/docs/setup.md CHANGED
@@ -14,6 +14,8 @@ When you create the configuration, give Kosha:
14
14
  Kosha server network. A link-local address (`169.254.x.x`) is refused.
15
15
 
16
16
  - **Database** — the database name.
17
+ - **Access** — `readonly` by default, or `readwrite` when successful queries
18
+ should be committed.
17
19
 
18
20
  Connections are always encrypted in transit (TLS), but the server's
19
21
  certificate isn't verified against a CA — most managed Postgres providers
@@ -24,7 +26,7 @@ configurable yet.
24
26
 
25
27
  Postgres has no concept of "the workspace's key" the way Apollo's API key
26
28
  does, but the usage is the same in practice: one admin connects **one**
27
- read-only username and password, once, and every query Kosha runs
29
+ username and password, once, and every query Kosha runs
28
30
  afterwards — on behalf of however many people in the org — rides on that
29
31
  same connection. This is a fact about how organizations run this integration,
30
32
  not a different mechanism: Kosha's connect flow is always "one secret, one
@@ -57,13 +59,30 @@ Nothing stops you from connecting a second, different credential under a
57
59
  different owner later (per team, per environment, whatever you need) — it's
58
60
  just that most setups only ever need the one.
59
61
 
60
- ### Read-only, enforced by Postgres itself
62
+ ### Bulk loading a CSV
61
63
 
62
- Every query Kosha runs through this connection happens inside a `BEGIN READ
63
- ONLY` transaction that is always rolled back, never committed. Postgres
64
- itself rejects `INSERT`/`UPDATE`/`DELETE`/DDL/`SELECT ... FOR UPDATE` inside
65
- that transaction — Kosha does not parse or filter the SQL text, so there is
66
- no way to word a write around it.
64
+ A `readwrite` configuration can load a CSV with a header row into an existing
65
+ table. The body is streamed through `COPY ... FROM STDIN`, so every row is
66
+ loaded or none is. `columns` is a JSON array naming the table columns in the
67
+ order the CSV holds them.
68
+
69
+ ```http
70
+ POST /api/query/postgres/pg-main/org/copy?schema=public&table=users&columns=["id","name"]
71
+ Content-Type: text/csv
72
+
73
+ id,name
74
+ 1,Alice
75
+ ```
76
+
77
+ Unquoted empty fields load as NULL. The 30-second statement timeout below
78
+ includes the time taken to send the file.
79
+
80
+ ### Access mode, enforced by Postgres itself
81
+
82
+ `readonly` configurations run inside a `BEGIN READ ONLY` transaction that is
83
+ always rolled back. `readwrite` configurations run inside a normal transaction
84
+ and commit successful queries. Postgres enforces the read-only mode itself;
85
+ Kosha does not parse or filter the SQL text.
67
86
 
68
87
  That guarantee doesn't bound _cost_: a read-only transaction can still run an
69
88
  expensive or endless `SELECT`. Kosha sets a 30-second statement timeout per
@@ -0,0 +1,6 @@
1
+ ALTER TABLE "postgres_configuration"
2
+ ADD COLUMN "accessMode" TEXT NOT NULL DEFAULT 'readonly';
3
+
4
+ ALTER TABLE "postgres_configuration"
5
+ ADD CONSTRAINT "postgres_configuration_accessMode_check"
6
+ CHECK ("accessMode" IN ('readonly', 'readwrite'));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kosha-ai/integration-postgres",
3
- "version": "0.8.0",
4
- "description": "Postgres integration for Kosha: read-only queries against a connected database",
3
+ "version": "0.8.2",
4
+ "description": "Postgres integration for Kosha: configurable read-only or read-write queries against a connected database",
5
5
  "keywords": [
6
6
  "kosha",
7
7
  "postgres",
@@ -40,18 +40,20 @@
40
40
  "!**/*.tsbuildinfo"
41
41
  ],
42
42
  "dependencies": {
43
- "tslib": "^2.3.0",
44
- "pg": "^8.13.0"
43
+ "pg": "^8.13.0",
44
+ "pg-copy-streams": "^7.0.0",
45
+ "tslib": "^2.3.0"
45
46
  },
46
47
  "kosha": {
47
48
  "kind": "integration",
48
49
  "key": "postgres"
49
50
  },
50
51
  "peerDependencies": {
51
- "@kosha-ai/integration-sdk": "0.8.0"
52
+ "@kosha-ai/integration-sdk": "0.8.2"
52
53
  },
53
54
  "devDependencies": {
54
55
  "@types/pg": "^8.11.0",
55
- "@kosha-ai/integration-sdk": "0.8.0"
56
+ "@types/pg-copy-streams": "^1.2.5",
57
+ "@kosha-ai/integration-sdk": "0.8.2"
56
58
  }
57
59
  }