@myrialabs/clopen 0.3.18 → 0.3.20
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/chat/stream-manager.ts +11 -1
- package/backend/database/migrations/039_create_file_audit_log.ts +45 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/file-audit-log-queries.test.ts +377 -0
- package/backend/database/queries/file-audit-log-queries.ts +184 -0
- package/backend/database/queries/index.ts +2 -1
- package/backend/db-client/drivers/mongodb.ts +52 -0
- package/backend/db-client/drivers/mysql.ts +168 -11
- package/backend/db-client/drivers/postgres.ts +182 -19
- package/backend/db-client/drivers/redis.ts +27 -0
- package/backend/db-client/drivers/sqlite.ts +66 -0
- package/backend/db-client/drivers/types.ts +13 -0
- package/backend/engine/install-recipes.ts +1 -109
- package/backend/http/files-upload.ts +84 -3
- package/backend/preview/browser/browser-preview-service.ts +44 -11
- package/backend/snapshot/snapshot-service.ts +82 -52
- package/backend/tunnel/tunnel-config.ts +76 -209
- package/backend/utils/client-ip.test.ts +55 -0
- package/backend/utils/client-ip.ts +42 -0
- package/backend/utils/ws.ts +6 -3
- package/backend/ws/auth/login.test.ts +271 -0
- package/backend/ws/auth/login.ts +36 -3
- package/backend/ws/auth/users.ts +3 -2
- package/backend/ws/db-client/schema.ts +14 -0
- package/backend/ws/db-client/structure.ts +120 -0
- package/backend/ws/files/path-access.test.ts +60 -1
- package/backend/ws/files/path-access.ts +21 -0
- package/backend/ws/snapshot/restore.ts +34 -29
- package/backend/ws/system-tools/install.ts +0 -1
- package/backend/ws/system-tools/status.ts +3 -4
- package/backend/ws/tunnel/config.ts +17 -25
- package/backend/ws/tunnel/operations.ts +63 -68
- package/dist/assets/{main-CaqEjA6B.js → main-72Z_L-nD.js} +224 -223
- package/dist/assets/main-ClADBkFf.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +2 -1
- package/shared/types/db-client/query.ts +9 -0
- package/shared/utils/ws-client.ts +188 -38
- package/backend/tunnel/cloudflared/binary.ts +0 -171
- package/backend/tunnel/cloudflared/index.ts +0 -24
- package/backend/tunnel/cloudflared/tunnel.ts +0 -444
- package/backend/tunnel/global-tunnel-manager.ts +0 -687
- package/backend/tunnel/project-tunnel-manager.ts +0 -264
- package/dist/assets/main-6cCq8H0w.css +0 -1
|
@@ -11,6 +11,7 @@ import type {
|
|
|
11
11
|
DbClientConnection,
|
|
12
12
|
DbClientHealth,
|
|
13
13
|
DbClientObjectDetails,
|
|
14
|
+
DbClientOverview,
|
|
14
15
|
DbClientQueryResult,
|
|
15
16
|
DbClientSchemaNode,
|
|
16
17
|
DbClientSchemaNodeType
|
|
@@ -110,6 +111,28 @@ export class MongoDbAdapter implements DbClientDriverAdapter {
|
|
|
110
111
|
return this.requireClient().db(this.targetDb(opts));
|
|
111
112
|
}
|
|
112
113
|
|
|
114
|
+
// ── Overview ──────────────────────────────────────────────────────────
|
|
115
|
+
|
|
116
|
+
async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
|
|
117
|
+
const client = this.requireClient();
|
|
118
|
+
const start = performance.now();
|
|
119
|
+
const info = await client.db('admin').command({ buildInfo: 1 }) as { version?: string };
|
|
120
|
+
const latencyMs = Math.round(performance.now() - start);
|
|
121
|
+
const db = this.getDb(opts);
|
|
122
|
+
const stats = await db.command({ dbStats: 1 }) as { dataSize?: number; collections?: number; objects?: number };
|
|
123
|
+
return {
|
|
124
|
+
serverVersion: info.version ?? null,
|
|
125
|
+
latencyMs,
|
|
126
|
+
sizeBytes: typeof stats.dataSize === 'number' ? stats.dataSize : null,
|
|
127
|
+
tableCount: typeof stats.collections === 'number' ? stats.collections : null,
|
|
128
|
+
viewCount: null,
|
|
129
|
+
extra: [
|
|
130
|
+
{ label: 'Database', value: this.targetDb(opts) },
|
|
131
|
+
...(typeof stats.objects === 'number' ? [{ label: 'Documents', value: String(stats.objects) }] : [])
|
|
132
|
+
]
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
113
136
|
// ── Schema ────────────────────────────────────────────────────────────
|
|
114
137
|
|
|
115
138
|
async listDatabases(): Promise<DbClientSchemaNode[]> {
|
|
@@ -234,11 +257,40 @@ export class MongoDbAdapter implements DbClientDriverAdapter {
|
|
|
234
257
|
return `db.${name}.drop()`;
|
|
235
258
|
}
|
|
236
259
|
|
|
260
|
+
async dropDatabase(name: string): Promise<string> {
|
|
261
|
+
await this.requireClient().db(name).dropDatabase();
|
|
262
|
+
if (this.defaultDb === name) this.defaultDb = null;
|
|
263
|
+
return `db.getSiblingDB('${name}').dropDatabase()`;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async resetDatabase(opts?: SchemaOpts): Promise<string> {
|
|
267
|
+
const db = this.getDb(opts);
|
|
268
|
+
const collections = await db.listCollections({}, { nameOnly: true }).toArray();
|
|
269
|
+
if (collections.length === 0) return '// no collections to empty';
|
|
270
|
+
for (const c of collections) await db.collection(c.name).deleteMany({});
|
|
271
|
+
return collections.map((c) => `db.${c.name}.deleteMany({})`).join('\n');
|
|
272
|
+
}
|
|
273
|
+
|
|
237
274
|
async truncateTable(name: string, opts?: SchemaOpts): Promise<string> {
|
|
238
275
|
await this.getDb(opts).collection(name).deleteMany({});
|
|
239
276
|
return `db.${name}.deleteMany({})`;
|
|
240
277
|
}
|
|
241
278
|
|
|
279
|
+
async resetTable(name: string, opts?: SchemaOpts): Promise<string> {
|
|
280
|
+
// MongoDB has no sequence counter; reset is equivalent to emptying.
|
|
281
|
+
return this.truncateTable(name, opts);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async duplicateTable(name: string, newName: string, opts?: (SchemaOpts & { withData?: boolean })): Promise<string> {
|
|
285
|
+
const db = this.getDb(opts);
|
|
286
|
+
if (opts?.withData) {
|
|
287
|
+
await db.collection(name).aggregate([{ $match: {} }, { $out: newName }]).toArray();
|
|
288
|
+
return `db.${name}.aggregate([{ $match: {} }, { $out: '${newName}' }])`;
|
|
289
|
+
}
|
|
290
|
+
await db.createCollection(newName);
|
|
291
|
+
return `db.createCollection('${newName}')`;
|
|
292
|
+
}
|
|
293
|
+
|
|
242
294
|
async renameTable(name: string, newName: string, opts?: SchemaOpts): Promise<string> {
|
|
243
295
|
await this.getDb(opts).renameCollection(name, newName);
|
|
244
296
|
return `db.${name}.renameCollection('${newName}')`;
|
|
@@ -10,6 +10,7 @@ import type {
|
|
|
10
10
|
DbClientObjectDetails,
|
|
11
11
|
DbClientObjectForeignKey,
|
|
12
12
|
DbClientObjectIndex,
|
|
13
|
+
DbClientOverview,
|
|
13
14
|
DbClientQueryResult,
|
|
14
15
|
DbClientSchemaNode,
|
|
15
16
|
DbClientSchemaNodeType
|
|
@@ -42,7 +43,13 @@ export class MysqlAdapter implements DbClientDriverAdapter {
|
|
|
42
43
|
|
|
43
44
|
private sql: SQL | null = null;
|
|
44
45
|
private alive = false;
|
|
46
|
+
// The session's currently-USEd database (mutated by ensureDatabase).
|
|
45
47
|
private defaultDb: string | null = null;
|
|
48
|
+
// The connection's configured database — immutable, used as the scope
|
|
49
|
+
// fallback so a connection-level overview never resolves to the last-browsed
|
|
50
|
+
// database that only the session happens to be sitting on.
|
|
51
|
+
private configuredDb: string | null = null;
|
|
52
|
+
private ensureLock = Promise.resolve();
|
|
46
53
|
|
|
47
54
|
async connect(conn: DbClientConnection, tunnelPort?: number): Promise<void> {
|
|
48
55
|
const host = tunnelPort ? '127.0.0.1' : (conn.host ?? '127.0.0.1');
|
|
@@ -56,18 +63,25 @@ export class MysqlAdapter implements DbClientDriverAdapter {
|
|
|
56
63
|
this.sql = new SQL(url);
|
|
57
64
|
await this.sql.connect();
|
|
58
65
|
this.defaultDb = conn.database || null;
|
|
66
|
+
this.configuredDb = conn.database || null;
|
|
59
67
|
this.alive = true;
|
|
60
68
|
}
|
|
61
69
|
|
|
62
70
|
async close(): Promise<void> {
|
|
63
|
-
|
|
64
|
-
|
|
71
|
+
let release: () => void;
|
|
72
|
+
const prev = this.ensureLock;
|
|
73
|
+
this.ensureLock = new Promise<void>((resolve) => { release = resolve; });
|
|
74
|
+
await prev;
|
|
75
|
+
|
|
65
76
|
try {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
77
|
+
this.alive = false;
|
|
78
|
+
this.defaultDb = null;
|
|
79
|
+
if (!this.sql) return;
|
|
80
|
+
await this.sql.close().catch((err) => debug.warn('db-client', 'MySQL close error:', err));
|
|
81
|
+
this.sql = null;
|
|
82
|
+
} finally {
|
|
83
|
+
release!();
|
|
69
84
|
}
|
|
70
|
-
this.sql = null;
|
|
71
85
|
}
|
|
72
86
|
|
|
73
87
|
isAlive(): boolean {
|
|
@@ -103,16 +117,28 @@ export class MysqlAdapter implements DbClientDriverAdapter {
|
|
|
103
117
|
}
|
|
104
118
|
|
|
105
119
|
private targetDb(opts?: SchemaOpts): string | undefined {
|
|
106
|
-
|
|
120
|
+
// Fall back to the configured database, never the session's last-USEd one.
|
|
121
|
+
return opts?.database || this.configuredDb || undefined;
|
|
107
122
|
}
|
|
108
123
|
|
|
109
124
|
private async ensureDatabase(database?: string): Promise<void> {
|
|
110
125
|
if (!database) return;
|
|
111
126
|
if (database === this.defaultDb) return;
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
this.
|
|
127
|
+
|
|
128
|
+
let release: () => void;
|
|
129
|
+
const prev = this.ensureLock;
|
|
130
|
+
this.ensureLock = new Promise<void>((resolve) => { release = resolve; });
|
|
131
|
+
await prev;
|
|
132
|
+
|
|
133
|
+
try {
|
|
134
|
+
if (database === this.defaultDb) return;
|
|
135
|
+
const sql = this.requireSql();
|
|
136
|
+
assertSafeIdentifier(database);
|
|
137
|
+
await sql.unsafe(`USE ${quoteMysql(database)}`);
|
|
138
|
+
this.defaultDb = database;
|
|
139
|
+
} finally {
|
|
140
|
+
release!();
|
|
141
|
+
}
|
|
116
142
|
}
|
|
117
143
|
|
|
118
144
|
async executeRead(q: string, params: unknown[] = [], opts?: { database?: string }): Promise<DbClientQueryResult> {
|
|
@@ -131,6 +157,54 @@ export class MysqlAdapter implements DbClientDriverAdapter {
|
|
|
131
157
|
return this.executeRead(`EXPLAIN ${q}`, [], opts);
|
|
132
158
|
}
|
|
133
159
|
|
|
160
|
+
// ── Overview ──────────────────────────────────────────────────────────
|
|
161
|
+
|
|
162
|
+
async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
|
|
163
|
+
const sql = this.requireSql();
|
|
164
|
+
const start = performance.now();
|
|
165
|
+
const verRows = (await sql.unsafe('SELECT VERSION() AS v')) as Array<{ v: string }>;
|
|
166
|
+
const latencyMs = Math.round(performance.now() - start);
|
|
167
|
+
const target = this.targetDb(opts);
|
|
168
|
+
if (!target) {
|
|
169
|
+
// Connection level — aggregate across all user databases on the server.
|
|
170
|
+
const rows = (await sql.unsafe(
|
|
171
|
+
`SELECT
|
|
172
|
+
COUNT(DISTINCT table_schema) AS dbs,
|
|
173
|
+
SUM(data_length + index_length) AS size,
|
|
174
|
+
SUM(table_type = 'BASE TABLE') AS tables,
|
|
175
|
+
SUM(table_type = 'VIEW') AS views
|
|
176
|
+
FROM information_schema.tables
|
|
177
|
+
WHERE table_schema NOT IN ('mysql', 'information_schema', 'performance_schema', 'sys')`
|
|
178
|
+
)) as Array<Record<string, unknown>>;
|
|
179
|
+
const r = rows[0] ?? {};
|
|
180
|
+
return {
|
|
181
|
+
serverVersion: verRows[0]?.v ?? null,
|
|
182
|
+
latencyMs,
|
|
183
|
+
sizeBytes: r.size === null || r.size === undefined ? null : Number(r.size),
|
|
184
|
+
tableCount: r.tables === null || r.tables === undefined ? null : Number(r.tables),
|
|
185
|
+
viewCount: r.views === null || r.views === undefined ? null : Number(r.views),
|
|
186
|
+
extra: [{ label: 'Databases', value: String(r.dbs === null || r.dbs === undefined ? 0 : Number(r.dbs)) }]
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
const rows = (await sql.unsafe(
|
|
190
|
+
`SELECT
|
|
191
|
+
SUM(data_length + index_length) AS size,
|
|
192
|
+
SUM(table_type = 'BASE TABLE') AS tables,
|
|
193
|
+
SUM(table_type = 'VIEW') AS views
|
|
194
|
+
FROM information_schema.tables WHERE table_schema = ?`,
|
|
195
|
+
[target] as never
|
|
196
|
+
)) as Array<Record<string, unknown>>;
|
|
197
|
+
const r = rows[0] ?? {};
|
|
198
|
+
return {
|
|
199
|
+
serverVersion: verRows[0]?.v ?? null,
|
|
200
|
+
latencyMs,
|
|
201
|
+
sizeBytes: r.size === null || r.size === undefined ? null : Number(r.size),
|
|
202
|
+
tableCount: r.tables === null || r.tables === undefined ? null : Number(r.tables),
|
|
203
|
+
viewCount: r.views === null || r.views === undefined ? null : Number(r.views),
|
|
204
|
+
extra: [{ label: 'Database', value: target }]
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
134
208
|
// ── Schema ────────────────────────────────────────────────────────────
|
|
135
209
|
|
|
136
210
|
async listDatabases(): Promise<DbClientSchemaNode[]> {
|
|
@@ -230,6 +304,89 @@ export class MysqlAdapter implements DbClientDriverAdapter {
|
|
|
230
304
|
return ddl;
|
|
231
305
|
}
|
|
232
306
|
|
|
307
|
+
async dropDatabase(name: string): Promise<string> {
|
|
308
|
+
assertSafeIdentifier(name);
|
|
309
|
+
const ddl = `DROP DATABASE ${Q(name)}`;
|
|
310
|
+
await this.requireSql().unsafe(ddl);
|
|
311
|
+
if (this.defaultDb === name) this.defaultDb = null;
|
|
312
|
+
return ddl;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async renameDatabase(name: string, newName: string): Promise<string> {
|
|
316
|
+
// MySQL has no RENAME DATABASE. Create the target, move every base table
|
|
317
|
+
// into it (RENAME TABLE moves data instantly, no copy), then drop the old
|
|
318
|
+
// one. Tables (and their data) are migrated losslessly.
|
|
319
|
+
assertSafeIdentifier(name);
|
|
320
|
+
assertSafeIdentifier(newName);
|
|
321
|
+
const sql = this.requireSql();
|
|
322
|
+
await sql.unsafe(`CREATE DATABASE ${Q(newName)}`);
|
|
323
|
+
const rows = (await sql.unsafe(
|
|
324
|
+
"SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE'",
|
|
325
|
+
[name] as never
|
|
326
|
+
)) as Array<{ TABLE_NAME: string }>;
|
|
327
|
+
for (const r of rows) {
|
|
328
|
+
assertSafeIdentifier(r.TABLE_NAME);
|
|
329
|
+
await sql.unsafe(`RENAME TABLE ${qualified(Q, [name, r.TABLE_NAME])} TO ${qualified(Q, [newName, r.TABLE_NAME])}`);
|
|
330
|
+
}
|
|
331
|
+
await sql.unsafe(`DROP DATABASE ${Q(name)}`);
|
|
332
|
+
// Force a fresh `USE` on next access — the session's selected db is gone.
|
|
333
|
+
if (this.defaultDb === name) this.defaultDb = null;
|
|
334
|
+
return `CREATE DATABASE ${Q(newName)}; RENAME TABLE …; DROP DATABASE ${Q(name)}`;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async resetDatabase(opts?: SchemaOpts): Promise<string> {
|
|
338
|
+
const target = this.targetDb(opts);
|
|
339
|
+
if (!target) throw new Error('MySQL: database is required');
|
|
340
|
+
const sql = this.requireSql();
|
|
341
|
+
const rows = (await sql.unsafe(
|
|
342
|
+
"SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE'",
|
|
343
|
+
[target] as never
|
|
344
|
+
)) as Array<{ TABLE_NAME: string }>;
|
|
345
|
+
if (rows.length === 0) return '-- no tables to empty';
|
|
346
|
+
rows.forEach((r) => assertSafeIdentifier(r.TABLE_NAME));
|
|
347
|
+
const statements = rows.map((r) => `TRUNCATE TABLE ${qualified(Q, [target, r.TABLE_NAME])}`);
|
|
348
|
+
await sql.unsafe('SET FOREIGN_KEY_CHECKS = 0');
|
|
349
|
+
try {
|
|
350
|
+
for (const stmt of statements) await sql.unsafe(stmt);
|
|
351
|
+
} finally {
|
|
352
|
+
await sql.unsafe('SET FOREIGN_KEY_CHECKS = 1');
|
|
353
|
+
}
|
|
354
|
+
return statements.join(';\n');
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async resetTable(name: string, opts?: SchemaOpts): Promise<string> {
|
|
358
|
+
// MySQL TRUNCATE already resets AUTO_INCREMENT.
|
|
359
|
+
return this.truncateTable(name, opts);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async duplicateTable(name: string, newName: string, opts?: (SchemaOpts & { withData?: boolean })): Promise<string> {
|
|
363
|
+
assertSafeIdentifier(name);
|
|
364
|
+
assertSafeIdentifier(newName);
|
|
365
|
+
const db = this.targetDb(opts);
|
|
366
|
+
const src = qualified(Q, [db, name]);
|
|
367
|
+
const dst = qualified(Q, [db, newName]);
|
|
368
|
+
const sql = this.requireSql();
|
|
369
|
+
const create = `CREATE TABLE ${dst} LIKE ${src}`;
|
|
370
|
+
await sql.unsafe(create);
|
|
371
|
+
const statements = [create];
|
|
372
|
+
if (opts?.withData) {
|
|
373
|
+
const copy = `INSERT INTO ${dst} SELECT * FROM ${src}`;
|
|
374
|
+
await sql.unsafe(copy);
|
|
375
|
+
statements.push(copy);
|
|
376
|
+
}
|
|
377
|
+
return statements.join(';\n');
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
async getCreateStatement(name: string, type: DbClientSchemaNodeType, opts?: SchemaOpts): Promise<string> {
|
|
381
|
+
assertSafeIdentifier(name);
|
|
382
|
+
const fqt = qualified(Q, [this.targetDb(opts), name]);
|
|
383
|
+
const keyword = type === 'view' ? 'VIEW' : 'TABLE';
|
|
384
|
+
const rows = (await this.requireSql().unsafe(`SHOW CREATE ${keyword} ${fqt}`)) as Array<Record<string, unknown>>;
|
|
385
|
+
const row = rows[0] ?? {};
|
|
386
|
+
const ddl = row['Create Table'] ?? row['Create View'] ?? Object.values(row)[1];
|
|
387
|
+
return String(ddl ?? '');
|
|
388
|
+
}
|
|
389
|
+
|
|
233
390
|
async createTable(definition: TableDefinition, opts?: SchemaOpts): Promise<string> {
|
|
234
391
|
assertSafeIdentifier(definition.name);
|
|
235
392
|
const ddl = renderCreateTable({
|
|
@@ -10,6 +10,7 @@ import type {
|
|
|
10
10
|
DbClientObjectDetails,
|
|
11
11
|
DbClientObjectForeignKey,
|
|
12
12
|
DbClientObjectIndex,
|
|
13
|
+
DbClientOverview,
|
|
13
14
|
DbClientQueryResult,
|
|
14
15
|
DbClientSchemaNode,
|
|
15
16
|
DbClientSchemaNodeType
|
|
@@ -43,10 +44,21 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
43
44
|
|
|
44
45
|
private sql: SQL | null = null;
|
|
45
46
|
private alive = false;
|
|
47
|
+
// The database the active connection currently points at (switched by
|
|
48
|
+
// reconnecting in ensureDatabase).
|
|
46
49
|
private defaultDb: string | null = null;
|
|
50
|
+
// The connection's home database — what we revert to when no specific
|
|
51
|
+
// database is requested, so a connection-level overview doesn't keep
|
|
52
|
+
// reporting the last-browsed database.
|
|
53
|
+
private homeDb = 'postgres';
|
|
54
|
+
// Whether the connection was created with a fixed database. `conn` itself is
|
|
55
|
+
// rewritten when switching databases, so this stable flag is what tells us a
|
|
56
|
+
// connection-level (cluster) overview is appropriate.
|
|
57
|
+
private hasConfiguredDb = false;
|
|
47
58
|
private defaultSchema: string | null = null;
|
|
48
59
|
private conn: DbClientConnection | null = null;
|
|
49
60
|
private tunnelPort: number | undefined = undefined;
|
|
61
|
+
private ensureLock = Promise.resolve();
|
|
50
62
|
|
|
51
63
|
private buildUrl(conn: DbClientConnection, tunnelPort?: number): string {
|
|
52
64
|
const host = tunnelPort ? '127.0.0.1' : (conn.host ?? '127.0.0.1');
|
|
@@ -69,7 +81,9 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
69
81
|
|
|
70
82
|
this.sql = new SQL(url);
|
|
71
83
|
await this.sql.connect();
|
|
72
|
-
this.
|
|
84
|
+
this.hasConfiguredDb = !!conn.database;
|
|
85
|
+
this.homeDb = conn.database || 'postgres';
|
|
86
|
+
this.defaultDb = this.homeDb;
|
|
73
87
|
this.defaultSchema = typeof conn.options?.schema === 'string' ? conn.options.schema : 'public';
|
|
74
88
|
this.conn = conn;
|
|
75
89
|
this.tunnelPort = tunnelPort;
|
|
@@ -77,29 +91,47 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
77
91
|
}
|
|
78
92
|
|
|
79
93
|
private async ensureDatabase(database?: string): Promise<void> {
|
|
80
|
-
if (!
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
94
|
+
if (!this.conn) return;
|
|
95
|
+
const target = database || this.homeDb;
|
|
96
|
+
if (target === this.defaultDb) return;
|
|
97
|
+
|
|
98
|
+
let release: () => void;
|
|
99
|
+
const prev = this.ensureLock;
|
|
100
|
+
this.ensureLock = new Promise<void>((resolve) => { release = resolve; });
|
|
101
|
+
await prev;
|
|
102
|
+
|
|
103
|
+
try {
|
|
104
|
+
if (target === this.defaultDb) return;
|
|
105
|
+
const newConn = { ...this.conn, database: target };
|
|
106
|
+
const url = this.buildUrl(newConn, this.tunnelPort);
|
|
107
|
+
const next = new SQL(url);
|
|
108
|
+
await next.connect();
|
|
109
|
+
const prevSql = this.sql;
|
|
110
|
+
this.sql = next;
|
|
111
|
+
this.defaultDb = target;
|
|
112
|
+
this.conn = newConn;
|
|
113
|
+
this.alive = true;
|
|
114
|
+
if (prevSql) await prevSql.close().catch((err) => debug.warn('db-client', 'pg switch close error:', err));
|
|
115
|
+
} finally {
|
|
116
|
+
release!();
|
|
117
|
+
}
|
|
92
118
|
}
|
|
93
119
|
|
|
94
120
|
async close(): Promise<void> {
|
|
95
|
-
|
|
96
|
-
|
|
121
|
+
let release: () => void;
|
|
122
|
+
const prev = this.ensureLock;
|
|
123
|
+
this.ensureLock = new Promise<void>((resolve) => { release = resolve; });
|
|
124
|
+
await prev;
|
|
125
|
+
|
|
97
126
|
try {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
127
|
+
this.alive = false;
|
|
128
|
+
this.conn = null;
|
|
129
|
+
if (!this.sql) return;
|
|
130
|
+
await this.sql.close().catch((err) => debug.warn('db-client', 'Postgres close error:', err));
|
|
131
|
+
this.sql = null;
|
|
132
|
+
} finally {
|
|
133
|
+
release!();
|
|
101
134
|
}
|
|
102
|
-
this.sql = null;
|
|
103
135
|
}
|
|
104
136
|
|
|
105
137
|
isAlive(): boolean {
|
|
@@ -154,6 +186,57 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
154
186
|
return this.executeRead(`EXPLAIN ${q}`, [], opts);
|
|
155
187
|
}
|
|
156
188
|
|
|
189
|
+
// ── Overview ──────────────────────────────────────────────────────────
|
|
190
|
+
|
|
191
|
+
async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
|
|
192
|
+
await this.ensureDatabase(opts?.database);
|
|
193
|
+
const sql = this.requireSql();
|
|
194
|
+
const start = performance.now();
|
|
195
|
+
const verRows = (await sql.unsafe('SELECT version() AS v')) as Array<{ v: string }>;
|
|
196
|
+
const latencyMs = Math.round(performance.now() - start);
|
|
197
|
+
|
|
198
|
+
// Connection level (no configured database, none in scope) → cluster-wide
|
|
199
|
+
// stats rather than the home database's, so it never looks "stuck" on the
|
|
200
|
+
// last-browsed database.
|
|
201
|
+
if (!this.hasConfiguredDb && !opts?.database) {
|
|
202
|
+
const rows = (await sql.unsafe(
|
|
203
|
+
`SELECT COUNT(*) AS dbs, SUM(pg_database_size(datname)) AS size
|
|
204
|
+
FROM pg_database WHERE datistemplate = false`
|
|
205
|
+
)) as Array<Record<string, unknown>>;
|
|
206
|
+
const r = rows[0] ?? {};
|
|
207
|
+
return {
|
|
208
|
+
serverVersion: verRows[0]?.v ?? null,
|
|
209
|
+
latencyMs,
|
|
210
|
+
sizeBytes: r.size === null || r.size === undefined ? null : Number(r.size),
|
|
211
|
+
tableCount: null,
|
|
212
|
+
viewCount: null,
|
|
213
|
+
extra: [{ label: 'Databases', value: String(r.dbs === null || r.dbs === undefined ? 0 : Number(r.dbs)) }]
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const schema = this.targetSchema(opts);
|
|
218
|
+
const sizeRows = (await sql.unsafe('SELECT pg_database_size(current_database()) AS size')) as Array<{ size: unknown }>;
|
|
219
|
+
const countRows = (await sql.unsafe(
|
|
220
|
+
`SELECT
|
|
221
|
+
COUNT(*) FILTER (WHERE table_type = 'BASE TABLE') AS tables,
|
|
222
|
+
COUNT(*) FILTER (WHERE table_type = 'VIEW') AS views
|
|
223
|
+
FROM information_schema.tables WHERE table_schema = $1`,
|
|
224
|
+
[schema] as never
|
|
225
|
+
)) as Array<Record<string, unknown>>;
|
|
226
|
+
const c = countRows[0] ?? {};
|
|
227
|
+
return {
|
|
228
|
+
serverVersion: verRows[0]?.v ?? null,
|
|
229
|
+
latencyMs,
|
|
230
|
+
sizeBytes: sizeRows[0]?.size === undefined ? null : Number(sizeRows[0].size),
|
|
231
|
+
tableCount: c.tables === undefined ? null : Number(c.tables),
|
|
232
|
+
viewCount: c.views === undefined ? null : Number(c.views),
|
|
233
|
+
extra: [
|
|
234
|
+
{ label: 'Database', value: this.defaultDb ?? 'postgres' },
|
|
235
|
+
{ label: 'Schema', value: schema }
|
|
236
|
+
]
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
157
240
|
// ── Schema ────────────────────────────────────────────────────────────
|
|
158
241
|
|
|
159
242
|
async listDatabases(): Promise<DbClientSchemaNode[]> {
|
|
@@ -281,6 +364,86 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
281
364
|
return ddl;
|
|
282
365
|
}
|
|
283
366
|
|
|
367
|
+
async dropDatabase(name: string): Promise<string> {
|
|
368
|
+
assertSafeIdentifier(name);
|
|
369
|
+
// Postgres refuses to drop the database the session is connected to —
|
|
370
|
+
// hop to the maintenance database first when needed.
|
|
371
|
+
if (this.defaultDb === name) await this.ensureDatabase('postgres');
|
|
372
|
+
const ddl = `DROP DATABASE ${Q(name)}`;
|
|
373
|
+
await this.requireSql().unsafe(ddl);
|
|
374
|
+
return ddl;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async renameDatabase(name: string, newName: string): Promise<string> {
|
|
378
|
+
assertSafeIdentifier(name);
|
|
379
|
+
assertSafeIdentifier(newName);
|
|
380
|
+
if (this.defaultDb === name) await this.ensureDatabase('postgres');
|
|
381
|
+
const ddl = `ALTER DATABASE ${Q(name)} RENAME TO ${Q(newName)}`;
|
|
382
|
+
await this.requireSql().unsafe(ddl);
|
|
383
|
+
return ddl;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
async resetDatabase(opts?: SchemaOpts): Promise<string> {
|
|
387
|
+
await this.ensureDatabase(opts?.database);
|
|
388
|
+
const target = this.targetSchema(opts);
|
|
389
|
+
const sql = this.requireSql();
|
|
390
|
+
const rows = (await sql.unsafe(
|
|
391
|
+
`SELECT table_name FROM information_schema.tables
|
|
392
|
+
WHERE table_schema = $1 AND table_type = 'BASE TABLE' ORDER BY table_name`,
|
|
393
|
+
[target] as never
|
|
394
|
+
)) as Array<{ table_name: string }>;
|
|
395
|
+
if (rows.length === 0) return '-- no tables to empty';
|
|
396
|
+
rows.forEach((r) => assertSafeIdentifier(r.table_name));
|
|
397
|
+
const list = rows.map((r) => qualified(Q, [target, r.table_name])).join(', ');
|
|
398
|
+
const ddl = `TRUNCATE TABLE ${list} RESTART IDENTITY CASCADE`;
|
|
399
|
+
await sql.unsafe(ddl);
|
|
400
|
+
return ddl;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
async resetTable(name: string, opts?: SchemaOpts): Promise<string> {
|
|
404
|
+
await this.ensureDatabase(opts?.database);
|
|
405
|
+
assertSafeIdentifier(name);
|
|
406
|
+
const ddl = `TRUNCATE TABLE ${qualified(Q, [this.targetSchema(opts), name])} RESTART IDENTITY`;
|
|
407
|
+
await this.requireSql().unsafe(ddl);
|
|
408
|
+
return ddl;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
async duplicateTable(name: string, newName: string, opts?: (SchemaOpts & { withData?: boolean })): Promise<string> {
|
|
412
|
+
await this.ensureDatabase(opts?.database);
|
|
413
|
+
assertSafeIdentifier(name);
|
|
414
|
+
assertSafeIdentifier(newName);
|
|
415
|
+
const schema = this.targetSchema(opts);
|
|
416
|
+
const src = qualified(Q, [schema, name]);
|
|
417
|
+
const dst = qualified(Q, [schema, newName]);
|
|
418
|
+
const sql = this.requireSql();
|
|
419
|
+
const create = `CREATE TABLE ${dst} (LIKE ${src} INCLUDING ALL)`;
|
|
420
|
+
await sql.unsafe(create);
|
|
421
|
+
const statements = [create];
|
|
422
|
+
if (opts?.withData) {
|
|
423
|
+
const copy = `INSERT INTO ${dst} SELECT * FROM ${src}`;
|
|
424
|
+
await sql.unsafe(copy);
|
|
425
|
+
statements.push(copy);
|
|
426
|
+
}
|
|
427
|
+
return statements.join(';\n');
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async getCreateStatement(name: string, _type: DbClientSchemaNodeType, opts?: SchemaOpts): Promise<string> {
|
|
431
|
+
// Postgres has no SHOW CREATE; reconstruct a best-effort CREATE TABLE.
|
|
432
|
+
const details = await this.getObjectDetails(name, 'table', opts?.database, opts?.schema);
|
|
433
|
+
const schema = this.targetSchema(opts);
|
|
434
|
+
const detailColumns = details.columns ?? [];
|
|
435
|
+
const cols = detailColumns.map((c) => {
|
|
436
|
+
const parts = [Q(c.name), c.type];
|
|
437
|
+
if (!c.nullable) parts.push('NOT NULL');
|
|
438
|
+
if (c.default !== null && c.default !== undefined && c.default !== '') parts.push(`DEFAULT ${c.default}`);
|
|
439
|
+
return ` ${parts.join(' ')}`;
|
|
440
|
+
});
|
|
441
|
+
const pk = detailColumns.filter((c) => c.isPrimary).map((c) => Q(c.name));
|
|
442
|
+
if (pk.length > 0) cols.push(` PRIMARY KEY (${pk.join(', ')})`);
|
|
443
|
+
const lines = [`CREATE TABLE ${qualified(Q, [schema, name])} (`, cols.join(',\n'), ');'];
|
|
444
|
+
return lines.join('\n');
|
|
445
|
+
}
|
|
446
|
+
|
|
284
447
|
async createTable(definition: TableDefinition, opts?: SchemaOpts): Promise<string> {
|
|
285
448
|
await this.ensureDatabase(opts?.database);
|
|
286
449
|
assertSafeIdentifier(definition.name);
|
|
@@ -14,6 +14,7 @@ import type {
|
|
|
14
14
|
DbClientConnection,
|
|
15
15
|
DbClientHealth,
|
|
16
16
|
DbClientObjectDetails,
|
|
17
|
+
DbClientOverview,
|
|
17
18
|
DbClientQueryResult,
|
|
18
19
|
DbClientSchemaNode,
|
|
19
20
|
DbClientSchemaNodeType
|
|
@@ -93,6 +94,27 @@ export class RedisAdapter implements DbClientDriverAdapter {
|
|
|
93
94
|
return this.client;
|
|
94
95
|
}
|
|
95
96
|
|
|
97
|
+
// ── Overview ──────────────────────────────────────────────────────────
|
|
98
|
+
|
|
99
|
+
async overview(): Promise<DbClientOverview> {
|
|
100
|
+
const client = this.requireClient();
|
|
101
|
+
const start = performance.now();
|
|
102
|
+
const info = (await client.send('INFO', [])) as string;
|
|
103
|
+
const latencyMs = Math.round(performance.now() - start);
|
|
104
|
+
const ver = /redis_version:([^\r\n]+)/.exec(info ?? '')?.[1]?.trim() ?? null;
|
|
105
|
+
const usedMemory = /used_memory:([0-9]+)/.exec(info ?? '')?.[1];
|
|
106
|
+
const dbsize = (await client.send('DBSIZE', [])) as number | string;
|
|
107
|
+
const keys = Number(dbsize);
|
|
108
|
+
return {
|
|
109
|
+
serverVersion: ver,
|
|
110
|
+
latencyMs,
|
|
111
|
+
sizeBytes: usedMemory ? Number(usedMemory) : null,
|
|
112
|
+
tableCount: Number.isFinite(keys) ? keys : null,
|
|
113
|
+
viewCount: null,
|
|
114
|
+
extra: [{ label: 'Keys', value: Number.isFinite(keys) ? String(keys) : '—' }]
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
96
118
|
// ── Schema (key listing) ──────────────────────────────────────────────
|
|
97
119
|
|
|
98
120
|
async listDatabases(): Promise<DbClientSchemaNode[]> {
|
|
@@ -170,6 +192,11 @@ export class RedisAdapter implements DbClientDriverAdapter {
|
|
|
170
192
|
return `DEL ${name}`;
|
|
171
193
|
}
|
|
172
194
|
|
|
195
|
+
async flushDatabase(): Promise<string> {
|
|
196
|
+
await this.requireClient().send('FLUSHDB', []);
|
|
197
|
+
return 'FLUSHDB';
|
|
198
|
+
}
|
|
199
|
+
|
|
173
200
|
async renameTable(name: string, newName: string): Promise<string> {
|
|
174
201
|
await this.requireClient().send('RENAME', [name, newName]);
|
|
175
202
|
return `RENAME ${name} ${newName}`;
|