@myrialabs/clopen 0.3.6 → 0.3.8
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/README.md +4 -4
- 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/index.ts +14 -0
- package/backend/database/queries/db-client-connection-queries.ts +237 -0
- package/backend/database/queries/db-client-query-history-queries.ts +113 -0
- package/backend/database/queries/index.ts +3 -1
- package/backend/database/queries/project-queries.ts +23 -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/install-recipes.ts +216 -137
- package/backend/engine/install-runner.ts +39 -0
- package/backend/git/git-service.ts +12 -0
- package/backend/mcp/servers/browser-automation/index.ts +6 -6
- package/backend/preview/browser/browser-pool.ts +10 -9
- package/backend/preview/browser/scripts/video-stream.ts +9 -3
- package/backend/tunnel/cloudflared/binary.ts +22 -4
- package/backend/tunnel/cloudflared/index.ts +2 -1
- package/backend/tunnel/cloudflared/tunnel.ts +17 -4
- package/backend/tunnel/global-tunnel-manager.ts +29 -51
- package/backend/tunnel/project-tunnel-manager.ts +14 -53
- package/backend/ws/db-client/connections.ts +180 -0
- package/backend/ws/db-client/index.ts +17 -0
- package/backend/ws/db-client/io.ts +458 -0
- package/backend/ws/db-client/query.ts +162 -0
- package/backend/ws/db-client/schema.ts +76 -0
- package/backend/ws/db-client/structure.ts +218 -0
- package/backend/ws/files/index.ts +5 -1
- package/backend/ws/files/read.ts +32 -0
- package/backend/ws/files/state.ts +39 -0
- package/backend/ws/index.ts +6 -2
- package/backend/ws/system-tools/install.ts +2 -1
- package/backend/ws/system-tools/status.ts +5 -4
- package/dist/assets/{index-BU8wB4Fg.js → index-DqAGCTFT.js} +2 -2
- package/dist/assets/{main-cQx6vfxB.js → main-DsED0rLr.js} +244 -192
- package/dist/assets/main-eWY9R8g9.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +4 -2
- package/shared/constants/preview.ts +48 -4
- package/shared/types/database/schema.ts +48 -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/utils/logger.ts +1 -0
- package/dist/assets/main-B3tMwjjU.css +0 -1
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared SQL builder helpers for MySQL / PostgreSQL / SQLite adapters.
|
|
3
|
+
*
|
|
4
|
+
* All builders return parameterized statements so user values are
|
|
5
|
+
* never interpolated into the SQL string.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { ColumnDefinition, IndexDefinition, TableDefinition } from './types';
|
|
9
|
+
|
|
10
|
+
const MYSQL_RESERVED_RX = /[^A-Za-z0-9_$]/;
|
|
11
|
+
|
|
12
|
+
export function quoteMysql(name: string): string {
|
|
13
|
+
if (!name) throw new Error('Identifier cannot be empty');
|
|
14
|
+
if (name.includes('`')) throw new Error(`Invalid identifier: ${name}`);
|
|
15
|
+
return `\`${name}\``;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function quotePg(name: string): string {
|
|
19
|
+
if (!name) throw new Error('Identifier cannot be empty');
|
|
20
|
+
if (name.includes('"')) throw new Error(`Invalid identifier: ${name}`);
|
|
21
|
+
return `"${name}"`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function quoteSqlite(name: string): string {
|
|
25
|
+
return quotePg(name);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type Quoter = (name: string) => string;
|
|
29
|
+
|
|
30
|
+
export function qualified(quote: Quoter, parts: Array<string | undefined | null>): string {
|
|
31
|
+
return parts.filter((p): p is string => Boolean(p)).map(quote).join('.');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface BuildInsertInput {
|
|
35
|
+
quote: Quoter;
|
|
36
|
+
table: string;
|
|
37
|
+
row: Record<string, unknown>;
|
|
38
|
+
schema?: string;
|
|
39
|
+
database?: string;
|
|
40
|
+
placeholder: (i: number) => string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function buildInsert({
|
|
44
|
+
quote,
|
|
45
|
+
table,
|
|
46
|
+
row,
|
|
47
|
+
schema,
|
|
48
|
+
database,
|
|
49
|
+
placeholder
|
|
50
|
+
}: BuildInsertInput): { sql: string; params: unknown[] } {
|
|
51
|
+
const cols = Object.keys(row);
|
|
52
|
+
if (cols.length === 0) throw new Error('Insert requires at least one column');
|
|
53
|
+
const params = cols.map((c) => row[c]);
|
|
54
|
+
const fqt = qualified(quote, [database, schema, table]);
|
|
55
|
+
const colSql = cols.map(quote).join(', ');
|
|
56
|
+
const placeholders = cols.map((_, i) => placeholder(i)).join(', ');
|
|
57
|
+
return {
|
|
58
|
+
sql: `INSERT INTO ${fqt} (${colSql}) VALUES (${placeholders})`,
|
|
59
|
+
params
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface BuildUpdateInput {
|
|
64
|
+
quote: Quoter;
|
|
65
|
+
table: string;
|
|
66
|
+
pk: Record<string, unknown>;
|
|
67
|
+
changes: Record<string, unknown>;
|
|
68
|
+
schema?: string;
|
|
69
|
+
database?: string;
|
|
70
|
+
placeholder: (i: number) => string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function buildUpdate({
|
|
74
|
+
quote,
|
|
75
|
+
table,
|
|
76
|
+
pk,
|
|
77
|
+
changes,
|
|
78
|
+
schema,
|
|
79
|
+
database,
|
|
80
|
+
placeholder
|
|
81
|
+
}: BuildUpdateInput): { sql: string; params: unknown[] } {
|
|
82
|
+
const setCols = Object.keys(changes);
|
|
83
|
+
const pkCols = Object.keys(pk);
|
|
84
|
+
if (setCols.length === 0) throw new Error('Update requires at least one change');
|
|
85
|
+
if (pkCols.length === 0) throw new Error('Update requires a primary key');
|
|
86
|
+
|
|
87
|
+
const params: unknown[] = [];
|
|
88
|
+
const setSql = setCols.map((c) => {
|
|
89
|
+
params.push(changes[c]);
|
|
90
|
+
return `${quote(c)} = ${placeholder(params.length - 1)}`;
|
|
91
|
+
}).join(', ');
|
|
92
|
+
|
|
93
|
+
const whereSql = pkCols.map((c) => {
|
|
94
|
+
params.push(pk[c]);
|
|
95
|
+
return `${quote(c)} = ${placeholder(params.length - 1)}`;
|
|
96
|
+
}).join(' AND ');
|
|
97
|
+
|
|
98
|
+
const fqt = qualified(quote, [database, schema, table]);
|
|
99
|
+
return {
|
|
100
|
+
sql: `UPDATE ${fqt} SET ${setSql} WHERE ${whereSql}`,
|
|
101
|
+
params
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
interface BuildDeleteInput {
|
|
106
|
+
quote: Quoter;
|
|
107
|
+
table: string;
|
|
108
|
+
pks: Record<string, unknown>[];
|
|
109
|
+
schema?: string;
|
|
110
|
+
database?: string;
|
|
111
|
+
placeholder: (i: number) => string;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function buildDelete({
|
|
115
|
+
quote,
|
|
116
|
+
table,
|
|
117
|
+
pks,
|
|
118
|
+
schema,
|
|
119
|
+
database,
|
|
120
|
+
placeholder
|
|
121
|
+
}: BuildDeleteInput): { sql: string; params: unknown[] } {
|
|
122
|
+
if (pks.length === 0) throw new Error('Delete requires at least one row');
|
|
123
|
+
const cols = Object.keys(pks[0]);
|
|
124
|
+
if (cols.length === 0) throw new Error('Delete requires a primary key');
|
|
125
|
+
|
|
126
|
+
const params: unknown[] = [];
|
|
127
|
+
const groups: string[] = [];
|
|
128
|
+
for (const pk of pks) {
|
|
129
|
+
const conds = cols.map((c) => {
|
|
130
|
+
params.push(pk[c]);
|
|
131
|
+
return `${quote(c)} = ${placeholder(params.length - 1)}`;
|
|
132
|
+
}).join(' AND ');
|
|
133
|
+
groups.push(`(${conds})`);
|
|
134
|
+
}
|
|
135
|
+
const fqt = qualified(quote, [database, schema, table]);
|
|
136
|
+
return {
|
|
137
|
+
sql: `DELETE FROM ${fqt} WHERE ${groups.join(' OR ')}`,
|
|
138
|
+
params
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
interface RenderColumnInput {
|
|
143
|
+
quote: Quoter;
|
|
144
|
+
column: ColumnDefinition;
|
|
145
|
+
driver: 'mysql' | 'postgres' | 'sqlite';
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function renderColumn({ quote, column, driver }: RenderColumnInput): string {
|
|
149
|
+
const parts = [quote(column.name), column.type];
|
|
150
|
+
if (column.nullable === false) parts.push('NOT NULL');
|
|
151
|
+
if (column.default !== undefined && column.default !== null && column.default !== '') {
|
|
152
|
+
parts.push(`DEFAULT ${column.default}`);
|
|
153
|
+
}
|
|
154
|
+
if (column.autoIncrement) {
|
|
155
|
+
if (driver === 'mysql') parts.push('AUTO_INCREMENT');
|
|
156
|
+
else if (driver === 'sqlite') parts.push('AUTOINCREMENT');
|
|
157
|
+
// PG handled via SERIAL/IDENTITY in the type itself; nothing to append.
|
|
158
|
+
}
|
|
159
|
+
if (column.primary) parts.push('PRIMARY KEY');
|
|
160
|
+
if (column.unique) parts.push('UNIQUE');
|
|
161
|
+
return parts.join(' ');
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
interface RenderTableInput {
|
|
165
|
+
quote: Quoter;
|
|
166
|
+
definition: TableDefinition;
|
|
167
|
+
schema?: string;
|
|
168
|
+
database?: string;
|
|
169
|
+
driver: 'mysql' | 'postgres' | 'sqlite';
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function renderCreateTable({
|
|
173
|
+
quote,
|
|
174
|
+
definition,
|
|
175
|
+
schema,
|
|
176
|
+
database,
|
|
177
|
+
driver
|
|
178
|
+
}: RenderTableInput): string {
|
|
179
|
+
if (definition.columns.length === 0) throw new Error('Table needs at least one column');
|
|
180
|
+
const colSql = definition.columns.map((column) => renderColumn({ quote, column, driver }));
|
|
181
|
+
const fqt = qualified(quote, [database, schema, definition.name]);
|
|
182
|
+
if (definition.primaryKey && definition.primaryKey.length > 0) {
|
|
183
|
+
colSql.push(`PRIMARY KEY (${definition.primaryKey.map(quote).join(', ')})`);
|
|
184
|
+
}
|
|
185
|
+
return `CREATE TABLE ${fqt} (${colSql.join(', ')})`;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
interface RenderIndexInput {
|
|
189
|
+
quote: Quoter;
|
|
190
|
+
tableName: string;
|
|
191
|
+
def: IndexDefinition;
|
|
192
|
+
schema?: string;
|
|
193
|
+
database?: string;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function renderCreateIndex({
|
|
197
|
+
quote,
|
|
198
|
+
tableName,
|
|
199
|
+
def,
|
|
200
|
+
schema,
|
|
201
|
+
database
|
|
202
|
+
}: RenderIndexInput): string {
|
|
203
|
+
if (def.columns.length === 0) throw new Error('Index needs at least one column');
|
|
204
|
+
const fqt = qualified(quote, [database, schema, tableName]);
|
|
205
|
+
const cols = def.columns.map(quote).join(', ');
|
|
206
|
+
const unique = def.unique ? 'UNIQUE ' : '';
|
|
207
|
+
return `CREATE ${unique}INDEX ${quote(def.name)} ON ${fqt} (${cols})`;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Validate identifier shape — defense-in-depth before quoting. */
|
|
211
|
+
export function assertSafeIdentifier(name: string): void {
|
|
212
|
+
if (!name || MYSQL_RESERVED_RX.test(name)) {
|
|
213
|
+
throw new Error(`Invalid identifier: ${name}`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQLite adapter — bun:sqlite (native, ships SQLite 3.51.0 per PHASE 0).
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { Database } from 'bun:sqlite';
|
|
6
|
+
import { homedir } from 'os';
|
|
7
|
+
import { resolve } from 'path';
|
|
8
|
+
import type {
|
|
9
|
+
DbClientConnection,
|
|
10
|
+
DbClientHealth,
|
|
11
|
+
DbClientObjectColumn,
|
|
12
|
+
DbClientObjectDetails,
|
|
13
|
+
DbClientObjectForeignKey,
|
|
14
|
+
DbClientObjectIndex,
|
|
15
|
+
DbClientQueryResult,
|
|
16
|
+
DbClientSchemaNode,
|
|
17
|
+
DbClientSchemaNodeType
|
|
18
|
+
} from '$shared/types/db-client';
|
|
19
|
+
import type {
|
|
20
|
+
AlterOperation,
|
|
21
|
+
DbClientDriverAdapter,
|
|
22
|
+
IndexDefinition,
|
|
23
|
+
SchemaOpts,
|
|
24
|
+
TableDefinition
|
|
25
|
+
} from './types';
|
|
26
|
+
import {
|
|
27
|
+
assertSafeIdentifier,
|
|
28
|
+
buildDelete,
|
|
29
|
+
buildInsert,
|
|
30
|
+
buildUpdate,
|
|
31
|
+
quoteSqlite,
|
|
32
|
+
renderColumn,
|
|
33
|
+
renderCreateIndex,
|
|
34
|
+
renderCreateTable
|
|
35
|
+
} from './sql-builders';
|
|
36
|
+
|
|
37
|
+
const Q = quoteSqlite;
|
|
38
|
+
|
|
39
|
+
function expandHome(p: string): string {
|
|
40
|
+
if (p === '~') return homedir();
|
|
41
|
+
if (p.startsWith('~/')) return resolve(homedir(), p.slice(2));
|
|
42
|
+
if (p.startsWith('/.')) return resolve(homedir(), p.slice(1));
|
|
43
|
+
return p;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class SqliteAdapter implements DbClientDriverAdapter {
|
|
47
|
+
readonly kind = 'sqlite' as const;
|
|
48
|
+
|
|
49
|
+
private db: Database | null = null;
|
|
50
|
+
private alive = false;
|
|
51
|
+
private version = '0.0.0';
|
|
52
|
+
|
|
53
|
+
async connect(conn: DbClientConnection): Promise<void> {
|
|
54
|
+
const raw = (conn.database ?? '').trim();
|
|
55
|
+
if (!raw) throw new Error('SQLite requires a file path in the `database` field');
|
|
56
|
+
const path = expandHome(raw);
|
|
57
|
+
this.db = new Database(path);
|
|
58
|
+
const v = this.db.query('SELECT sqlite_version() AS version').get() as { version: string };
|
|
59
|
+
this.version = v.version;
|
|
60
|
+
this.alive = true;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async close(): Promise<void> {
|
|
64
|
+
this.alive = false;
|
|
65
|
+
if (this.db) {
|
|
66
|
+
this.db.close();
|
|
67
|
+
this.db = null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
isAlive(): boolean {
|
|
72
|
+
return this.alive && this.db !== null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async health(): Promise<DbClientHealth> {
|
|
76
|
+
if (!this.db) return notConnected();
|
|
77
|
+
const start = performance.now();
|
|
78
|
+
try {
|
|
79
|
+
const row = this.db.query('SELECT sqlite_version() AS version').get() as { version: string } | null;
|
|
80
|
+
return {
|
|
81
|
+
ok: true,
|
|
82
|
+
latencyMs: Math.round(performance.now() - start),
|
|
83
|
+
serverVersion: row?.version ?? null,
|
|
84
|
+
sshOk: null,
|
|
85
|
+
error: null
|
|
86
|
+
};
|
|
87
|
+
} catch (err) {
|
|
88
|
+
return {
|
|
89
|
+
ok: false,
|
|
90
|
+
latencyMs: null,
|
|
91
|
+
serverVersion: null,
|
|
92
|
+
sshOk: null,
|
|
93
|
+
error: err instanceof Error ? err.message : String(err)
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
private requireDb(): Database {
|
|
99
|
+
if (!this.db) throw new Error('SQLite not connected');
|
|
100
|
+
return this.db;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private versionAtLeast(min: string): boolean {
|
|
104
|
+
const split = (s: string): number[] => s.split('.').map(Number);
|
|
105
|
+
const [a1, a2 = 0, a3 = 0] = split(this.version);
|
|
106
|
+
const [b1, b2 = 0, b3 = 0] = split(min);
|
|
107
|
+
if (a1 !== b1) return a1 > b1;
|
|
108
|
+
if (a2 !== b2) return a2 > b2;
|
|
109
|
+
return a3 >= b3;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async executeRead(q: string, params: unknown[] = []): Promise<DbClientQueryResult> {
|
|
113
|
+
const db = this.requireDb();
|
|
114
|
+
const start = performance.now();
|
|
115
|
+
const stmt = db.query(q);
|
|
116
|
+
const rows = (params.length > 0
|
|
117
|
+
? stmt.all(...(params as never[]))
|
|
118
|
+
: stmt.all()) as Array<Record<string, unknown>>;
|
|
119
|
+
const durationMs = Math.round(performance.now() - start);
|
|
120
|
+
const columns = rows.length > 0
|
|
121
|
+
? Object.keys(rows[0]).map((name) => ({ name, type: null as string | null }))
|
|
122
|
+
: [];
|
|
123
|
+
return {
|
|
124
|
+
columns,
|
|
125
|
+
rows,
|
|
126
|
+
rowCount: rows.length,
|
|
127
|
+
affectedRows: null,
|
|
128
|
+
durationMs,
|
|
129
|
+
driverMeta: {}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async executeWrite(q: string, params: unknown[] = []): Promise<DbClientQueryResult> {
|
|
134
|
+
const db = this.requireDb();
|
|
135
|
+
const start = performance.now();
|
|
136
|
+
const stmt = db.prepare(q);
|
|
137
|
+
const result = (params.length > 0
|
|
138
|
+
? stmt.run(...(params as never[]))
|
|
139
|
+
: stmt.run()) as { changes: number; lastInsertRowid: number | bigint };
|
|
140
|
+
return {
|
|
141
|
+
columns: [],
|
|
142
|
+
rows: [],
|
|
143
|
+
rowCount: 0,
|
|
144
|
+
affectedRows: result.changes,
|
|
145
|
+
durationMs: Math.round(performance.now() - start),
|
|
146
|
+
driverMeta: { lastInsertRowid: result.lastInsertRowid?.toString() ?? null }
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async explain(q: string): Promise<DbClientQueryResult> {
|
|
151
|
+
return this.executeRead(`EXPLAIN QUERY PLAN ${q}`);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ── Schema ────────────────────────────────────────────────────────────
|
|
155
|
+
|
|
156
|
+
async listDatabases(): Promise<DbClientSchemaNode[]> {
|
|
157
|
+
// SQLite has only the open file — surface it as a single virtual database.
|
|
158
|
+
const filename = this.requireDb().filename;
|
|
159
|
+
return [{ name: filename || 'main', type: 'database' as const }];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async listObjects(): Promise<DbClientSchemaNode[]> {
|
|
163
|
+
const rows = this.requireDb().query(
|
|
164
|
+
"SELECT name, type FROM sqlite_master WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
165
|
+
).all() as Array<{ name: string; type: string }>;
|
|
166
|
+
return rows.map((r) => ({
|
|
167
|
+
name: r.name,
|
|
168
|
+
type: r.type === 'view' ? 'view' as const : 'table' as const
|
|
169
|
+
}));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async getObjectDetails(name: string): Promise<DbClientObjectDetails> {
|
|
173
|
+
const db = this.requireDb();
|
|
174
|
+
assertSafeIdentifier(name);
|
|
175
|
+
|
|
176
|
+
const colRows = db.query(`PRAGMA table_info(${Q(name)})`).all() as Array<Record<string, unknown>>;
|
|
177
|
+
const columns: DbClientObjectColumn[] = colRows.map((r) => ({
|
|
178
|
+
name: String(r.name),
|
|
179
|
+
type: String(r.type ?? ''),
|
|
180
|
+
nullable: r.notnull === 0,
|
|
181
|
+
default: r.dflt_value === null ? null : String(r.dflt_value),
|
|
182
|
+
isPrimary: typeof r.pk === 'number' ? r.pk > 0 : Boolean(r.pk),
|
|
183
|
+
isUnique: false
|
|
184
|
+
}));
|
|
185
|
+
|
|
186
|
+
const idxRows = db.query(`PRAGMA index_list(${Q(name)})`).all() as Array<Record<string, unknown>>;
|
|
187
|
+
const indexes: DbClientObjectIndex[] = [];
|
|
188
|
+
for (const r of idxRows) {
|
|
189
|
+
const idxName = String(r.name);
|
|
190
|
+
const cols = (db.query(`PRAGMA index_info(${Q(idxName)})`).all() as Array<{ name: string }>)
|
|
191
|
+
.map((c) => c.name);
|
|
192
|
+
indexes.push({
|
|
193
|
+
name: idxName,
|
|
194
|
+
columns: cols,
|
|
195
|
+
unique: r.unique === 1
|
|
196
|
+
});
|
|
197
|
+
// Mark unique columns
|
|
198
|
+
if (r.unique === 1 && cols.length === 1) {
|
|
199
|
+
const col = columns.find((c) => c.name === cols[0]);
|
|
200
|
+
if (col) col.isUnique = true;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const fkRows = db.query(`PRAGMA foreign_key_list(${Q(name)})`).all() as Array<Record<string, unknown>>;
|
|
205
|
+
const foreignKeys: DbClientObjectForeignKey[] = fkRows.map((r) => ({
|
|
206
|
+
column: String(r.from),
|
|
207
|
+
refTable: String(r.table),
|
|
208
|
+
refColumn: String(r.to)
|
|
209
|
+
}));
|
|
210
|
+
|
|
211
|
+
return { name, type: 'table', columns, indexes, foreignKeys };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ── Structure ─────────────────────────────────────────────────────────
|
|
215
|
+
|
|
216
|
+
async createTable(definition: TableDefinition): Promise<string> {
|
|
217
|
+
assertSafeIdentifier(definition.name);
|
|
218
|
+
const ddl = renderCreateTable({ quote: Q, definition, driver: 'sqlite' });
|
|
219
|
+
this.requireDb().run(ddl);
|
|
220
|
+
return ddl;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async alterTable(name: string, operations: AlterOperation[]): Promise<string> {
|
|
224
|
+
assertSafeIdentifier(name);
|
|
225
|
+
const fqt = Q(name);
|
|
226
|
+
const ddls: string[] = [];
|
|
227
|
+
for (const op of operations) {
|
|
228
|
+
switch (op.kind) {
|
|
229
|
+
case 'add-column':
|
|
230
|
+
assertSafeIdentifier(op.column.name);
|
|
231
|
+
ddls.push(`ALTER TABLE ${fqt} ADD COLUMN ${renderColumn({ quote: Q, column: op.column, driver: 'sqlite' })}`);
|
|
232
|
+
break;
|
|
233
|
+
case 'drop-column':
|
|
234
|
+
if (!this.versionAtLeast('3.35.0')) {
|
|
235
|
+
throw new Error(`SQLite ${this.version} does not support DROP COLUMN (requires 3.35+)`);
|
|
236
|
+
}
|
|
237
|
+
assertSafeIdentifier(op.name);
|
|
238
|
+
ddls.push(`ALTER TABLE ${fqt} DROP COLUMN ${Q(op.name)}`);
|
|
239
|
+
break;
|
|
240
|
+
case 'rename-column':
|
|
241
|
+
if (!this.versionAtLeast('3.25.0')) {
|
|
242
|
+
throw new Error(`SQLite ${this.version} does not support RENAME COLUMN (requires 3.25+)`);
|
|
243
|
+
}
|
|
244
|
+
assertSafeIdentifier(op.name);
|
|
245
|
+
assertSafeIdentifier(op.newName);
|
|
246
|
+
ddls.push(`ALTER TABLE ${fqt} RENAME COLUMN ${Q(op.name)} TO ${Q(op.newName)}`);
|
|
247
|
+
break;
|
|
248
|
+
case 'modify-column':
|
|
249
|
+
throw new Error('SQLite does not support MODIFY COLUMN — recreate the table to change a column type');
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
const db = this.requireDb();
|
|
253
|
+
for (const ddl of ddls) db.run(ddl);
|
|
254
|
+
return ddls.join('; ');
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
async dropTable(name: string): Promise<string> {
|
|
258
|
+
assertSafeIdentifier(name);
|
|
259
|
+
const ddl = `DROP TABLE ${Q(name)}`;
|
|
260
|
+
this.requireDb().run(ddl);
|
|
261
|
+
return ddl;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async truncateTable(name: string): Promise<string> {
|
|
265
|
+
assertSafeIdentifier(name);
|
|
266
|
+
const ddl = `DELETE FROM ${Q(name)}`;
|
|
267
|
+
this.requireDb().run(ddl);
|
|
268
|
+
return ddl;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async renameTable(name: string, newName: string): Promise<string> {
|
|
272
|
+
assertSafeIdentifier(name);
|
|
273
|
+
assertSafeIdentifier(newName);
|
|
274
|
+
const ddl = `ALTER TABLE ${Q(name)} RENAME TO ${Q(newName)}`;
|
|
275
|
+
this.requireDb().run(ddl);
|
|
276
|
+
return ddl;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async createIndex(tableName: string, def: IndexDefinition): Promise<string> {
|
|
280
|
+
assertSafeIdentifier(tableName);
|
|
281
|
+
assertSafeIdentifier(def.name);
|
|
282
|
+
def.columns.forEach(assertSafeIdentifier);
|
|
283
|
+
const ddl = renderCreateIndex({ quote: Q, tableName, def });
|
|
284
|
+
this.requireDb().run(ddl);
|
|
285
|
+
return ddl;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async dropIndex(_tableName: string, indexName: string): Promise<string> {
|
|
289
|
+
assertSafeIdentifier(indexName);
|
|
290
|
+
const ddl = `DROP INDEX ${Q(indexName)}`;
|
|
291
|
+
this.requireDb().run(ddl);
|
|
292
|
+
return ddl;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async createView(name: string, query: string): Promise<string> {
|
|
296
|
+
assertSafeIdentifier(name);
|
|
297
|
+
const ddl = `CREATE VIEW ${Q(name)} AS ${query}`;
|
|
298
|
+
this.requireDb().run(ddl);
|
|
299
|
+
return ddl;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async dropView(name: string): Promise<string> {
|
|
303
|
+
assertSafeIdentifier(name);
|
|
304
|
+
const ddl = `DROP VIEW ${Q(name)}`;
|
|
305
|
+
this.requireDb().run(ddl);
|
|
306
|
+
return ddl;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// ── Data CRUD ─────────────────────────────────────────────────────────
|
|
310
|
+
|
|
311
|
+
async insertRow(table: string, row: Record<string, unknown>): Promise<DbClientQueryResult> {
|
|
312
|
+
assertSafeIdentifier(table);
|
|
313
|
+
Object.keys(row).forEach(assertSafeIdentifier);
|
|
314
|
+
const { sql, params } = buildInsert({ quote: Q, table, row, placeholder: () => '?' });
|
|
315
|
+
return this.executeWrite(sql, params);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async updateRow(
|
|
319
|
+
table: string,
|
|
320
|
+
pk: Record<string, unknown>,
|
|
321
|
+
changes: Record<string, unknown>
|
|
322
|
+
): Promise<DbClientQueryResult> {
|
|
323
|
+
assertSafeIdentifier(table);
|
|
324
|
+
[...Object.keys(pk), ...Object.keys(changes)].forEach(assertSafeIdentifier);
|
|
325
|
+
const { sql, params } = buildUpdate({ quote: Q, table, pk, changes, placeholder: () => '?' });
|
|
326
|
+
return this.executeWrite(sql, params);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async deleteRows(table: string, pks: Record<string, unknown>[]): Promise<DbClientQueryResult> {
|
|
330
|
+
assertSafeIdentifier(table);
|
|
331
|
+
if (pks.length > 0) Object.keys(pks[0]).forEach(assertSafeIdentifier);
|
|
332
|
+
const { sql, params } = buildDelete({ quote: Q, table, pks, placeholder: () => '?' });
|
|
333
|
+
return this.executeWrite(sql, params);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function notConnected(): DbClientHealth {
|
|
338
|
+
return {
|
|
339
|
+
ok: false,
|
|
340
|
+
latencyMs: null,
|
|
341
|
+
serverVersion: null,
|
|
342
|
+
sshOk: null,
|
|
343
|
+
error: 'Not connected'
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* db-client — unified driver adapter interface.
|
|
3
|
+
*
|
|
4
|
+
* Phase 1 implemented: connect / close / health.
|
|
5
|
+
* Phase 2 adds: schema introspection, query execution, data CRUD,
|
|
6
|
+
* and structure management. Methods that don't apply to every driver
|
|
7
|
+
* (e.g. table operations on Redis) remain optional.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type {
|
|
11
|
+
DbClientConnection,
|
|
12
|
+
DbClientHealth,
|
|
13
|
+
DbClientObjectDetails,
|
|
14
|
+
DbClientQueryResult,
|
|
15
|
+
DbClientSchemaNode,
|
|
16
|
+
DbClientSchemaNodeType,
|
|
17
|
+
DbDriver
|
|
18
|
+
} from '$shared/types/db-client';
|
|
19
|
+
|
|
20
|
+
export interface SchemaOpts {
|
|
21
|
+
database?: string;
|
|
22
|
+
schema?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ColumnDefinition {
|
|
26
|
+
name: string;
|
|
27
|
+
type: string;
|
|
28
|
+
nullable?: boolean;
|
|
29
|
+
default?: string | null;
|
|
30
|
+
primary?: boolean;
|
|
31
|
+
unique?: boolean;
|
|
32
|
+
autoIncrement?: boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface TableDefinition {
|
|
36
|
+
name: string;
|
|
37
|
+
columns: ColumnDefinition[];
|
|
38
|
+
primaryKey?: string[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface IndexDefinition {
|
|
42
|
+
name: string;
|
|
43
|
+
columns: string[];
|
|
44
|
+
unique?: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type AlterOperation =
|
|
48
|
+
| { kind: 'add-column'; column: ColumnDefinition }
|
|
49
|
+
| { kind: 'drop-column'; name: string }
|
|
50
|
+
| { kind: 'rename-column'; name: string; newName: string }
|
|
51
|
+
| { kind: 'modify-column'; column: ColumnDefinition };
|
|
52
|
+
|
|
53
|
+
export interface DbClientDriverAdapter {
|
|
54
|
+
readonly kind: DbDriver;
|
|
55
|
+
|
|
56
|
+
connect(conn: DbClientConnection, tunnelPort?: number): Promise<void>;
|
|
57
|
+
close(): Promise<void>;
|
|
58
|
+
isAlive(): boolean;
|
|
59
|
+
health(): Promise<DbClientHealth>;
|
|
60
|
+
|
|
61
|
+
listDatabases?(): Promise<DbClientSchemaNode[]>;
|
|
62
|
+
listSchemas?(database?: string): Promise<DbClientSchemaNode[]>;
|
|
63
|
+
listObjects?(database?: string, schema?: string): Promise<DbClientSchemaNode[]>;
|
|
64
|
+
getObjectDetails?(
|
|
65
|
+
name: string,
|
|
66
|
+
type: DbClientSchemaNodeType,
|
|
67
|
+
database?: string,
|
|
68
|
+
schema?: string
|
|
69
|
+
): Promise<DbClientObjectDetails>;
|
|
70
|
+
|
|
71
|
+
executeRead?(q: string, params?: unknown[], opts?: { database?: string; limit?: number }): Promise<DbClientQueryResult>;
|
|
72
|
+
executeWrite?(q: string, params?: unknown[], opts?: { database?: string }): Promise<DbClientQueryResult>;
|
|
73
|
+
explain?(q: string, opts?: { database?: string }): Promise<DbClientQueryResult>;
|
|
74
|
+
cancel?(): Promise<void>;
|
|
75
|
+
|
|
76
|
+
// Structure
|
|
77
|
+
createDatabase?(name: string): Promise<string>;
|
|
78
|
+
createTable?(definition: TableDefinition, opts?: SchemaOpts): Promise<string>;
|
|
79
|
+
alterTable?(name: string, operations: AlterOperation[], opts?: SchemaOpts): Promise<string>;
|
|
80
|
+
dropTable?(name: string, opts?: SchemaOpts): Promise<string>;
|
|
81
|
+
truncateTable?(name: string, opts?: SchemaOpts): Promise<string>;
|
|
82
|
+
renameTable?(name: string, newName: string, opts?: SchemaOpts): Promise<string>;
|
|
83
|
+
createIndex?(tableName: string, def: IndexDefinition, opts?: SchemaOpts): Promise<string>;
|
|
84
|
+
dropIndex?(tableName: string, indexName: string, opts?: SchemaOpts): Promise<string>;
|
|
85
|
+
createView?(name: string, query: string, opts?: SchemaOpts): Promise<string>;
|
|
86
|
+
dropView?(name: string, opts?: SchemaOpts): Promise<string>;
|
|
87
|
+
|
|
88
|
+
// Data CRUD (parameterized)
|
|
89
|
+
insertRow?(table: string, row: Record<string, unknown>, opts?: SchemaOpts): Promise<DbClientQueryResult>;
|
|
90
|
+
updateRow?(table: string, pk: Record<string, unknown>, changes: Record<string, unknown>, opts?: SchemaOpts): Promise<DbClientQueryResult>;
|
|
91
|
+
deleteRows?(table: string, pks: Record<string, unknown>[], opts?: SchemaOpts): Promise<DbClientQueryResult>;
|
|
92
|
+
}
|