@myrialabs/clopen 0.3.7 → 0.3.9
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/backend/auth/permissions.ts +41 -2
- package/backend/chat/stream-manager.ts +71 -0
- package/backend/database/migrations/030_add_files_panel_state_to_user_projects.ts +34 -0
- package/backend/database/migrations/031_create_db_client_tables.ts +74 -0
- package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
- package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
- package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
- package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
- package/backend/database/migrations/index.ts +43 -1
- package/backend/database/queries/db-client-connection-queries.ts +343 -0
- package/backend/database/queries/db-client-query-history-queries.ts +113 -0
- package/backend/database/queries/engine-queries.ts +12 -0
- package/backend/database/queries/index.ts +3 -1
- package/backend/database/queries/project-queries.ts +28 -0
- package/backend/db-client/connection-manager.ts +257 -0
- package/backend/db-client/drivers/bun-sql-helpers.ts +41 -0
- package/backend/db-client/drivers/mongodb.ts +358 -0
- package/backend/db-client/drivers/mysql.ts +385 -0
- package/backend/db-client/drivers/postgres.ts +446 -0
- package/backend/db-client/drivers/redis.ts +267 -0
- package/backend/db-client/drivers/sql-builders.ts +215 -0
- package/backend/db-client/drivers/sqlite.ts +346 -0
- package/backend/db-client/drivers/types.ts +92 -0
- package/backend/db-client/query-executor.ts +126 -0
- package/backend/db-client/ssh-tunnel.ts +122 -0
- package/backend/engine/README.md +1702 -0
- package/backend/engine/adapters/claude/models.ts +141 -0
- package/backend/engine/adapters/claude/stream.ts +1 -1
- package/backend/engine/adapters/codex/credential.ts +179 -0
- package/backend/engine/adapters/codex/error-handler.ts +65 -0
- package/backend/engine/adapters/codex/index.ts +1 -0
- package/backend/engine/adapters/codex/message-converter.ts +646 -0
- package/backend/engine/adapters/codex/models.ts +105 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
- package/backend/engine/adapters/codex/session-fork.ts +149 -0
- package/backend/engine/adapters/codex/stream.ts +310 -0
- package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
- package/backend/engine/adapters/copilot/error-handler.ts +94 -0
- package/backend/engine/adapters/copilot/index.ts +1 -0
- package/backend/engine/adapters/copilot/message-converter.ts +973 -0
- package/backend/engine/adapters/copilot/models.ts +92 -0
- package/backend/engine/adapters/copilot/session-fork.ts +111 -0
- package/backend/engine/adapters/copilot/stream.ts +573 -0
- package/backend/engine/adapters/opencode/config.ts +56 -104
- package/backend/engine/adapters/opencode/error-handler.ts +71 -0
- package/backend/engine/adapters/opencode/models.ts +79 -0
- package/backend/engine/adapters/opencode/presets.ts +91 -0
- package/backend/engine/adapters/opencode/stream.ts +5 -115
- package/backend/engine/adapters/qwen/credential.ts +78 -0
- package/backend/engine/adapters/qwen/environment.ts +84 -0
- package/backend/engine/adapters/qwen/error-handler.ts +71 -0
- package/backend/engine/adapters/qwen/index.ts +1 -0
- package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
- package/backend/engine/adapters/qwen/models.ts +81 -0
- package/backend/engine/adapters/qwen/presets.ts +51 -0
- package/backend/engine/adapters/qwen/session-fork.ts +97 -0
- package/backend/engine/adapters/qwen/stream.ts +380 -0
- package/backend/engine/index.ts +35 -0
- package/backend/engine/install-recipes.ts +80 -1
- package/backend/engine/install-runner.ts +4 -0
- package/backend/git/git-service.ts +12 -0
- package/backend/mcp/README.md +84 -14
- package/backend/mcp/config.ts +218 -17
- package/backend/mcp/index.ts +2 -0
- package/backend/mcp/project-context.ts +55 -0
- package/backend/mcp/servers/browser-automation/actions.ts +6 -1
- package/backend/mcp/servers/helper.ts +13 -0
- package/backend/middleware/error-handler.ts +16 -2
- package/backend/preview/browser/browser-preview-service.ts +4 -4
- package/backend/preview/browser/scripts/video-stream.ts +9 -3
- package/backend/ws/README.md +128 -3
- package/backend/ws/access.ts +56 -0
- package/backend/ws/chat/stream.ts +36 -12
- package/backend/ws/db-client/access.ts +19 -0
- package/backend/ws/db-client/connections.ts +194 -0
- package/backend/ws/db-client/index.ts +17 -0
- package/backend/ws/db-client/io.ts +456 -0
- package/backend/ws/db-client/query.ts +214 -0
- package/backend/ws/db-client/schema.ts +81 -0
- package/backend/ws/db-client/structure.ts +230 -0
- package/backend/ws/engine/access.ts +39 -0
- package/backend/ws/engine/claude/accounts.ts +15 -10
- package/backend/ws/engine/codex/accounts.ts +516 -0
- package/backend/ws/engine/codex/index.ts +14 -0
- package/backend/ws/engine/codex/status.ts +87 -0
- package/backend/ws/engine/copilot/accounts.ts +122 -0
- package/backend/ws/engine/copilot/index.ts +13 -0
- package/backend/ws/engine/copilot/status.ts +54 -0
- package/backend/ws/engine/index.ts +7 -1
- package/backend/ws/engine/opencode/providers.ts +1 -1
- package/backend/ws/engine/qwen/accounts.ts +137 -0
- package/backend/ws/engine/qwen/index.ts +15 -0
- package/backend/ws/engine/qwen/presets.ts +40 -0
- package/backend/ws/engine/qwen/status.ts +54 -0
- package/backend/ws/files/index.ts +5 -1
- package/backend/ws/files/read.ts +34 -0
- package/backend/ws/files/state.ts +42 -0
- package/backend/ws/files/watch.ts +7 -1
- package/backend/ws/git/branch.ts +13 -19
- package/backend/ws/git/commit-message.ts +3 -4
- package/backend/ws/git/commit.ts +5 -7
- package/backend/ws/git/conflict.ts +7 -10
- package/backend/ws/git/diff.ts +7 -10
- package/backend/ws/git/log.ts +3 -4
- package/backend/ws/git/remote.ts +30 -43
- package/backend/ws/git/staging.ts +13 -19
- package/backend/ws/git/status.ts +7 -11
- package/backend/ws/index.ts +5 -1
- package/backend/ws/messages/crud.ts +7 -13
- package/backend/ws/preview/access.ts +45 -0
- package/backend/ws/preview/browser/cleanup.ts +3 -11
- package/backend/ws/preview/browser/console.ts +5 -40
- package/backend/ws/preview/browser/interact.ts +2 -6
- package/backend/ws/preview/browser/native-ui.ts +5 -18
- package/backend/ws/preview/browser/stats.ts +2 -12
- package/backend/ws/preview/browser/tab-info.ts +4 -20
- package/backend/ws/preview/browser/tab.ts +4 -27
- package/backend/ws/preview/browser/webcodecs.ts +6 -47
- package/backend/ws/projects/crud.ts +4 -10
- package/backend/ws/projects/status.ts +2 -0
- package/backend/ws/sessions/crud.ts +22 -33
- package/backend/ws/settings/crud.ts +13 -13
- package/backend/ws/snapshot/restore.ts +5 -2
- package/backend/ws/snapshot/timeline.ts +3 -1
- package/backend/ws/system-tools/access.ts +28 -0
- package/backend/ws/system-tools/install.ts +13 -4
- package/backend/ws/system-tools/status.ts +5 -2
- package/backend/ws/terminal/access.ts +56 -0
- package/backend/ws/terminal/persistence.ts +12 -6
- package/backend/ws/terminal/session.ts +35 -14
- package/backend/ws/terminal/stream.ts +4 -1
- package/dist/assets/{index-C86jwBxR.js → index-D8V2wj9B.js} +2 -2
- package/dist/assets/{main-DhLx8wD1.js → main-C9nYVmnw.js} +222 -195
- package/dist/assets/main-hspyFOoK.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +7 -1
- package/shared/constants/engines.ts +45 -140
- package/shared/types/database/schema.ts +49 -1
- package/shared/types/db-client/connection.ts +60 -0
- package/shared/types/db-client/index.ts +6 -0
- package/shared/types/db-client/query.ts +77 -0
- package/shared/types/unified/common.ts +1 -1
- package/shared/types/unified/engine.ts +29 -1
- package/shared/types/unified/index.ts +2 -0
- package/shared/types/unified/message.ts +1 -1
- package/shared/types/unified/tool.ts +17 -2
- package/shared/utils/logger.ts +1 -0
- package/shared/utils/ws-server.ts +14 -0
- package/dist/assets/main-jTnmAoXS.css +0 -1
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PostgreSQL adapter — Bun.sql (postgres://) per PHASE 0 findings.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { SQL } from 'bun';
|
|
6
|
+
import type {
|
|
7
|
+
DbClientConnection,
|
|
8
|
+
DbClientHealth,
|
|
9
|
+
DbClientObjectColumn,
|
|
10
|
+
DbClientObjectDetails,
|
|
11
|
+
DbClientObjectForeignKey,
|
|
12
|
+
DbClientObjectIndex,
|
|
13
|
+
DbClientQueryResult,
|
|
14
|
+
DbClientSchemaNode,
|
|
15
|
+
DbClientSchemaNodeType
|
|
16
|
+
} from '$shared/types/db-client';
|
|
17
|
+
import type {
|
|
18
|
+
AlterOperation,
|
|
19
|
+
DbClientDriverAdapter,
|
|
20
|
+
IndexDefinition,
|
|
21
|
+
SchemaOpts,
|
|
22
|
+
TableDefinition
|
|
23
|
+
} from './types';
|
|
24
|
+
import { normalizeBunSqlResult } from './bun-sql-helpers';
|
|
25
|
+
import {
|
|
26
|
+
assertSafeIdentifier,
|
|
27
|
+
buildDelete,
|
|
28
|
+
buildInsert,
|
|
29
|
+
buildUpdate,
|
|
30
|
+
qualified,
|
|
31
|
+
quotePg,
|
|
32
|
+
renderColumn,
|
|
33
|
+
renderCreateIndex,
|
|
34
|
+
renderCreateTable
|
|
35
|
+
} from './sql-builders';
|
|
36
|
+
import { debug } from '$shared/utils/logger';
|
|
37
|
+
|
|
38
|
+
const Q = quotePg;
|
|
39
|
+
const PG_PLACEHOLDER = (i: number): string => `$${i + 1}`;
|
|
40
|
+
|
|
41
|
+
export class PostgresAdapter implements DbClientDriverAdapter {
|
|
42
|
+
readonly kind = 'postgres' as const;
|
|
43
|
+
|
|
44
|
+
private sql: SQL | null = null;
|
|
45
|
+
private alive = false;
|
|
46
|
+
private defaultDb: string | null = null;
|
|
47
|
+
private defaultSchema: string | null = null;
|
|
48
|
+
private conn: DbClientConnection | null = null;
|
|
49
|
+
private tunnelPort: number | undefined = undefined;
|
|
50
|
+
|
|
51
|
+
private buildUrl(conn: DbClientConnection, tunnelPort?: number): string {
|
|
52
|
+
const host = tunnelPort ? '127.0.0.1' : (conn.host ?? '127.0.0.1');
|
|
53
|
+
const port = tunnelPort ?? conn.port ?? 5432;
|
|
54
|
+
const user = encodeURIComponent(conn.username ?? '');
|
|
55
|
+
const pass = conn.password ? `:${encodeURIComponent(conn.password)}` : '';
|
|
56
|
+
const auth = user ? `${user}${pass}@` : '';
|
|
57
|
+
const db = conn.database ? `/${encodeURIComponent(conn.database)}` : '/postgres';
|
|
58
|
+
|
|
59
|
+
const params = new URLSearchParams();
|
|
60
|
+
if (conn.sslMode && conn.sslMode !== 'disable') {
|
|
61
|
+
params.set('sslmode', conn.sslMode);
|
|
62
|
+
}
|
|
63
|
+
const qs = params.toString();
|
|
64
|
+
return `postgres://${auth}${host}:${port}${db}${qs ? `?${qs}` : ''}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async connect(conn: DbClientConnection, tunnelPort?: number): Promise<void> {
|
|
68
|
+
const url = this.buildUrl(conn, tunnelPort);
|
|
69
|
+
|
|
70
|
+
this.sql = new SQL(url);
|
|
71
|
+
await this.sql.connect();
|
|
72
|
+
this.defaultDb = conn.database || null;
|
|
73
|
+
this.defaultSchema = typeof conn.options?.schema === 'string' ? conn.options.schema : 'public';
|
|
74
|
+
this.conn = conn;
|
|
75
|
+
this.tunnelPort = tunnelPort;
|
|
76
|
+
this.alive = true;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private async ensureDatabase(database?: string): Promise<void> {
|
|
80
|
+
if (!database || !this.conn) return;
|
|
81
|
+
if (database === this.defaultDb) return;
|
|
82
|
+
const newConn = { ...this.conn, database };
|
|
83
|
+
const url = this.buildUrl(newConn, this.tunnelPort);
|
|
84
|
+
const next = new SQL(url);
|
|
85
|
+
await next.connect();
|
|
86
|
+
const prev = this.sql;
|
|
87
|
+
this.sql = next;
|
|
88
|
+
this.defaultDb = database;
|
|
89
|
+
this.conn = newConn;
|
|
90
|
+
this.alive = true;
|
|
91
|
+
if (prev) await prev.close().catch((err) => debug.warn('db-client', 'pg switch close error:', err));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async close(): Promise<void> {
|
|
95
|
+
this.alive = false;
|
|
96
|
+
if (!this.sql) return;
|
|
97
|
+
try {
|
|
98
|
+
await this.sql.close();
|
|
99
|
+
} catch (err) {
|
|
100
|
+
debug.warn('db-client', 'Postgres close error:', err);
|
|
101
|
+
}
|
|
102
|
+
this.sql = null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
isAlive(): boolean {
|
|
106
|
+
return this.alive && this.sql !== null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async health(): Promise<DbClientHealth> {
|
|
110
|
+
if (!this.sql) return notConnected();
|
|
111
|
+
const start = performance.now();
|
|
112
|
+
try {
|
|
113
|
+
const rows = (await this.sql.unsafe('SELECT version() AS version')) as Array<{ version: string }>;
|
|
114
|
+
return {
|
|
115
|
+
ok: true,
|
|
116
|
+
latencyMs: Math.round(performance.now() - start),
|
|
117
|
+
serverVersion: rows[0]?.version ?? null,
|
|
118
|
+
sshOk: null,
|
|
119
|
+
error: null
|
|
120
|
+
};
|
|
121
|
+
} catch (err) {
|
|
122
|
+
return {
|
|
123
|
+
ok: false,
|
|
124
|
+
latencyMs: null,
|
|
125
|
+
serverVersion: null,
|
|
126
|
+
sshOk: null,
|
|
127
|
+
error: err instanceof Error ? err.message : String(err)
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private requireSql(): SQL {
|
|
133
|
+
if (!this.sql) throw new Error('Postgres not connected');
|
|
134
|
+
return this.sql;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private targetSchema(opts?: SchemaOpts): string {
|
|
138
|
+
return opts?.schema || this.defaultSchema || 'public';
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async executeRead(q: string, params: unknown[] = [], opts?: { database?: string }): Promise<DbClientQueryResult> {
|
|
142
|
+
await this.ensureDatabase(opts?.database);
|
|
143
|
+
const sql = this.requireSql();
|
|
144
|
+
const start = performance.now();
|
|
145
|
+
const raw = await sql.unsafe(q, params as never);
|
|
146
|
+
return normalizeBunSqlResult(raw, Math.round(performance.now() - start));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async executeWrite(q: string, params: unknown[] = [], opts?: { database?: string }): Promise<DbClientQueryResult> {
|
|
150
|
+
return this.executeRead(q, params, opts);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async explain(q: string, opts?: { database?: string }): Promise<DbClientQueryResult> {
|
|
154
|
+
return this.executeRead(`EXPLAIN ${q}`, [], opts);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ── Schema ────────────────────────────────────────────────────────────
|
|
158
|
+
|
|
159
|
+
async listDatabases(): Promise<DbClientSchemaNode[]> {
|
|
160
|
+
const rows = (await this.requireSql().unsafe(
|
|
161
|
+
'SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname'
|
|
162
|
+
)) as Array<{ datname: string }>;
|
|
163
|
+
return rows.map((r) => ({ name: r.datname, type: 'database' as const }));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async listSchemas(): Promise<DbClientSchemaNode[]> {
|
|
167
|
+
const rows = (await this.requireSql().unsafe(
|
|
168
|
+
`SELECT schema_name FROM information_schema.schemata
|
|
169
|
+
WHERE schema_name NOT IN ('pg_catalog','information_schema','pg_toast')
|
|
170
|
+
ORDER BY schema_name`
|
|
171
|
+
)) as Array<{ schema_name: string }>;
|
|
172
|
+
return rows.map((r) => ({ name: r.schema_name, type: 'schema' as const }));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async listObjects(database?: string, schema?: string): Promise<DbClientSchemaNode[]> {
|
|
176
|
+
await this.ensureDatabase(database);
|
|
177
|
+
const target = this.targetSchema({ schema });
|
|
178
|
+
const rows = (await this.requireSql().unsafe(
|
|
179
|
+
`SELECT table_name, table_type FROM information_schema.tables
|
|
180
|
+
WHERE table_schema = $1 ORDER BY table_name`,
|
|
181
|
+
[target] as never
|
|
182
|
+
)) as Array<{ table_name: string; table_type: string }>;
|
|
183
|
+
return rows.map((r) => ({
|
|
184
|
+
name: r.table_name,
|
|
185
|
+
type: r.table_type === 'VIEW' ? 'view' as const : 'table' as const
|
|
186
|
+
}));
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async getObjectDetails(
|
|
190
|
+
name: string,
|
|
191
|
+
_type: DbClientSchemaNodeType,
|
|
192
|
+
database?: string,
|
|
193
|
+
schema?: string
|
|
194
|
+
): Promise<DbClientObjectDetails> {
|
|
195
|
+
await this.ensureDatabase(database);
|
|
196
|
+
const target = this.targetSchema({ schema });
|
|
197
|
+
const sql = this.requireSql();
|
|
198
|
+
|
|
199
|
+
const colRows = (await sql.unsafe(
|
|
200
|
+
`SELECT c.column_name, c.data_type, c.udt_name, c.is_nullable, c.column_default,
|
|
201
|
+
EXISTS (
|
|
202
|
+
SELECT 1 FROM information_schema.key_column_usage kcu
|
|
203
|
+
JOIN information_schema.table_constraints tc
|
|
204
|
+
ON tc.constraint_name = kcu.constraint_name
|
|
205
|
+
AND tc.table_schema = kcu.table_schema
|
|
206
|
+
WHERE tc.constraint_type = 'PRIMARY KEY'
|
|
207
|
+
AND kcu.table_schema = c.table_schema
|
|
208
|
+
AND kcu.table_name = c.table_name
|
|
209
|
+
AND kcu.column_name = c.column_name
|
|
210
|
+
) AS is_primary,
|
|
211
|
+
EXISTS (
|
|
212
|
+
SELECT 1 FROM information_schema.key_column_usage kcu
|
|
213
|
+
JOIN information_schema.table_constraints tc
|
|
214
|
+
ON tc.constraint_name = kcu.constraint_name
|
|
215
|
+
AND tc.table_schema = kcu.table_schema
|
|
216
|
+
WHERE tc.constraint_type = 'UNIQUE'
|
|
217
|
+
AND kcu.table_schema = c.table_schema
|
|
218
|
+
AND kcu.table_name = c.table_name
|
|
219
|
+
AND kcu.column_name = c.column_name
|
|
220
|
+
) AS is_unique
|
|
221
|
+
FROM information_schema.columns c
|
|
222
|
+
WHERE c.table_schema = $1 AND c.table_name = $2
|
|
223
|
+
ORDER BY c.ordinal_position`,
|
|
224
|
+
[target, name] as never
|
|
225
|
+
)) as Array<Record<string, unknown>>;
|
|
226
|
+
|
|
227
|
+
const columns: DbClientObjectColumn[] = colRows.map((r) => ({
|
|
228
|
+
name: String(r.column_name),
|
|
229
|
+
type: String(r.udt_name ?? r.data_type ?? ''),
|
|
230
|
+
nullable: r.is_nullable === 'YES',
|
|
231
|
+
default: r.column_default === null ? null : String(r.column_default),
|
|
232
|
+
isPrimary: Boolean(r.is_primary),
|
|
233
|
+
isUnique: Boolean(r.is_unique)
|
|
234
|
+
}));
|
|
235
|
+
|
|
236
|
+
const idxRows = (await sql.unsafe(
|
|
237
|
+
`SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = $1 AND tablename = $2`,
|
|
238
|
+
[target, name] as never
|
|
239
|
+
)) as Array<{ indexname: string; indexdef: string }>;
|
|
240
|
+
|
|
241
|
+
const indexes: DbClientObjectIndex[] = idxRows.map((r) => {
|
|
242
|
+
const m = /\(([^)]+)\)/.exec(r.indexdef);
|
|
243
|
+
const cols = m ? m[1].split(',').map((s) => s.trim().replace(/"/g, '')) : [];
|
|
244
|
+
return {
|
|
245
|
+
name: r.indexname,
|
|
246
|
+
columns: cols,
|
|
247
|
+
unique: /\bUNIQUE\b/i.test(r.indexdef)
|
|
248
|
+
};
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
const fkRows = (await sql.unsafe(
|
|
252
|
+
`SELECT kcu.column_name, ccu.table_name AS ref_table, ccu.column_name AS ref_column
|
|
253
|
+
FROM information_schema.table_constraints tc
|
|
254
|
+
JOIN information_schema.key_column_usage kcu
|
|
255
|
+
ON tc.constraint_name = kcu.constraint_name
|
|
256
|
+
AND tc.table_schema = kcu.table_schema
|
|
257
|
+
JOIN information_schema.constraint_column_usage ccu
|
|
258
|
+
ON ccu.constraint_name = tc.constraint_name
|
|
259
|
+
AND ccu.table_schema = tc.table_schema
|
|
260
|
+
WHERE tc.constraint_type = 'FOREIGN KEY'
|
|
261
|
+
AND tc.table_schema = $1
|
|
262
|
+
AND tc.table_name = $2`,
|
|
263
|
+
[target, name] as never
|
|
264
|
+
)) as Array<Record<string, unknown>>;
|
|
265
|
+
|
|
266
|
+
const foreignKeys: DbClientObjectForeignKey[] = fkRows.map((r) => ({
|
|
267
|
+
column: String(r.column_name),
|
|
268
|
+
refTable: String(r.ref_table),
|
|
269
|
+
refColumn: String(r.ref_column)
|
|
270
|
+
}));
|
|
271
|
+
|
|
272
|
+
return { name, type: 'table', columns, indexes, foreignKeys };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// ── Structure ─────────────────────────────────────────────────────────
|
|
276
|
+
|
|
277
|
+
async createDatabase(name: string): Promise<string> {
|
|
278
|
+
assertSafeIdentifier(name);
|
|
279
|
+
const ddl = `CREATE DATABASE ${Q(name)}`;
|
|
280
|
+
await this.requireSql().unsafe(ddl);
|
|
281
|
+
return ddl;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async createTable(definition: TableDefinition, opts?: SchemaOpts): Promise<string> {
|
|
285
|
+
await this.ensureDatabase(opts?.database);
|
|
286
|
+
assertSafeIdentifier(definition.name);
|
|
287
|
+
const ddl = renderCreateTable({
|
|
288
|
+
quote: Q,
|
|
289
|
+
definition,
|
|
290
|
+
schema: this.targetSchema(opts),
|
|
291
|
+
driver: 'postgres'
|
|
292
|
+
});
|
|
293
|
+
await this.requireSql().unsafe(ddl);
|
|
294
|
+
return ddl;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async alterTable(name: string, operations: AlterOperation[], opts?: SchemaOpts): Promise<string> {
|
|
298
|
+
await this.ensureDatabase(opts?.database);
|
|
299
|
+
assertSafeIdentifier(name);
|
|
300
|
+
const fqt = qualified(Q, [this.targetSchema(opts), name]);
|
|
301
|
+
const parts: string[] = [];
|
|
302
|
+
for (const op of operations) {
|
|
303
|
+
switch (op.kind) {
|
|
304
|
+
case 'add-column':
|
|
305
|
+
assertSafeIdentifier(op.column.name);
|
|
306
|
+
parts.push(`ADD COLUMN ${renderColumn({ quote: Q, column: op.column, driver: 'postgres' })}`);
|
|
307
|
+
break;
|
|
308
|
+
case 'drop-column':
|
|
309
|
+
assertSafeIdentifier(op.name);
|
|
310
|
+
parts.push(`DROP COLUMN ${Q(op.name)}`);
|
|
311
|
+
break;
|
|
312
|
+
case 'rename-column':
|
|
313
|
+
assertSafeIdentifier(op.name);
|
|
314
|
+
assertSafeIdentifier(op.newName);
|
|
315
|
+
parts.push(`RENAME COLUMN ${Q(op.name)} TO ${Q(op.newName)}`);
|
|
316
|
+
break;
|
|
317
|
+
case 'modify-column':
|
|
318
|
+
assertSafeIdentifier(op.column.name);
|
|
319
|
+
parts.push(`ALTER COLUMN ${Q(op.column.name)} TYPE ${op.column.type}`);
|
|
320
|
+
break;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
const ddl = `ALTER TABLE ${fqt} ${parts.join(', ')}`;
|
|
324
|
+
await this.requireSql().unsafe(ddl);
|
|
325
|
+
return ddl;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async dropTable(name: string, opts?: SchemaOpts): Promise<string> {
|
|
329
|
+
await this.ensureDatabase(opts?.database);
|
|
330
|
+
assertSafeIdentifier(name);
|
|
331
|
+
const ddl = `DROP TABLE ${qualified(Q, [this.targetSchema(opts), name])}`;
|
|
332
|
+
await this.requireSql().unsafe(ddl);
|
|
333
|
+
return ddl;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
async truncateTable(name: string, opts?: SchemaOpts): Promise<string> {
|
|
337
|
+
await this.ensureDatabase(opts?.database);
|
|
338
|
+
assertSafeIdentifier(name);
|
|
339
|
+
const ddl = `TRUNCATE TABLE ${qualified(Q, [this.targetSchema(opts), name])}`;
|
|
340
|
+
await this.requireSql().unsafe(ddl);
|
|
341
|
+
return ddl;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async renameTable(name: string, newName: string, opts?: SchemaOpts): Promise<string> {
|
|
345
|
+
await this.ensureDatabase(opts?.database);
|
|
346
|
+
assertSafeIdentifier(name);
|
|
347
|
+
assertSafeIdentifier(newName);
|
|
348
|
+
const ddl = `ALTER TABLE ${qualified(Q, [this.targetSchema(opts), name])} RENAME TO ${Q(newName)}`;
|
|
349
|
+
await this.requireSql().unsafe(ddl);
|
|
350
|
+
return ddl;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
async createIndex(tableName: string, def: IndexDefinition, opts?: SchemaOpts): Promise<string> {
|
|
354
|
+
await this.ensureDatabase(opts?.database);
|
|
355
|
+
assertSafeIdentifier(tableName);
|
|
356
|
+
assertSafeIdentifier(def.name);
|
|
357
|
+
def.columns.forEach(assertSafeIdentifier);
|
|
358
|
+
const ddl = renderCreateIndex({ quote: Q, tableName, def, schema: this.targetSchema(opts) });
|
|
359
|
+
await this.requireSql().unsafe(ddl);
|
|
360
|
+
return ddl;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
async dropIndex(_tableName: string, indexName: string, opts?: SchemaOpts): Promise<string> {
|
|
364
|
+
await this.ensureDatabase(opts?.database);
|
|
365
|
+
assertSafeIdentifier(indexName);
|
|
366
|
+
const ddl = `DROP INDEX ${qualified(Q, [this.targetSchema(opts), indexName])}`;
|
|
367
|
+
await this.requireSql().unsafe(ddl);
|
|
368
|
+
return ddl;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
async createView(name: string, query: string, opts?: SchemaOpts): Promise<string> {
|
|
372
|
+
await this.ensureDatabase(opts?.database);
|
|
373
|
+
assertSafeIdentifier(name);
|
|
374
|
+
const ddl = `CREATE VIEW ${qualified(Q, [this.targetSchema(opts), name])} AS ${query}`;
|
|
375
|
+
await this.requireSql().unsafe(ddl);
|
|
376
|
+
return ddl;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async dropView(name: string, opts?: SchemaOpts): Promise<string> {
|
|
380
|
+
await this.ensureDatabase(opts?.database);
|
|
381
|
+
assertSafeIdentifier(name);
|
|
382
|
+
const ddl = `DROP VIEW ${qualified(Q, [this.targetSchema(opts), name])}`;
|
|
383
|
+
await this.requireSql().unsafe(ddl);
|
|
384
|
+
return ddl;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// ── Data CRUD ─────────────────────────────────────────────────────────
|
|
388
|
+
|
|
389
|
+
async insertRow(table: string, row: Record<string, unknown>, opts?: SchemaOpts): Promise<DbClientQueryResult> {
|
|
390
|
+
await this.ensureDatabase(opts?.database);
|
|
391
|
+
assertSafeIdentifier(table);
|
|
392
|
+
Object.keys(row).forEach(assertSafeIdentifier);
|
|
393
|
+
const { sql, params } = buildInsert({
|
|
394
|
+
quote: Q,
|
|
395
|
+
table,
|
|
396
|
+
row,
|
|
397
|
+
schema: this.targetSchema(opts),
|
|
398
|
+
placeholder: PG_PLACEHOLDER
|
|
399
|
+
});
|
|
400
|
+
return this.executeWrite(sql, params);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
async updateRow(
|
|
404
|
+
table: string,
|
|
405
|
+
pk: Record<string, unknown>,
|
|
406
|
+
changes: Record<string, unknown>,
|
|
407
|
+
opts?: SchemaOpts
|
|
408
|
+
): Promise<DbClientQueryResult> {
|
|
409
|
+
await this.ensureDatabase(opts?.database);
|
|
410
|
+
assertSafeIdentifier(table);
|
|
411
|
+
[...Object.keys(pk), ...Object.keys(changes)].forEach(assertSafeIdentifier);
|
|
412
|
+
const { sql, params } = buildUpdate({
|
|
413
|
+
quote: Q,
|
|
414
|
+
table,
|
|
415
|
+
pk,
|
|
416
|
+
changes,
|
|
417
|
+
schema: this.targetSchema(opts),
|
|
418
|
+
placeholder: PG_PLACEHOLDER
|
|
419
|
+
});
|
|
420
|
+
return this.executeWrite(sql, params);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
async deleteRows(table: string, pks: Record<string, unknown>[], opts?: SchemaOpts): Promise<DbClientQueryResult> {
|
|
424
|
+
await this.ensureDatabase(opts?.database);
|
|
425
|
+
assertSafeIdentifier(table);
|
|
426
|
+
if (pks.length > 0) Object.keys(pks[0]).forEach(assertSafeIdentifier);
|
|
427
|
+
const { sql, params } = buildDelete({
|
|
428
|
+
quote: Q,
|
|
429
|
+
table,
|
|
430
|
+
pks,
|
|
431
|
+
schema: this.targetSchema(opts),
|
|
432
|
+
placeholder: PG_PLACEHOLDER
|
|
433
|
+
});
|
|
434
|
+
return this.executeWrite(sql, params);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function notConnected(): DbClientHealth {
|
|
439
|
+
return {
|
|
440
|
+
ok: false,
|
|
441
|
+
latencyMs: null,
|
|
442
|
+
serverVersion: null,
|
|
443
|
+
sshOk: null,
|
|
444
|
+
error: 'Not connected'
|
|
445
|
+
};
|
|
446
|
+
}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Redis adapter — Bun.RedisClient per PHASE 0 findings.
|
|
3
|
+
*
|
|
4
|
+
* Query shape: command string `"GET foo"` or JSON command array
|
|
5
|
+
* `["HSET", "k", "f", "v"]`.
|
|
6
|
+
*
|
|
7
|
+
* "Schema" introspection lists keys via SCAN (capped at 1000) and
|
|
8
|
+
* exposes type/TTL on object details. Structure operations are
|
|
9
|
+
* key-level (rename, expire, delete).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { RedisClient } from 'bun';
|
|
13
|
+
import type {
|
|
14
|
+
DbClientConnection,
|
|
15
|
+
DbClientHealth,
|
|
16
|
+
DbClientObjectDetails,
|
|
17
|
+
DbClientQueryResult,
|
|
18
|
+
DbClientSchemaNode,
|
|
19
|
+
DbClientSchemaNodeType
|
|
20
|
+
} from '$shared/types/db-client';
|
|
21
|
+
import type { DbClientDriverAdapter } from './types';
|
|
22
|
+
import { debug } from '$shared/utils/logger';
|
|
23
|
+
|
|
24
|
+
const SCAN_CAP = 1000;
|
|
25
|
+
|
|
26
|
+
export class RedisAdapter implements DbClientDriverAdapter {
|
|
27
|
+
readonly kind = 'redis' as const;
|
|
28
|
+
|
|
29
|
+
private client: RedisClient | null = null;
|
|
30
|
+
private alive = false;
|
|
31
|
+
|
|
32
|
+
async connect(conn: DbClientConnection, tunnelPort?: number): Promise<void> {
|
|
33
|
+
const host = tunnelPort ? '127.0.0.1' : (conn.host ?? '127.0.0.1');
|
|
34
|
+
const port = tunnelPort ?? conn.port ?? 6379;
|
|
35
|
+
const pass = conn.password ? `:${encodeURIComponent(conn.password)}@` : '';
|
|
36
|
+
const dbIdx = conn.database && /^\d+$/.test(conn.database) ? `/${conn.database}` : '';
|
|
37
|
+
|
|
38
|
+
const url = `redis://${pass}${host}:${port}${dbIdx}`;
|
|
39
|
+
this.client = new RedisClient(url);
|
|
40
|
+
await this.client.connect();
|
|
41
|
+
this.alive = true;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async close(): Promise<void> {
|
|
45
|
+
this.alive = false;
|
|
46
|
+
if (this.client) {
|
|
47
|
+
try {
|
|
48
|
+
this.client.close();
|
|
49
|
+
} catch (err) {
|
|
50
|
+
debug.warn('db-client', 'Redis close error:', err);
|
|
51
|
+
}
|
|
52
|
+
this.client = null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
isAlive(): boolean {
|
|
57
|
+
return this.alive && this.client !== null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async health(): Promise<DbClientHealth> {
|
|
61
|
+
if (!this.client) return notConnected();
|
|
62
|
+
const start = performance.now();
|
|
63
|
+
try {
|
|
64
|
+
await this.client.send('PING', []);
|
|
65
|
+
let serverVersion: string | null = null;
|
|
66
|
+
try {
|
|
67
|
+
const info = (await this.client.send('INFO', ['server'])) as string;
|
|
68
|
+
const match = /redis_version:([^\r\n]+)/.exec(info ?? '');
|
|
69
|
+
serverVersion = match?.[1]?.trim() ?? null;
|
|
70
|
+
} catch {
|
|
71
|
+
serverVersion = null;
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
ok: true,
|
|
75
|
+
latencyMs: Math.round(performance.now() - start),
|
|
76
|
+
serverVersion,
|
|
77
|
+
sshOk: null,
|
|
78
|
+
error: null
|
|
79
|
+
};
|
|
80
|
+
} catch (err) {
|
|
81
|
+
return {
|
|
82
|
+
ok: false,
|
|
83
|
+
latencyMs: null,
|
|
84
|
+
serverVersion: null,
|
|
85
|
+
sshOk: null,
|
|
86
|
+
error: err instanceof Error ? err.message : String(err)
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private requireClient(): RedisClient {
|
|
92
|
+
if (!this.client) throw new Error('Redis not connected');
|
|
93
|
+
return this.client;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ── Schema (key listing) ──────────────────────────────────────────────
|
|
97
|
+
|
|
98
|
+
async listDatabases(): Promise<DbClientSchemaNode[]> {
|
|
99
|
+
// Redis has 16 logical DBs by default — surface 0..15 as virtual entries.
|
|
100
|
+
return Array.from({ length: 16 }, (_, i) => ({
|
|
101
|
+
name: String(i),
|
|
102
|
+
type: 'database' as const
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async listObjects(): Promise<DbClientSchemaNode[]> {
|
|
107
|
+
const client = this.requireClient();
|
|
108
|
+
const keys: string[] = [];
|
|
109
|
+
let cursor = '0';
|
|
110
|
+
do {
|
|
111
|
+
const reply = (await client.send('SCAN', [cursor, 'COUNT', '200'])) as [string, string[]];
|
|
112
|
+
cursor = reply[0];
|
|
113
|
+
for (const k of reply[1]) {
|
|
114
|
+
keys.push(k);
|
|
115
|
+
if (keys.length >= SCAN_CAP) break;
|
|
116
|
+
}
|
|
117
|
+
} while (cursor !== '0' && keys.length < SCAN_CAP);
|
|
118
|
+
keys.sort();
|
|
119
|
+
return keys.map((name) => ({ name, type: 'key' as const }));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async getObjectDetails(name: string, _type: DbClientSchemaNodeType): Promise<DbClientObjectDetails> {
|
|
123
|
+
const client = this.requireClient();
|
|
124
|
+
const [type, ttl] = await Promise.all([
|
|
125
|
+
client.send('TYPE', [name]) as Promise<string>,
|
|
126
|
+
client.send('TTL', [name]) as Promise<number>
|
|
127
|
+
]);
|
|
128
|
+
return {
|
|
129
|
+
name,
|
|
130
|
+
type: 'key',
|
|
131
|
+
redisValueType: type,
|
|
132
|
+
redisTtlSeconds: ttl < 0 ? null : ttl
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// ── Query execution ──────────────────────────────────────────────────
|
|
137
|
+
|
|
138
|
+
async executeRead(q: string): Promise<DbClientQueryResult> {
|
|
139
|
+
return this.runCommand(q);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async executeWrite(q: string): Promise<DbClientQueryResult> {
|
|
143
|
+
return this.runCommand(q);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private async runCommand(q: string): Promise<DbClientQueryResult> {
|
|
147
|
+
const { cmd, args } = parseRedisCommand(q);
|
|
148
|
+
const client = this.requireClient();
|
|
149
|
+
const start = performance.now();
|
|
150
|
+
const reply = await client.send(cmd, args);
|
|
151
|
+
const durationMs = Math.round(performance.now() - start);
|
|
152
|
+
const rows = formatReply(reply);
|
|
153
|
+
const columns = rows.length > 0
|
|
154
|
+
? Object.keys(rows[0]).map((name) => ({ name, type: null as string | null }))
|
|
155
|
+
: [];
|
|
156
|
+
return {
|
|
157
|
+
columns,
|
|
158
|
+
rows,
|
|
159
|
+
rowCount: rows.length,
|
|
160
|
+
affectedRows: null,
|
|
161
|
+
durationMs,
|
|
162
|
+
driverMeta: {}
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// ── "Structure" — key-level operations ───────────────────────────────
|
|
167
|
+
|
|
168
|
+
async dropTable(name: string): Promise<string> {
|
|
169
|
+
await this.requireClient().send('DEL', [name]);
|
|
170
|
+
return `DEL ${name}`;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async renameTable(name: string, newName: string): Promise<string> {
|
|
174
|
+
await this.requireClient().send('RENAME', [name, newName]);
|
|
175
|
+
return `RENAME ${name} ${newName}`;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async deleteRows(table: string, _pks: Record<string, unknown>[]): Promise<DbClientQueryResult> {
|
|
179
|
+
await this.requireClient().send('DEL', [table]);
|
|
180
|
+
return {
|
|
181
|
+
columns: [],
|
|
182
|
+
rows: [],
|
|
183
|
+
rowCount: 0,
|
|
184
|
+
affectedRows: 1,
|
|
185
|
+
durationMs: 0,
|
|
186
|
+
driverMeta: {}
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function parseRedisCommand(q: string): { cmd: string; args: string[] } {
|
|
192
|
+
const trimmed = q.trim();
|
|
193
|
+
if (trimmed.startsWith('[')) {
|
|
194
|
+
try {
|
|
195
|
+
const parsed = JSON.parse(trimmed) as unknown;
|
|
196
|
+
if (Array.isArray(parsed) && parsed.length > 0) {
|
|
197
|
+
return {
|
|
198
|
+
cmd: String(parsed[0]).toUpperCase(),
|
|
199
|
+
args: parsed.slice(1).map((v) => String(v))
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
} catch {
|
|
203
|
+
// fall through to plain parsing
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
// Naive whitespace tokenizer — quoted args supported.
|
|
207
|
+
const tokens = tokenize(trimmed);
|
|
208
|
+
if (tokens.length === 0) throw new Error('Empty Redis command');
|
|
209
|
+
return { cmd: tokens[0].toUpperCase(), args: tokens.slice(1) };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function tokenize(s: string): string[] {
|
|
213
|
+
const out: string[] = [];
|
|
214
|
+
let buf = '';
|
|
215
|
+
let quote: '"' | "'" | null = null;
|
|
216
|
+
for (let i = 0; i < s.length; i++) {
|
|
217
|
+
const ch = s[i];
|
|
218
|
+
if (quote) {
|
|
219
|
+
if (ch === quote) {
|
|
220
|
+
quote = null;
|
|
221
|
+
} else if (ch === '\\' && i + 1 < s.length) {
|
|
222
|
+
buf += s[++i];
|
|
223
|
+
} else {
|
|
224
|
+
buf += ch;
|
|
225
|
+
}
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (ch === '"' || ch === "'") {
|
|
229
|
+
quote = ch;
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
if (/\s/.test(ch)) {
|
|
233
|
+
if (buf) { out.push(buf); buf = ''; }
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
buf += ch;
|
|
237
|
+
}
|
|
238
|
+
if (buf) out.push(buf);
|
|
239
|
+
return out;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function formatReply(reply: unknown): Array<Record<string, unknown>> {
|
|
243
|
+
if (reply === null || reply === undefined) {
|
|
244
|
+
return [{ value: null }];
|
|
245
|
+
}
|
|
246
|
+
if (typeof reply === 'string' || typeof reply === 'number' || typeof reply === 'boolean') {
|
|
247
|
+
return [{ value: reply }];
|
|
248
|
+
}
|
|
249
|
+
if (Array.isArray(reply)) {
|
|
250
|
+
return reply.map((v, i) => ({ index: i, value: v }));
|
|
251
|
+
}
|
|
252
|
+
if (typeof reply === 'object') {
|
|
253
|
+
// HGETALL etc. return null-prototype objects per Phase 0.
|
|
254
|
+
return [{ ...(reply as Record<string, unknown>) }];
|
|
255
|
+
}
|
|
256
|
+
return [{ value: String(reply) }];
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function notConnected(): DbClientHealth {
|
|
260
|
+
return {
|
|
261
|
+
ok: false,
|
|
262
|
+
latencyMs: null,
|
|
263
|
+
serverVersion: null,
|
|
264
|
+
sshOk: null,
|
|
265
|
+
error: 'Not connected'
|
|
266
|
+
};
|
|
267
|
+
}
|