@myrialabs/clopen 0.3.17 → 0.3.19

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.
Files changed (34) hide show
  1. package/backend/chat/stream-manager.ts +11 -1
  2. package/backend/database/migrations/038_add_workspace_state_to_user_projects.ts +23 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/project-queries.ts +18 -0
  5. package/backend/db-client/drivers/mongodb.ts +52 -0
  6. package/backend/db-client/drivers/mysql.ts +140 -1
  7. package/backend/db-client/drivers/postgres.ts +152 -5
  8. package/backend/db-client/drivers/redis.ts +27 -0
  9. package/backend/db-client/drivers/sqlite.ts +66 -0
  10. package/backend/db-client/drivers/types.ts +13 -0
  11. package/backend/git/git-service.ts +135 -2
  12. package/backend/preview/browser/browser-preview-service.ts +53 -17
  13. package/backend/snapshot/snapshot-service.ts +82 -52
  14. package/backend/utils/ws.ts +3 -1
  15. package/backend/ws/db-client/schema.ts +14 -0
  16. package/backend/ws/db-client/structure.ts +120 -0
  17. package/backend/ws/git/commit.ts +63 -0
  18. package/backend/ws/git/remote.ts +36 -1
  19. package/backend/ws/index.ts +2 -0
  20. package/backend/ws/preview/access.ts +20 -1
  21. package/backend/ws/preview/browser/tab-info.ts +15 -6
  22. package/backend/ws/preview/index.ts +7 -0
  23. package/backend/ws/snapshot/restore.ts +34 -29
  24. package/backend/ws/workspace/index.ts +14 -0
  25. package/backend/ws/workspace/state.ts +44 -0
  26. package/dist/assets/main-BOUXyIaW.js +362 -0
  27. package/dist/assets/main-ClADBkFf.css +1 -0
  28. package/dist/index.html +2 -2
  29. package/package.json +1 -1
  30. package/shared/constants/notification-sounds.ts +1 -1
  31. package/shared/types/db-client/query.ts +9 -0
  32. package/shared/utils/logger.ts +4 -6
  33. package/dist/assets/main-CHTThSzD.js +0 -358
  34. package/dist/assets/main-Dzb_5CtR.css +0 -1
