-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.ts
More file actions
444 lines (386 loc) · 13.2 KB
/
Copy pathdb.ts
File metadata and controls
444 lines (386 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/**
* Typed Tauri command client.
*
* All Rust backend calls go through this module. There is no HTTP layer —
* each function maps to one `invoke('db_*', ...)` call. Session state lives
* here because the Rust DashMap is process-scoped: a webview reload drops
* the session, matching module-memory lifetime.
*
* Read/write classification for the SQL editor is done in JS via
* lib/query-classifier (intentional — classifier-as-safety only matters
* across a hostile client/server boundary, which doesn't exist when the
* user owns the binary).
*/
import { invoke as tauriInvoke, type InvokeArgs } from "@tauri-apps/api/core";
import { classifyQuery, requiresTypedConfirmation } from "./query-classifier";
import type { DBConfig, SavedConnection } from "@/types";
import type { Filter } from "./filters";
import type { MutationRequest } from "./mutation";
let sessionId: string | null = null;
export function getSessionId(): string | null {
return sessionId;
}
// Dev-only debug hook — surface internal connection state to the devtools
// console so we can diagnose "Not connected" mysteries without adding
// throwaway logs. Drop later if/when the debugging stops being useful.
if (typeof window !== 'undefined') {
(window as unknown as { __justdbDebug: unknown }).__justdbDebug = {
get sessionId() { return sessionId; },
};
}
function requireSession(): string {
if (!sessionId) {
throw new Error("Not connected. Connect to a database first.");
}
return sessionId;
}
function invoke<T>(cmd: string, args?: InvokeArgs): Promise<T> {
return tauriInvoke<T>(cmd, args);
}
// ─── connection lifecycle ────────────────────────────────────────────────
interface ConnectResult {
sessionId: string;
database: string;
type: string;
savedConnection?: SavedConnection;
}
// Rust's ConnectResponse — `db_type` is the authoritative backend kind,
// echoed back from the persisted config (saved connections don't keep
// `type` on the JS side, so the form-provided value would be lost otherwise).
interface ConnectInvokeResponse {
sessionId: string;
database: string;
dbType: "postgresql" | "sqlite";
}
async function connect(
config: DBConfig,
save?: { name: string; id: string },
): Promise<ConnectResult> {
// Keep the prior session valid until the new one is established. We
// used to pre-emptively `await disconnect()` here, which left the JS
// sessionId = null during the few-hundred-ms while the new connect
// resolved. Any health-poll or table-data query that fired in that
// window threw "Not connected" → the dashboard rendered Connection
// lost / Reconnecting state for a perfectly healthy connection.
const oldSessionId = sessionId;
const res = await invoke<ConnectInvokeResponse>("db_connect", { config });
sessionId = res.sessionId;
if (oldSessionId && oldSessionId !== res.sessionId) {
// Best-effort cleanup of the prior session — runs in the background
// so a slow disconnect doesn't delay the new session being usable.
invoke<void>("db_disconnect", { sessionId: oldSessionId }).catch(() => {});
}
let savedConnection: SavedConnection | undefined;
if (save) {
try {
savedConnection = await invoke<SavedConnection>("db_saved_create", {
id: save.id,
name: save.name,
config,
});
} catch (e) {
// Keychain write failing (e.g. Linux without gnome-keyring) shouldn't
// fail the connect. User is connected; the connection just isn't saved.
console.error("[db] saved-connection write failed:", e);
}
}
return {
sessionId: res.sessionId,
database: res.database,
type: res.dbType,
savedConnection,
};
}
async function connectSaved(
id: string,
): Promise<{ sessionId: string; database: string; type: "postgresql" | "sqlite" }> {
// See `connect` above for why the prior sessionId stays live until the
// new one resolves.
const oldSessionId = sessionId;
const res = await invoke<ConnectInvokeResponse>("db_saved_connect", { id });
sessionId = res.sessionId;
if (oldSessionId && oldSessionId !== res.sessionId) {
invoke<void>("db_disconnect", { sessionId: oldSessionId }).catch(() => {});
}
return { sessionId: res.sessionId, database: res.database, type: res.dbType };
}
// Drop a specific session id without touching the module-level current
// sessionId — unless that current id is the one we're dropping, in which
// case clear it too. Used to clean up orphans from cancelled connects
// without disturbing a fresh attempt that already raced ahead.
async function disconnectId(id: string): Promise<void> {
await invoke<void>("db_disconnect", { sessionId: id }).catch(() => {});
if (sessionId === id) sessionId = null;
}
async function disconnect(): Promise<void> {
if (!sessionId) return;
await invoke<void>("db_disconnect", { sessionId });
sessionId = null;
}
interface HealthState {
healthy: boolean;
latency: number | null;
activeConnections?: number;
idleConnections?: number;
}
async function health(): Promise<HealthState> {
if (!sessionId) {
return { healthy: false, latency: null, activeConnections: 0, idleConnections: 0 };
}
return invoke<HealthState>("db_health", { sessionId });
}
// ─── catalog listings ─────────────────────────────────────────────────────
const listSchemas = () =>
invoke<string[]>("db_list_schemas", { sessionId: requireSession() });
const listTables = (schema = "public") =>
invoke<string[]>("db_list_tables", { sessionId: requireSession(), schema });
// The Rust ViewsResponse already shapes the camelCase fields; pass straight.
const listViews = (schema = "public") =>
invoke<{ views: string[]; materializedViews: string[] }>("db_views", {
sessionId: requireSession(),
schema,
});
// Rust wraps in `{ functions }` — peel for callers.
const listFunctions = async (schema = "public"): Promise<unknown[]> => {
const res = await invoke<{ functions: unknown[] }>("db_functions", {
sessionId: requireSession(),
schema,
});
return res.functions ?? [];
};
// Rust wraps in `{ schemaMap }` — peel.
const schemaMap = async (schema = "public"): Promise<Record<string, string[]>> => {
const res = await invoke<{ schemaMap: Record<string, string[]> }>(
"db_schema_map",
{ sessionId: requireSession(), schema },
);
return res.schemaMap ?? {};
};
// Typed schema overview (column types + PK/FK) for the whole schema — used to
// ground the AI. Rust wraps in `{ tables }` — peel.
const schemaOverview = async (schema = "public"): Promise<SchemaOverviewTable[]> => {
const res = await invoke<{ tables: SchemaOverviewTable[] }>("db_schema_overview", {
sessionId: requireSession(),
schema,
});
return res.tables ?? [];
};
// Rust wraps in `{ counts }` — peel.
const tableCounts = async (schema = "public"): Promise<Record<string, number>> => {
const res = await invoke<{ counts: Record<string, number> }>(
"db_table_counts",
{ sessionId: requireSession(), schema },
);
return res.counts ?? {};
};
// ─── table-level reads ────────────────────────────────────────────────────
interface TableRowsArgs {
table: string;
schema?: string;
limit?: number;
offset?: number;
sortColumn?: string;
sortDirection?: "asc" | "desc";
filters?: Filter[];
}
interface TableRowsResponse {
rows: any[];
total: number;
limit: number;
offset: number;
countIsEstimate: boolean;
}
function tableRows(args: TableRowsArgs): Promise<TableRowsResponse> {
return invoke<TableRowsResponse>("db_table_rows", {
sessionId: requireSession(),
schema: args.schema ?? "public",
limit: args.limit ?? 100,
offset: args.offset ?? 0,
table: args.table,
sortColumn: args.sortColumn,
sortDirection: args.sortDirection,
filters: args.filters && args.filters.length > 0 ? args.filters : undefined,
});
}
const tableSchema = (table: string, schema = "public") =>
invoke<any[]>("db_table_schema", {
sessionId: requireSession(),
table,
schema,
});
const relationships = (table: string, schema = "public") =>
invoke<{ relationships: any[]; indexes: any[] }>("db_relationships", {
sessionId: requireSession(),
table,
schema,
});
// Rust wraps in `{ stats }` — peel.
const tableStats = async (table: string, schema = "public"): Promise<any> => {
const res = await invoke<{ stats: any }>("db_table_stats", {
sessionId: requireSession(),
table,
schema,
});
return res?.stats ?? null;
};
// ─── mutations / DDL ──────────────────────────────────────────────────────
const mutate = (request: MutationRequest) =>
invoke<unknown>("db_mutate", { sessionId: requireSession(), body: request });
const mutateBatch = (changes: MutationRequest[]) =>
invoke<unknown>("db_mutate_batch", {
sessionId: requireSession(),
changes,
});
const ddl = (sql: string) =>
invoke<unknown>("db_ddl", { sessionId: requireSession(), sql });
const cascadePreview = (deletes: unknown[], options?: unknown) =>
invoke<any>("db_cascade_preview", {
sessionId: requireSession(),
deletes,
options,
});
interface LookupRowArgs {
schema: string;
table: string;
column: string;
value: unknown;
}
const lookupRow = (args: LookupRowArgs) =>
invoke<{ rows: any[] }>("db_lookup_row", {
sessionId: requireSession(),
schema: args.schema,
table: args.table,
column: args.column,
value: args.value ?? null,
});
interface ImportArgs {
schema: string;
table: string;
columns: string[];
rows: unknown[][];
batchSize?: number;
}
const importRows = (args: ImportArgs) =>
invoke<{ insertedRows: number }>("db_import", {
sessionId: requireSession(),
...args,
});
const explain = (query: string) =>
invoke<any>("db_explain", { sessionId: requireSession(), query });
// ─── saved connections (OS keychain) ─────────────────────────────────────
const savedList = () => invoke<SavedConnection[]>("db_saved_list");
const savedCreate = (id: string, name: string, config: DBConfig) =>
invoke<SavedConnection>("db_saved_create", { id, name, config });
const savedDelete = (id: string) =>
invoke<void>("db_saved_delete", { id });
// ─── SQL editor (classifier gate stays in JS) ────────────────────────────
interface RunQueryConfirmation {
needsConfirmation: true;
preview: string;
classification: {
kind: "write" | "ddl";
statement: string;
isBulkWrite: boolean;
requiresTypedConfirmation: boolean;
};
}
interface RunQueryResult {
needsConfirmation?: false;
rows: any[];
executionTime: number;
fields: any[];
classification: {
kind: string;
statement: string;
isBulkWrite: boolean;
};
}
async function runQuery(
query: string,
confirmed = false,
): Promise<RunQueryConfirmation | RunQueryResult> {
const sid = requireSession();
const classification = classifyQuery(query);
if (classification.kind === "blocked" || classification.kind === "unknown") {
throw new Error(
classification.reason ||
`Statements of type ${classification.statement || "(unknown)"} are not allowed`,
);
}
if (
(classification.kind === "write" || classification.kind === "ddl") &&
!confirmed
) {
return {
needsConfirmation: true,
preview: query,
classification: {
kind: classification.kind,
statement: classification.statement,
isBulkWrite: classification.isBulkWrite,
requiresTypedConfirmation: requiresTypedConfirmation(classification),
},
};
}
const result = await invoke<{
rows: any[];
executionTime: number;
fields: any[];
}>("db_run_query", { sessionId: sid, sql: query });
return {
...result,
classification: {
kind: classification.kind,
statement: classification.statement,
isBulkWrite: classification.isBulkWrite,
},
};
}
// ─── public API ──────────────────────────────────────────────────────────
export const db = {
// connection lifecycle
connect,
connectSaved,
disconnect,
disconnectId,
health,
isConnected: () => sessionId !== null,
// listings
listSchemas,
listTables,
listViews,
listFunctions,
schemaMap,
schemaOverview,
tableCounts,
// table-level
tableRows,
tableSchema,
relationships,
tableStats,
// mutations
mutate,
mutateBatch,
ddl,
cascadePreview,
lookupRow,
importRows,
explain,
// saved connections
savedList,
savedCreate,
savedDelete,
// SQL editor
runQuery,
};
export interface SchemaOverviewColumn {
name: string;
type: string;
pk: boolean;
fk?: { table: string; column: string };
}
export interface SchemaOverviewTable {
name: string;
columns: SchemaOverviewColumn[];
}
export type { TableRowsResponse, ConnectResult, HealthState, RunQueryResult, RunQueryConfirmation };