@@ -427,8 +427,13 @@ class StreamManager extends EventEmitter {
427
427
  private async processStream(streamState: StreamState, requestData: StreamRequest): Promise<void> {
428
428
  let userMessageId: string | undefined;
429
429
 
430
+ // Launch the pre-edit baseline scan as early as possible so it overlaps with
431
+ // engine initialization. It MUST finish before the engine can write any files
432
+ // (awaited just before streamQuery below) — otherwise early writes would be
433
+ // folded into the baseline and silently dropped from this turn's checkpoint.
434
+ let baselineInitPromise: Promise<void> | null = null;
430
435
  if (requestData.projectPath && requestData.chatSessionId) {
431
- snapshotService.initializeSessionBaseline(
436
+ baselineInitPromise = snapshotService.initializeSessionBaseline(
432
437
  requestData.projectPath,
433
438
  requestData.chatSessionId
434
439
  ).catch(err => debug.error('snapshot', 'Failed to initialize session baseline:', err));
@@ -598,6 +603,11 @@ class StreamManager extends EventEmitter {
598
603
  }
599
604
  }
600
605
 
606
+ // Guarantee the pre-edit baseline is captured before the engine can write
607
+ // any files (see processStream top). Without this await a fast engine on a
608
+ // large repo could begin editing while the baseline scan is still running.
609
+ if (baselineInitPromise) await baselineInitPromise;
610
+
601
611
  // Stream EngineOutput events through the engine adapter
602
612
  const streamIterable = engine.streamQuery({
603
613
  projectPath,
@@ -0,0 +1,23 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add workspace_state to user_projects for per-project dock/layout restore';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding workspace_state to user_projects...');
8
+ db.exec(`ALTER TABLE user_projects ADD COLUMN workspace_state TEXT`);
9
+ debug.log('migration', 'workspace_state column added');
10
+ };
11
+
12
+ export const down = (db: DatabaseConnection): void => {
13
+ debug.log('migration', 'Removing workspace_state from user_projects...');
14
+ db.exec(`
15
+ CREATE TABLE user_projects_backup AS
16
+ SELECT user_id, project_id, joined_at, current_session_id, files_panel_state FROM user_projects
17
+ `);
18
+ db.exec(`DROP TABLE user_projects`);
19
+ db.exec(`ALTER TABLE user_projects_backup RENAME TO user_projects`);
20
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_user_projects_user_id ON user_projects(user_id)`);
21
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_user_projects_project_id ON user_projects(project_id)`);
22
+ debug.log('migration', 'workspace_state column removed');
23
+ };
@@ -36,6 +36,7 @@ import * as migration034 from './034_seed_qwen_provider';
36
36
  import * as migration035 from './035_add_owner_to_db_client_connections';
37
37
  import * as migration036 from './036_create_auth_audit_log';
38
38
  import * as migration037 from './037_repair_auth_audit_log_schema';
39
+ import * as migration038 from './038_add_workspace_state_to_user_projects';
39
40
 
40
41
  // Export all migrations in order
41
42
  export const migrations = [
@@ -260,6 +261,12 @@ export const migrations = [
260
261
  description: migration037.description,
261
262
  up: migration037.up,
262
263
  down: migration037.down
264
+ },
265
+ {
266
+ id: '038',
267
+ description: migration038.description,
268
+ up: migration038.up,
269
+ down: migration038.down
263
270
  }
264
271
  ];
265
272
 
@@ -138,5 +138,23 @@ export const projectQueries = {
138
138
  SET files_panel_state = ?
139
139
  WHERE user_id = ? AND project_id = ?
140
140
  `).run(state, userId, projectId);
141
+ },
142
+
143
+ getWorkspaceState(userId: string, projectId: string): string | null {
144
+ const db = getDatabase();
145
+ const result = db.prepare(`
146
+ SELECT workspace_state FROM user_projects
147
+ WHERE user_id = ? AND project_id = ?
148
+ `).get(userId, projectId) as { workspace_state: string | null } | null;
149
+ return result?.workspace_state || null;
150
+ },
151
+
152
+ setWorkspaceState(userId: string, projectId: string, state: string | null): void {
153
+ const db = getDatabase();
154
+ db.prepare(`
155
+ UPDATE user_projects
156
+ SET workspace_state = ?
157
+ WHERE user_id = ? AND project_id = ?
158
+ `).run(state, userId, projectId);
141
159
  }
142
160
  };
@@ -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,12 @@ 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;
46
52
 
47
53
  async connect(conn: DbClientConnection, tunnelPort?: number): Promise<void> {
48
54
  const host = tunnelPort ? '127.0.0.1' : (conn.host ?? '127.0.0.1');
@@ -56,6 +62,7 @@ export class MysqlAdapter implements DbClientDriverAdapter {
56
62
  this.sql = new SQL(url);
57
63
  await this.sql.connect();
58
64
  this.defaultDb = conn.database || null;
65
+ this.configuredDb = conn.database || null;
59
66
  this.alive = true;
60
67
  }
61
68
 
@@ -103,7 +110,8 @@ export class MysqlAdapter implements DbClientDriverAdapter {
103
110
  }
104
111
 
105
112
  private targetDb(opts?: SchemaOpts): string | undefined {
106
- return opts?.database || this.defaultDb || undefined;
113
+ // Fall back to the configured database, never the session's last-USEd one.
114
+ return opts?.database || this.configuredDb || undefined;
107
115
  }
108
116
 
109
117
  private async ensureDatabase(database?: string): Promise<void> {
@@ -131,6 +139,54 @@ export class MysqlAdapter implements DbClientDriverAdapter {
131
139
  return this.executeRead(`EXPLAIN ${q}`, [], opts);
132
140
  }
133
141
 
142
+ // ── Overview ──────────────────────────────────────────────────────────
143
+
144
+ async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
145
+ const sql = this.requireSql();
146
+ const start = performance.now();
147
+ const verRows = (await sql.unsafe('SELECT VERSION() AS v')) as Array<{ v: string }>;
148
+ const latencyMs = Math.round(performance.now() - start);
149
+ const target = this.targetDb(opts);
150
+ if (!target) {
151
+ // Connection level — aggregate across all user databases on the server.
152
+ const rows = (await sql.unsafe(
153
+ `SELECT
154
+ COUNT(DISTINCT table_schema) AS dbs,
155
+ SUM(data_length + index_length) AS size,
156
+ SUM(table_type = 'BASE TABLE') AS tables,
157
+ SUM(table_type = 'VIEW') AS views
158
+ FROM information_schema.tables
159
+ WHERE table_schema NOT IN ('mysql', 'information_schema', 'performance_schema', 'sys')`
160
+ )) as Array<Record<string, unknown>>;
161
+ const r = rows[0] ?? {};
162
+ return {
163
+ serverVersion: verRows[0]?.v ?? null,
164
+ latencyMs,
165
+ sizeBytes: r.size === null || r.size === undefined ? null : Number(r.size),
166
+ tableCount: r.tables === null || r.tables === undefined ? null : Number(r.tables),
167
+ viewCount: r.views === null || r.views === undefined ? null : Number(r.views),
168
+ extra: [{ label: 'Databases', value: String(r.dbs === null || r.dbs === undefined ? 0 : Number(r.dbs)) }]
169
+ };
170
+ }
171
+ const rows = (await sql.unsafe(
172
+ `SELECT
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 WHERE table_schema = ?`,
177
+ [target] as never
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: 'Database', value: target }]
187
+ };
188
+ }
189
+
134
190
  // ── Schema ────────────────────────────────────────────────────────────
135
191
 
136
192
  async listDatabases(): Promise<DbClientSchemaNode[]> {
@@ -230,6 +286,89 @@ export class MysqlAdapter implements DbClientDriverAdapter {
230
286
  return ddl;
231
287
  }
232
288
 
289
+ async dropDatabase(name: string): Promise<string> {
290
+ assertSafeIdentifier(name);
291
+ const ddl = `DROP DATABASE ${Q(name)}`;
292
+ await this.requireSql().unsafe(ddl);
293
+ if (this.defaultDb === name) this.defaultDb = null;
294
+ return ddl;
295
+ }
296
+
297
+ async renameDatabase(name: string, newName: string): Promise<string> {
298
+ // MySQL has no RENAME DATABASE. Create the target, move every base table
299
+ // into it (RENAME TABLE moves data instantly, no copy), then drop the old
300
+ // one. Tables (and their data) are migrated losslessly.
301
+ assertSafeIdentifier(name);
302
+ assertSafeIdentifier(newName);
303
+ const sql = this.requireSql();
304
+ await sql.unsafe(`CREATE DATABASE ${Q(newName)}`);
305
+ const rows = (await sql.unsafe(
306
+ "SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE'",
307
+ [name] as never
308
+ )) as Array<{ TABLE_NAME: string }>;
309
+ for (const r of rows) {
310
+ assertSafeIdentifier(r.TABLE_NAME);
311
+ await sql.unsafe(`RENAME TABLE ${qualified(Q, [name, r.TABLE_NAME])} TO ${qualified(Q, [newName, r.TABLE_NAME])}`);
312
+ }
313
+ await sql.unsafe(`DROP DATABASE ${Q(name)}`);
314
+ // Force a fresh `USE` on next access — the session's selected db is gone.
315
+ if (this.defaultDb === name) this.defaultDb = null;
316
+ return `CREATE DATABASE ${Q(newName)}; RENAME TABLE …; DROP DATABASE ${Q(name)}`;
317
+ }
318
+
319
+ async resetDatabase(opts?: SchemaOpts): Promise<string> {
320
+ const target = this.targetDb(opts);
321
+ if (!target) throw new Error('MySQL: database is required');
322
+ const sql = this.requireSql();
323
+ const rows = (await sql.unsafe(
324
+ "SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE'",
325
+ [target] as never
326
+ )) as Array<{ TABLE_NAME: string }>;
327
+ if (rows.length === 0) return '-- no tables to empty';
328
+ rows.forEach((r) => assertSafeIdentifier(r.TABLE_NAME));
329
+ const statements = rows.map((r) => `TRUNCATE TABLE ${qualified(Q, [target, r.TABLE_NAME])}`);
330
+ await sql.unsafe('SET FOREIGN_KEY_CHECKS = 0');
331
+ try {
332
+ for (const stmt of statements) await sql.unsafe(stmt);
333
+ } finally {
334
+ await sql.unsafe('SET FOREIGN_KEY_CHECKS = 1');
335
+ }
336
+ return statements.join(';\n');
337
+ }
338
+
339
+ async resetTable(name: string, opts?: SchemaOpts): Promise<string> {
340
+ // MySQL TRUNCATE already resets AUTO_INCREMENT.
341
+ return this.truncateTable(name, opts);
342
+ }
343
+
344
+ async duplicateTable(name: string, newName: string, opts?: (SchemaOpts & { withData?: boolean })): Promise<string> {
345
+ assertSafeIdentifier(name);
346
+ assertSafeIdentifier(newName);
347
+ const db = this.targetDb(opts);
348
+ const src = qualified(Q, [db, name]);
349
+ const dst = qualified(Q, [db, newName]);
350
+ const sql = this.requireSql();
351
+ const create = `CREATE TABLE ${dst} LIKE ${src}`;
352
+ await sql.unsafe(create);
353
+ const statements = [create];
354
+ if (opts?.withData) {
355
+ const copy = `INSERT INTO ${dst} SELECT * FROM ${src}`;
356
+ await sql.unsafe(copy);
357
+ statements.push(copy);
358
+ }
359
+ return statements.join(';\n');
360
+ }
361
+
362
+ async getCreateStatement(name: string, type: DbClientSchemaNodeType, opts?: SchemaOpts): Promise<string> {
363
+ assertSafeIdentifier(name);
364
+ const fqt = qualified(Q, [this.targetDb(opts), name]);
365
+ const keyword = type === 'view' ? 'VIEW' : 'TABLE';
366
+ const rows = (await this.requireSql().unsafe(`SHOW CREATE ${keyword} ${fqt}`)) as Array<Record<string, unknown>>;
367
+ const row = rows[0] ?? {};
368
+ const ddl = row['Create Table'] ?? row['Create View'] ?? Object.values(row)[1];
369
+ return String(ddl ?? '');
370
+ }
371
+
233
372
  async createTable(definition: TableDefinition, opts?: SchemaOpts): Promise<string> {
234
373
  assertSafeIdentifier(definition.name);
235
374
  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,7 +44,17 @@ 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;
@@ -69,7 +80,9 @@ export class PostgresAdapter implements DbClientDriverAdapter {
69
80
 
70
81
  this.sql = new SQL(url);
71
82
  await this.sql.connect();
72
- this.defaultDb = conn.database || null;
83
+ this.hasConfiguredDb = !!conn.database;
84
+ this.homeDb = conn.database || 'postgres';
85
+ this.defaultDb = this.homeDb;
73
86
  this.defaultSchema = typeof conn.options?.schema === 'string' ? conn.options.schema : 'public';
74
87
  this.conn = conn;
75
88
  this.tunnelPort = tunnelPort;
@@ -77,15 +90,18 @@ export class PostgresAdapter implements DbClientDriverAdapter {
77
90
  }
78
91
 
79
92
  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 };
93
+ if (!this.conn) return;
94
+ // No specific database → revert to the home database, so connection-level
95
+ // operations don't run against whatever database was last browsed.
96
+ const target = database || this.homeDb;
97
+ if (target === this.defaultDb) return;
98
+ const newConn = { ...this.conn, database: target };
83
99
  const url = this.buildUrl(newConn, this.tunnelPort);
84
100
  const next = new SQL(url);
85
101
  await next.connect();
86
102
  const prev = this.sql;
87
103
  this.sql = next;
88
- this.defaultDb = database;
104
+ this.defaultDb = target;
89
105
  this.conn = newConn;
90
106
  this.alive = true;
91
107
  if (prev) await prev.close().catch((err) => debug.warn('db-client', 'pg switch close error:', err));
@@ -154,6 +170,57 @@ export class PostgresAdapter implements DbClientDriverAdapter {
154
170
  return this.executeRead(`EXPLAIN ${q}`, [], opts);
155
171
  }
156
172
 
173
+ // ── Overview ──────────────────────────────────────────────────────────
174
+
175
+ async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
176
+ await this.ensureDatabase(opts?.database);
177
+ const sql = this.requireSql();
178
+ const start = performance.now();
179
+ const verRows = (await sql.unsafe('SELECT version() AS v')) as Array<{ v: string }>;
180
+ const latencyMs = Math.round(performance.now() - start);
181
+
182
+ // Connection level (no configured database, none in scope) → cluster-wide
183
+ // stats rather than the home database's, so it never looks "stuck" on the
184
+ // last-browsed database.
185
+ if (!this.hasConfiguredDb && !opts?.database) {
186
+ const rows = (await sql.unsafe(
187
+ `SELECT COUNT(*) AS dbs, SUM(pg_database_size(datname)) AS size
188
+ FROM pg_database WHERE datistemplate = false`
189
+ )) as Array<Record<string, unknown>>;
190
+ const r = rows[0] ?? {};
191
+ return {
192
+ serverVersion: verRows[0]?.v ?? null,
193
+ latencyMs,
194
+ sizeBytes: r.size === null || r.size === undefined ? null : Number(r.size),
195
+ tableCount: null,
196
+ viewCount: null,
197
+ extra: [{ label: 'Databases', value: String(r.dbs === null || r.dbs === undefined ? 0 : Number(r.dbs)) }]
198
+ };
199
+ }
200
+
201
+ const schema = this.targetSchema(opts);
202
+ const sizeRows = (await sql.unsafe('SELECT pg_database_size(current_database()) AS size')) as Array<{ size: unknown }>;
203
+ const countRows = (await sql.unsafe(
204
+ `SELECT
205
+ COUNT(*) FILTER (WHERE table_type = 'BASE TABLE') AS tables,
206
+ COUNT(*) FILTER (WHERE table_type = 'VIEW') AS views
207
+ FROM information_schema.tables WHERE table_schema = $1`,
208
+ [schema] as never
209
+ )) as Array<Record<string, unknown>>;
210
+ const c = countRows[0] ?? {};
211
+ return {
212
+ serverVersion: verRows[0]?.v ?? null,
213
+ latencyMs,
214
+ sizeBytes: sizeRows[0]?.size === undefined ? null : Number(sizeRows[0].size),
215
+ tableCount: c.tables === undefined ? null : Number(c.tables),
216
+ viewCount: c.views === undefined ? null : Number(c.views),
217
+ extra: [
218
+ { label: 'Database', value: this.defaultDb ?? 'postgres' },
219
+ { label: 'Schema', value: schema }
220
+ ]
221
+ };
222
+ }
223
+
157
224
  // ── Schema ────────────────────────────────────────────────────────────
158
225
 
159
226
  async listDatabases(): Promise<DbClientSchemaNode[]> {
@@ -281,6 +348,86 @@ export class PostgresAdapter implements DbClientDriverAdapter {
281
348
  return ddl;
282
349
  }
283
350
 
351
+ async dropDatabase(name: string): Promise<string> {
352
+ assertSafeIdentifier(name);
353
+ // Postgres refuses to drop the database the session is connected to —
354
+ // hop to the maintenance database first when needed.
355
+ if (this.defaultDb === name) await this.ensureDatabase('postgres');
356
+ const ddl = `DROP DATABASE ${Q(name)}`;
357
+ await this.requireSql().unsafe(ddl);
358
+ return ddl;
359
+ }
360
+
361
+ async renameDatabase(name: string, newName: string): Promise<string> {
362
+ assertSafeIdentifier(name);
363
+ assertSafeIdentifier(newName);
364
+ if (this.defaultDb === name) await this.ensureDatabase('postgres');
365
+ const ddl = `ALTER DATABASE ${Q(name)} RENAME TO ${Q(newName)}`;
366
+ await this.requireSql().unsafe(ddl);
367
+ return ddl;
368
+ }
369
+
370
+ async resetDatabase(opts?: SchemaOpts): Promise<string> {
371
+ await this.ensureDatabase(opts?.database);
372
+ const target = this.targetSchema(opts);
373
+ const sql = this.requireSql();
374
+ const rows = (await sql.unsafe(
375
+ `SELECT table_name FROM information_schema.tables
376
+ WHERE table_schema = $1 AND table_type = 'BASE TABLE' ORDER BY table_name`,
377
+ [target] as never
378
+ )) as Array<{ table_name: string }>;
379
+ if (rows.length === 0) return '-- no tables to empty';
380
+ rows.forEach((r) => assertSafeIdentifier(r.table_name));
381
+ const list = rows.map((r) => qualified(Q, [target, r.table_name])).join(', ');
382
+ const ddl = `TRUNCATE TABLE ${list} RESTART IDENTITY CASCADE`;
383
+ await sql.unsafe(ddl);
384
+ return ddl;
385
+ }
386
+
387
+ async resetTable(name: string, opts?: SchemaOpts): Promise<string> {
388
+ await this.ensureDatabase(opts?.database);
389
+ assertSafeIdentifier(name);
390
+ const ddl = `TRUNCATE TABLE ${qualified(Q, [this.targetSchema(opts), name])} RESTART IDENTITY`;
391
+ await this.requireSql().unsafe(ddl);
392
+ return ddl;
393
+ }
394
+
395
+ async duplicateTable(name: string, newName: string, opts?: (SchemaOpts & { withData?: boolean })): Promise<string> {
396
+ await this.ensureDatabase(opts?.database);
397
+ assertSafeIdentifier(name);
398
+ assertSafeIdentifier(newName);
399
+ const schema = this.targetSchema(opts);
400
+ const src = qualified(Q, [schema, name]);
401
+ const dst = qualified(Q, [schema, newName]);
402
+ const sql = this.requireSql();
403
+ const create = `CREATE TABLE ${dst} (LIKE ${src} INCLUDING ALL)`;
404
+ await sql.unsafe(create);
405
+ const statements = [create];
406
+ if (opts?.withData) {
407
+ const copy = `INSERT INTO ${dst} SELECT * FROM ${src}`;
408
+ await sql.unsafe(copy);
409
+ statements.push(copy);
410
+ }
411
+ return statements.join(';\n');
412
+ }
413
+
414
+ async getCreateStatement(name: string, _type: DbClientSchemaNodeType, opts?: SchemaOpts): Promise<string> {
415
+ // Postgres has no SHOW CREATE; reconstruct a best-effort CREATE TABLE.
416
+ const details = await this.getObjectDetails(name, 'table', opts?.database, opts?.schema);
417
+ const schema = this.targetSchema(opts);
418
+ const detailColumns = details.columns ?? [];
419
+ const cols = detailColumns.map((c) => {
420
+ const parts = [Q(c.name), c.type];
421
+ if (!c.nullable) parts.push('NOT NULL');
422
+ if (c.default !== null && c.default !== undefined && c.default !== '') parts.push(`DEFAULT ${c.default}`);
423
+ return ` ${parts.join(' ')}`;
424
+ });
425
+ const pk = detailColumns.filter((c) => c.isPrimary).map((c) => Q(c.name));
426
+ if (pk.length > 0) cols.push(` PRIMARY KEY (${pk.join(', ')})`);
427
+ const lines = [`CREATE TABLE ${qualified(Q, [schema, name])} (`, cols.join(',\n'), ');'];
428
+ return lines.join('\n');
429
+ }
430
+
284
431
  async createTable(definition: TableDefinition, opts?: SchemaOpts): Promise<string> {
285
432
  await this.ensureDatabase(opts?.database);
286
433
  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}`;