@myrialabs/clopen 0.4.7 → 0.4.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/backend/db-client/drivers/mysql.ts +21 -0
- package/backend/db-client/drivers/postgres.ts +20 -0
- package/backend/db-client/drivers/sqlite.ts +21 -0
- package/backend/db-client/drivers/types.ts +19 -0
- package/backend/db-client/query-executor.ts +89 -1
- package/backend/ws/db-client/query-history-retention.test.ts +217 -0
- package/backend/ws/db-client/query.ts +77 -2
- package/backend/ws/git/ignored.ts +65 -0
- package/backend/ws/git/index.ts +3 -1
- package/dist/assets/__vite-browser-external-BIHI7g3E.js +1 -0
- package/dist/assets/{index-xrB3zcfA.js → index-B_F_OgoC.js} +1 -1
- package/dist/assets/index-jGo0X72U.js +1 -0
- package/dist/assets/{main-LBI3a0n5.js → main-BkCc3WEB.js} +303 -270
- package/dist/assets/main-CWDwET4x.css +1 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm +0 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/db-client/query.ts +33 -0
- package/shared/utils/db-client/split-sql.test.ts +88 -0
- package/shared/utils/db-client/split-sql.ts +132 -0
- package/dist/assets/main-BXS8bjJ6.css +0 -1
|
@@ -18,6 +18,7 @@ import type {
|
|
|
18
18
|
import type {
|
|
19
19
|
AlterOperation,
|
|
20
20
|
DbClientDriverAdapter,
|
|
21
|
+
DbClientTxContext,
|
|
21
22
|
IndexDefinition,
|
|
22
23
|
SchemaOpts,
|
|
23
24
|
TableDefinition
|
|
@@ -157,6 +158,26 @@ export class MysqlAdapter implements DbClientDriverAdapter {
|
|
|
157
158
|
return this.executeRead(`EXPLAIN ${q}`, [], opts);
|
|
158
159
|
}
|
|
159
160
|
|
|
161
|
+
async withTransaction<T>(fn: (tx: DbClientTxContext) => Promise<T>, opts?: { database?: string }): Promise<T> {
|
|
162
|
+
await this.ensureDatabase(opts?.database);
|
|
163
|
+
const sql = this.requireSql();
|
|
164
|
+
// Bun.sql reserves one connection for the `begin` block. Note: MySQL
|
|
165
|
+
// implicitly commits on DDL (CREATE/ALTER/DROP/…), so a batch that
|
|
166
|
+
// mixes DDL with later failures cannot fully roll back the DDL — a
|
|
167
|
+
// server limitation, not an app one.
|
|
168
|
+
return sql.begin(async (tx) => {
|
|
169
|
+
const run = async (q: string, params: unknown[] = []): Promise<DbClientQueryResult> => {
|
|
170
|
+
const start = performance.now();
|
|
171
|
+
const raw = await tx.unsafe(q, params as never);
|
|
172
|
+
return normalizeBunSqlResult(raw, Math.round(performance.now() - start));
|
|
173
|
+
};
|
|
174
|
+
return fn({
|
|
175
|
+
executeRead: (q, params) => run(q, params ?? []),
|
|
176
|
+
executeWrite: (q, params) => run(q, params ?? [])
|
|
177
|
+
});
|
|
178
|
+
}) as Promise<T>;
|
|
179
|
+
}
|
|
180
|
+
|
|
160
181
|
// ── Overview ──────────────────────────────────────────────────────────
|
|
161
182
|
|
|
162
183
|
async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
|
|
@@ -18,6 +18,7 @@ import type {
|
|
|
18
18
|
import type {
|
|
19
19
|
AlterOperation,
|
|
20
20
|
DbClientDriverAdapter,
|
|
21
|
+
DbClientTxContext,
|
|
21
22
|
IndexDefinition,
|
|
22
23
|
SchemaOpts,
|
|
23
24
|
TableDefinition
|
|
@@ -186,6 +187,25 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
186
187
|
return this.executeRead(`EXPLAIN ${q}`, [], opts);
|
|
187
188
|
}
|
|
188
189
|
|
|
190
|
+
async withTransaction<T>(fn: (tx: DbClientTxContext) => Promise<T>, opts?: { database?: string }): Promise<T> {
|
|
191
|
+
await this.ensureDatabase(opts?.database);
|
|
192
|
+
const sql = this.requireSql();
|
|
193
|
+
// Bun.sql reserves a single connection for the duration of `begin`, so
|
|
194
|
+
// every statement below shares one transaction. Postgres wraps DDL in
|
|
195
|
+
// the transaction too, so a mid-batch failure rolls everything back.
|
|
196
|
+
return sql.begin(async (tx) => {
|
|
197
|
+
const run = async (q: string, params: unknown[] = []): Promise<DbClientQueryResult> => {
|
|
198
|
+
const start = performance.now();
|
|
199
|
+
const raw = await tx.unsafe(q, params as never);
|
|
200
|
+
return normalizeBunSqlResult(raw, Math.round(performance.now() - start));
|
|
201
|
+
};
|
|
202
|
+
return fn({
|
|
203
|
+
executeRead: (q, params) => run(q, params ?? []),
|
|
204
|
+
executeWrite: (q, params) => run(q, params ?? [])
|
|
205
|
+
});
|
|
206
|
+
}) as Promise<T>;
|
|
207
|
+
}
|
|
208
|
+
|
|
189
209
|
// ── Overview ──────────────────────────────────────────────────────────
|
|
190
210
|
|
|
191
211
|
async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
|
|
@@ -20,6 +20,7 @@ import type {
|
|
|
20
20
|
import type {
|
|
21
21
|
AlterOperation,
|
|
22
22
|
DbClientDriverAdapter,
|
|
23
|
+
DbClientTxContext,
|
|
23
24
|
IndexDefinition,
|
|
24
25
|
SchemaOpts,
|
|
25
26
|
TableDefinition
|
|
@@ -152,6 +153,26 @@ export class SqliteAdapter implements DbClientDriverAdapter {
|
|
|
152
153
|
return this.executeRead(`EXPLAIN QUERY PLAN ${q}`);
|
|
153
154
|
}
|
|
154
155
|
|
|
156
|
+
async withTransaction<T>(fn: (tx: DbClientTxContext) => Promise<T>): Promise<T> {
|
|
157
|
+
const db = this.requireDb();
|
|
158
|
+
db.exec('BEGIN');
|
|
159
|
+
try {
|
|
160
|
+
const out = await fn({
|
|
161
|
+
executeRead: (q, params) => this.executeRead(q, params ?? []),
|
|
162
|
+
executeWrite: (q, params) => this.executeWrite(q, params ?? [])
|
|
163
|
+
});
|
|
164
|
+
db.exec('COMMIT');
|
|
165
|
+
return out;
|
|
166
|
+
} catch (err) {
|
|
167
|
+
try {
|
|
168
|
+
db.exec('ROLLBACK');
|
|
169
|
+
} catch {
|
|
170
|
+
// Rollback failure is secondary to the error that triggered it.
|
|
171
|
+
}
|
|
172
|
+
throw err;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
155
176
|
// ── Overview ──────────────────────────────────────────────────────────
|
|
156
177
|
|
|
157
178
|
async overview(): Promise<DbClientOverview> {
|
|
@@ -51,6 +51,16 @@ export type AlterOperation =
|
|
|
51
51
|
| { kind: 'rename-column'; name: string; newName: string }
|
|
52
52
|
| { kind: 'modify-column'; column: ColumnDefinition };
|
|
53
53
|
|
|
54
|
+
/**
|
|
55
|
+
* A connection-bound executor handed to `withTransaction`'s callback. Every
|
|
56
|
+
* call runs on the same transaction's connection, so a batch of statements
|
|
57
|
+
* commits or rolls back atomically.
|
|
58
|
+
*/
|
|
59
|
+
export interface DbClientTxContext {
|
|
60
|
+
executeRead(q: string, params?: unknown[], opts?: { database?: string; limit?: number }): Promise<DbClientQueryResult>;
|
|
61
|
+
executeWrite(q: string, params?: unknown[], opts?: { database?: string }): Promise<DbClientQueryResult>;
|
|
62
|
+
}
|
|
63
|
+
|
|
54
64
|
export interface DbClientDriverAdapter {
|
|
55
65
|
readonly kind: DbDriver;
|
|
56
66
|
|
|
@@ -75,6 +85,15 @@ export interface DbClientDriverAdapter {
|
|
|
75
85
|
explain?(q: string, opts?: { database?: string }): Promise<DbClientQueryResult>;
|
|
76
86
|
cancel?(): Promise<void>;
|
|
77
87
|
|
|
88
|
+
/**
|
|
89
|
+
* Run `fn` inside a single database transaction on one dedicated
|
|
90
|
+
* connection. Implemented only by drivers that can guarantee atomicity
|
|
91
|
+
* (a pooled driver must reserve a connection). If `fn` throws, the
|
|
92
|
+
* transaction is rolled back and the error re-thrown. Absence of this
|
|
93
|
+
* method signals the caller to fall back to non-transactional execution.
|
|
94
|
+
*/
|
|
95
|
+
withTransaction?<T>(fn: (tx: DbClientTxContext) => Promise<T>, opts?: { database?: string }): Promise<T>;
|
|
96
|
+
|
|
78
97
|
// Structure
|
|
79
98
|
createDatabase?(name: string): Promise<string>;
|
|
80
99
|
dropDatabase?(name: string): Promise<string>;
|
|
@@ -5,10 +5,12 @@
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import type {
|
|
8
|
+
DbClientBatchResult,
|
|
8
9
|
DbClientQueryResult,
|
|
10
|
+
DbClientStatementResult,
|
|
9
11
|
DbDriver
|
|
10
12
|
} from '$shared/types/db-client';
|
|
11
|
-
import type { DbClientDriverAdapter } from './drivers/types';
|
|
13
|
+
import type { DbClientDriverAdapter, DbClientTxContext } from './drivers/types';
|
|
12
14
|
|
|
13
15
|
export type QueryClass = 'read' | 'write' | 'ddl' | 'unknown';
|
|
14
16
|
|
|
@@ -124,3 +126,89 @@ export async function runSafely(input: RunSafelyInput): Promise<DbClientQueryRes
|
|
|
124
126
|
if (!fn) throw new Error(`Driver ${driver} does not support ${mode}`);
|
|
125
127
|
return fn.call(adapter, query, params, { database });
|
|
126
128
|
}
|
|
129
|
+
|
|
130
|
+
interface ExecuteBatchInput {
|
|
131
|
+
driver: DbDriver;
|
|
132
|
+
adapter: DbClientDriverAdapter;
|
|
133
|
+
statements: string[];
|
|
134
|
+
params?: unknown[];
|
|
135
|
+
database?: string;
|
|
136
|
+
limit?: number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function skippedStatement(index: number, query: string, queryClass: QueryClass): DbClientStatementResult {
|
|
140
|
+
return { index, query, queryClass, status: 'skipped', result: null, error: null, durationMs: 0 };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Execute a pre-split batch of statements in order. Each statement is
|
|
145
|
+
* classified individually and routed to read (auto-LIMITed) or write
|
|
146
|
+
* execution accordingly — the classification of the whole batch never lets a
|
|
147
|
+
* write ride in on the read path. When the driver supports transactions the
|
|
148
|
+
* batch is atomic: the first failure rolls the whole batch back and every
|
|
149
|
+
* later statement is reported as `skipped`.
|
|
150
|
+
*/
|
|
151
|
+
export async function executeBatch(input: ExecuteBatchInput): Promise<DbClientBatchResult> {
|
|
152
|
+
const { driver, adapter, statements, params, database, limit } = input;
|
|
153
|
+
|
|
154
|
+
const runAll = async (exec: DbClientTxContext): Promise<{ results: DbClientStatementResult[]; totalDurationMs: number; failed: boolean }> => {
|
|
155
|
+
const results: DbClientStatementResult[] = [];
|
|
156
|
+
let totalDurationMs = 0;
|
|
157
|
+
let failed = false;
|
|
158
|
+
for (let index = 0; index < statements.length; index++) {
|
|
159
|
+
const query = statements[index];
|
|
160
|
+
const queryClass = classifyQuery(driver, query);
|
|
161
|
+
if (failed) {
|
|
162
|
+
results.push(skippedStatement(index, query, queryClass));
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
const result = queryClass === 'read'
|
|
167
|
+
? await exec.executeRead(applyAutoLimit(query, limit ?? 500), params, { database })
|
|
168
|
+
: await exec.executeWrite(query, params, { database });
|
|
169
|
+
totalDurationMs += result.durationMs;
|
|
170
|
+
results.push({ index, query, queryClass, status: 'success', result, error: null, durationMs: result.durationMs });
|
|
171
|
+
} catch (err) {
|
|
172
|
+
failed = true;
|
|
173
|
+
results.push({
|
|
174
|
+
index,
|
|
175
|
+
query,
|
|
176
|
+
queryClass,
|
|
177
|
+
status: 'error',
|
|
178
|
+
result: null,
|
|
179
|
+
error: err instanceof Error ? err.message : String(err),
|
|
180
|
+
durationMs: 0
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return { results, totalDurationMs, failed };
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
if (typeof adapter.withTransaction === 'function' && statements.length > 1) {
|
|
188
|
+
let captured: { results: DbClientStatementResult[]; totalDurationMs: number; failed: boolean } | null = null;
|
|
189
|
+
try {
|
|
190
|
+
await adapter.withTransaction(async (tx) => {
|
|
191
|
+
captured = await runAll(tx);
|
|
192
|
+
// Throw to force a rollback while preserving the per-statement report.
|
|
193
|
+
if (captured.failed) throw new BatchRollbackSignal();
|
|
194
|
+
}, { database });
|
|
195
|
+
} catch (err) {
|
|
196
|
+
if (!(err instanceof BatchRollbackSignal)) throw err;
|
|
197
|
+
}
|
|
198
|
+
// `captured` is always assigned unless withTransaction never ran the
|
|
199
|
+
// callback (which would have thrown a non-signal error above).
|
|
200
|
+
const c = captured as unknown as { results: DbClientStatementResult[]; totalDurationMs: number; failed: boolean };
|
|
201
|
+
return { statements: c.results, totalDurationMs: c.totalDurationMs, transaction: true, ok: !c.failed };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Non-transactional fallback: statements run sequentially and independently.
|
|
205
|
+
const direct: DbClientTxContext = {
|
|
206
|
+
executeRead: (q, p, o) => runSafely({ driver, adapter, query: q, params: p, mode: 'read', database: o?.database, limit: o?.limit }),
|
|
207
|
+
executeWrite: (q, p, o) => runSafely({ driver, adapter, query: q, params: p, mode: 'write', database: o?.database })
|
|
208
|
+
};
|
|
209
|
+
const { results, totalDurationMs, failed } = await runAll(direct);
|
|
210
|
+
return { statements: results, totalDurationMs, transaction: false, ok: !failed };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Internal sentinel: thrown to trigger a transaction rollback on batch failure. */
|
|
214
|
+
class BatchRollbackSignal extends Error {}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Test query history retention policy enforcement.
|
|
3
|
+
*
|
|
4
|
+
* Verifies that deterministic pruning keeps exactly HISTORY_KEEP_PER_CONNECTION
|
|
5
|
+
* entries after every PRUNE_EVERY_N_QUERIES inserts, replacing the old
|
|
6
|
+
* probabilistic approach that could allow unbounded growth.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { describe, test, expect, beforeEach } from 'bun:test';
|
|
10
|
+
import { initializeDatabase, closeDatabase } from '../../database';
|
|
11
|
+
import { dbClientQueryHistoryQueries } from '../../database/queries';
|
|
12
|
+
import { dbClientConnectionQueries } from '../../database/queries';
|
|
13
|
+
|
|
14
|
+
const HISTORY_KEEP_PER_CONNECTION = 200;
|
|
15
|
+
const PRUNE_EVERY_N_QUERIES = 10;
|
|
16
|
+
|
|
17
|
+
describe('Query History Retention', () => {
|
|
18
|
+
beforeEach(async () => {
|
|
19
|
+
await initializeDatabase();
|
|
20
|
+
// Clean up any existing test data
|
|
21
|
+
const db = await import('../../database').then(m => m.getDatabase());
|
|
22
|
+
db.prepare('DELETE FROM db_client_query_history').run();
|
|
23
|
+
db.prepare('DELETE FROM db_client_connections').run();
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('prunes history after PRUNE_EVERY_N_QUERIES inserts', () => {
|
|
27
|
+
// Create a test connection
|
|
28
|
+
const connection = dbClientConnectionQueries.createForUser({
|
|
29
|
+
name: 'test-connection',
|
|
30
|
+
driver: 'postgres',
|
|
31
|
+
host: 'localhost',
|
|
32
|
+
port: 5432,
|
|
33
|
+
username: 'test',
|
|
34
|
+
password: 'test',
|
|
35
|
+
database: 'testdb',
|
|
36
|
+
sslMode: 'disable',
|
|
37
|
+
ssh: {
|
|
38
|
+
enabled: false,
|
|
39
|
+
host: '',
|
|
40
|
+
port: 22,
|
|
41
|
+
username: '',
|
|
42
|
+
authMethod: 'password',
|
|
43
|
+
password: '',
|
|
44
|
+
privateKey: '',
|
|
45
|
+
passphrase: ''
|
|
46
|
+
},
|
|
47
|
+
options: {}
|
|
48
|
+
}, 'test-user-id');
|
|
49
|
+
|
|
50
|
+
// Insert HISTORY_KEEP_PER_CONNECTION + 50 queries (250 total)
|
|
51
|
+
const totalQueries = HISTORY_KEEP_PER_CONNECTION + 50;
|
|
52
|
+
for (let i = 0; i < totalQueries; i++) {
|
|
53
|
+
dbClientQueryHistoryQueries.insert({
|
|
54
|
+
connectionId: connection.id,
|
|
55
|
+
userId: 'test-user-id',
|
|
56
|
+
query: `SELECT ${i};`,
|
|
57
|
+
durationMs: Math.random() * 100,
|
|
58
|
+
rowCount: 1,
|
|
59
|
+
status: 'success',
|
|
60
|
+
error: null
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// Manually trigger prune every PRUNE_EVERY_N_QUERIES
|
|
64
|
+
if ((i + 1) % PRUNE_EVERY_N_QUERIES === 0) {
|
|
65
|
+
dbClientQueryHistoryQueries.prune(connection.id, HISTORY_KEEP_PER_CONNECTION);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Verify exactly HISTORY_KEEP_PER_CONNECTION entries remain
|
|
70
|
+
const { total } = dbClientQueryHistoryQueries.list({
|
|
71
|
+
connectionId: connection.id,
|
|
72
|
+
limit: 1000
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
expect(total).toBe(HISTORY_KEEP_PER_CONNECTION);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('keeps most recent queries after pruning', () => {
|
|
79
|
+
const connection = dbClientConnectionQueries.createForUser({
|
|
80
|
+
name: 'test-connection-2',
|
|
81
|
+
driver: 'postgres',
|
|
82
|
+
host: 'localhost',
|
|
83
|
+
port: 5432,
|
|
84
|
+
username: 'test',
|
|
85
|
+
password: 'test',
|
|
86
|
+
database: 'testdb',
|
|
87
|
+
sslMode: 'disable',
|
|
88
|
+
ssh: {
|
|
89
|
+
enabled: false,
|
|
90
|
+
host: '',
|
|
91
|
+
port: 22,
|
|
92
|
+
username: '',
|
|
93
|
+
authMethod: 'password',
|
|
94
|
+
password: '',
|
|
95
|
+
privateKey: '',
|
|
96
|
+
passphrase: ''
|
|
97
|
+
},
|
|
98
|
+
options: {}
|
|
99
|
+
}, 'test-user-id');
|
|
100
|
+
|
|
101
|
+
// Insert 250 queries — more than HISTORY_KEEP_PER_CONNECTION
|
|
102
|
+
for (let i = 0; i < 250; i++) {
|
|
103
|
+
dbClientQueryHistoryQueries.insert({
|
|
104
|
+
connectionId: connection.id,
|
|
105
|
+
userId: 'test-user-id',
|
|
106
|
+
query: `SELECT ${i};`,
|
|
107
|
+
durationMs: 10,
|
|
108
|
+
rowCount: 1,
|
|
109
|
+
status: 'success',
|
|
110
|
+
error: null
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
if ((i + 1) % PRUNE_EVERY_N_QUERIES === 0) {
|
|
114
|
+
dbClientQueryHistoryQueries.prune(connection.id, HISTORY_KEEP_PER_CONNECTION);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const { items, total } = dbClientQueryHistoryQueries.list({
|
|
119
|
+
connectionId: connection.id,
|
|
120
|
+
limit: 1000
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
expect(total).toBe(HISTORY_KEEP_PER_CONNECTION);
|
|
124
|
+
expect(items.length).toBe(HISTORY_KEEP_PER_CONNECTION);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test('prune does not affect other connections', () => {
|
|
128
|
+
// Create two connections
|
|
129
|
+
const conn1 = dbClientConnectionQueries.createForUser({
|
|
130
|
+
name: 'connection-1',
|
|
131
|
+
driver: 'postgres',
|
|
132
|
+
host: 'localhost',
|
|
133
|
+
port: 5432,
|
|
134
|
+
username: 'test',
|
|
135
|
+
password: 'test',
|
|
136
|
+
database: 'testdb',
|
|
137
|
+
sslMode: 'disable',
|
|
138
|
+
ssh: {
|
|
139
|
+
enabled: false,
|
|
140
|
+
host: '',
|
|
141
|
+
port: 22,
|
|
142
|
+
username: '',
|
|
143
|
+
authMethod: 'password',
|
|
144
|
+
password: '',
|
|
145
|
+
privateKey: '',
|
|
146
|
+
passphrase: ''
|
|
147
|
+
},
|
|
148
|
+
options: {}
|
|
149
|
+
}, 'user-1');
|
|
150
|
+
|
|
151
|
+
const conn2 = dbClientConnectionQueries.createForUser({
|
|
152
|
+
name: 'connection-2',
|
|
153
|
+
driver: 'mysql',
|
|
154
|
+
host: 'localhost',
|
|
155
|
+
port: 3306,
|
|
156
|
+
username: 'test',
|
|
157
|
+
password: 'test',
|
|
158
|
+
database: 'testdb',
|
|
159
|
+
sslMode: 'disable',
|
|
160
|
+
ssh: {
|
|
161
|
+
enabled: false,
|
|
162
|
+
host: '',
|
|
163
|
+
port: 22,
|
|
164
|
+
username: '',
|
|
165
|
+
authMethod: 'password',
|
|
166
|
+
password: '',
|
|
167
|
+
privateKey: '',
|
|
168
|
+
passphrase: ''
|
|
169
|
+
},
|
|
170
|
+
options: {}
|
|
171
|
+
}, 'user-2');
|
|
172
|
+
|
|
173
|
+
// Insert 250 queries for conn1
|
|
174
|
+
for (let i = 0; i < 250; i++) {
|
|
175
|
+
dbClientQueryHistoryQueries.insert({
|
|
176
|
+
connectionId: conn1.id,
|
|
177
|
+
userId: 'user-1',
|
|
178
|
+
query: `SELECT ${i};`,
|
|
179
|
+
durationMs: 10,
|
|
180
|
+
rowCount: 1,
|
|
181
|
+
status: 'success',
|
|
182
|
+
error: null
|
|
183
|
+
});
|
|
184
|
+
if ((i + 1) % PRUNE_EVERY_N_QUERIES === 0) {
|
|
185
|
+
dbClientQueryHistoryQueries.prune(conn1.id, HISTORY_KEEP_PER_CONNECTION);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Insert only 50 queries for conn2
|
|
190
|
+
for (let i = 0; i < 50; i++) {
|
|
191
|
+
dbClientQueryHistoryQueries.insert({
|
|
192
|
+
connectionId: conn2.id,
|
|
193
|
+
userId: 'user-2',
|
|
194
|
+
query: `SELECT ${i};`,
|
|
195
|
+
durationMs: 10,
|
|
196
|
+
rowCount: 1,
|
|
197
|
+
status: 'success',
|
|
198
|
+
error: null
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Verify conn1 has exactly 200
|
|
203
|
+
const { total: total1 } = dbClientQueryHistoryQueries.list({
|
|
204
|
+
connectionId: conn1.id,
|
|
205
|
+
limit: 1000
|
|
206
|
+
});
|
|
207
|
+
expect(total1).toBe(HISTORY_KEEP_PER_CONNECTION);
|
|
208
|
+
|
|
209
|
+
// Verify conn2 still has all 50 (not affected by conn1 pruning)
|
|
210
|
+
const { total: total2 } = dbClientQueryHistoryQueries.list({
|
|
211
|
+
connectionId: conn2.id,
|
|
212
|
+
limit: 1000
|
|
213
|
+
});
|
|
214
|
+
expect(total2).toBe(50);
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
|
|
@@ -3,14 +3,20 @@
|
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
import { t } from 'elysia';
|
|
6
|
+
import type { DbClientQueryResult } from '$shared/types/db-client';
|
|
6
7
|
import { createRouter } from '$shared/utils/ws-server';
|
|
7
8
|
import { connectionManager } from '../../db-client/connection-manager';
|
|
8
|
-
import { runSafely } from '../../db-client/query-executor';
|
|
9
|
+
import { executeBatch, runSafely } from '../../db-client/query-executor';
|
|
10
|
+
import { splitSqlStatements } from '$shared/utils/db-client/split-sql';
|
|
9
11
|
import { dbClientQueryHistoryQueries } from '../../database/queries';
|
|
10
12
|
import { getDbClientPrincipal, requireDbClientConnectionAccess } from './access';
|
|
11
13
|
import { debug } from '$shared/utils/logger';
|
|
12
14
|
|
|
13
15
|
const HISTORY_KEEP_PER_CONNECTION = 200;
|
|
16
|
+
const PRUNE_EVERY_N_QUERIES = 10;
|
|
17
|
+
|
|
18
|
+
// Track insert count per connection for deterministic pruning
|
|
19
|
+
const insertCounters = new Map<string, number>();
|
|
14
20
|
|
|
15
21
|
function recordHistory(input: {
|
|
16
22
|
connectionId: string;
|
|
@@ -31,8 +37,14 @@ function recordHistory(input: {
|
|
|
31
37
|
status: input.status,
|
|
32
38
|
error: input.error
|
|
33
39
|
});
|
|
34
|
-
|
|
40
|
+
|
|
41
|
+
// Deterministic pruning: prune after every N inserts
|
|
42
|
+
const count = (insertCounters.get(input.connectionId) ?? 0) + 1;
|
|
43
|
+
insertCounters.set(input.connectionId, count);
|
|
44
|
+
|
|
45
|
+
if (count >= PRUNE_EVERY_N_QUERIES) {
|
|
35
46
|
dbClientQueryHistoryQueries.prune(input.connectionId, HISTORY_KEEP_PER_CONNECTION);
|
|
47
|
+
insertCounters.set(input.connectionId, 0);
|
|
36
48
|
}
|
|
37
49
|
} catch (err) {
|
|
38
50
|
// history must never break query execution
|
|
@@ -133,6 +145,69 @@ export const queryHandler = createRouter()
|
|
|
133
145
|
}
|
|
134
146
|
})
|
|
135
147
|
|
|
148
|
+
.http('db-client:execute-batch', {
|
|
149
|
+
data: t.Object({
|
|
150
|
+
connectionId: t.String({ minLength: 1 }),
|
|
151
|
+
query: t.String({ minLength: 1 }),
|
|
152
|
+
params: t.Optional(t.Array(t.Any())),
|
|
153
|
+
database: t.Optional(t.String()),
|
|
154
|
+
limit: t.Optional(t.Number())
|
|
155
|
+
}),
|
|
156
|
+
response: t.Any()
|
|
157
|
+
}, async ({ data, conn }) => {
|
|
158
|
+
const { userId } = getDbClientPrincipal(conn);
|
|
159
|
+
const connection = requireDbClientConnectionAccess(conn, data.connectionId);
|
|
160
|
+
const adapter = await connectionManager.get(data.connectionId);
|
|
161
|
+
// Statement splitting is a SQL concern; Mongo/Redis payloads run whole.
|
|
162
|
+
const isSql = connection.driver === 'mysql' || connection.driver === 'postgres' || connection.driver === 'sqlite';
|
|
163
|
+
const split = isSql ? splitSqlStatements(data.query) : [data.query.trim()];
|
|
164
|
+
const statements = split.length > 0 ? split : [data.query.trim()];
|
|
165
|
+
try {
|
|
166
|
+
const batch = await executeBatch({
|
|
167
|
+
driver: connection.driver,
|
|
168
|
+
adapter,
|
|
169
|
+
statements,
|
|
170
|
+
params: data.params,
|
|
171
|
+
database: data.database,
|
|
172
|
+
limit: data.limit
|
|
173
|
+
});
|
|
174
|
+
const rowCount = batch.statements.reduce((acc, s) => acc + (s.result?.rowCount ?? 0), 0);
|
|
175
|
+
const affectedRows = batch.statements.reduce((acc, s) => acc + (s.result?.affectedRows ?? 0), 0);
|
|
176
|
+
const failed = batch.statements.find((s) => s.status === 'error');
|
|
177
|
+
recordHistory({
|
|
178
|
+
connectionId: data.connectionId,
|
|
179
|
+
userId,
|
|
180
|
+
query: data.query,
|
|
181
|
+
status: batch.ok ? 'success' : 'error',
|
|
182
|
+
durationMs: batch.totalDurationMs,
|
|
183
|
+
rowCount,
|
|
184
|
+
error: failed?.error ?? null
|
|
185
|
+
});
|
|
186
|
+
// Mirror the last statement that produced rows at the top level (so
|
|
187
|
+
// existing single-result consumers keep working) with the full
|
|
188
|
+
// per-statement report attached under `batch`.
|
|
189
|
+
const reversed = [...batch.statements].reverse();
|
|
190
|
+
const lastResult = reversed.find((s) => s.result && s.result.rows.length > 0)?.result
|
|
191
|
+
?? reversed.find((s) => s.result)?.result
|
|
192
|
+
?? null;
|
|
193
|
+
const top: DbClientQueryResult = lastResult
|
|
194
|
+
? { ...lastResult, durationMs: batch.totalDurationMs, batch }
|
|
195
|
+
: { columns: [], rows: [], rowCount, affectedRows, durationMs: batch.totalDurationMs, driverMeta: {}, batch };
|
|
196
|
+
return top;
|
|
197
|
+
} catch (error) {
|
|
198
|
+
recordHistory({
|
|
199
|
+
connectionId: data.connectionId,
|
|
200
|
+
userId,
|
|
201
|
+
query: data.query,
|
|
202
|
+
status: 'error',
|
|
203
|
+
durationMs: null,
|
|
204
|
+
rowCount: null,
|
|
205
|
+
error: error instanceof Error ? error.message : String(error)
|
|
206
|
+
});
|
|
207
|
+
throw error;
|
|
208
|
+
}
|
|
209
|
+
})
|
|
210
|
+
|
|
136
211
|
.http('db-client:explain', {
|
|
137
212
|
data: t.Object({
|
|
138
213
|
connectionId: t.String({ minLength: 1 }),
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { t } from 'elysia';
|
|
2
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
3
|
+
import { execGit } from '../../git/git-executor';
|
|
4
|
+
import { requireProjectAccess } from '../access';
|
|
5
|
+
import path from 'path';
|
|
6
|
+
|
|
7
|
+
export const ignoredHandler = createRouter()
|
|
8
|
+
.http('git:ignored-paths', {
|
|
9
|
+
data: t.Object({
|
|
10
|
+
projectId: t.String()
|
|
11
|
+
}),
|
|
12
|
+
response: t.Object({
|
|
13
|
+
ignored: t.Array(t.String())
|
|
14
|
+
})
|
|
15
|
+
}, async ({ data, conn }) => {
|
|
16
|
+
const project = requireProjectAccess(conn, data.projectId);
|
|
17
|
+
const ignored: string[] = [];
|
|
18
|
+
|
|
19
|
+
try {
|
|
20
|
+
const isRepo = await execGit(['rev-parse', '--is-inside-work-tree'], project.path, 5_000)
|
|
21
|
+
.then(r => r.exitCode === 0)
|
|
22
|
+
.catch(() => false);
|
|
23
|
+
|
|
24
|
+
if (!isRepo) return { ignored };
|
|
25
|
+
|
|
26
|
+
// Get ignored files (leaf paths)
|
|
27
|
+
const filesResult = await execGit(
|
|
28
|
+
['ls-files', '--others', '--ignored', '--exclude-standard'],
|
|
29
|
+
project.path,
|
|
30
|
+
30_000
|
|
31
|
+
);
|
|
32
|
+
if (filesResult.exitCode === 0) {
|
|
33
|
+
const sep = project.path.includes('\\') ? '\\' : '/';
|
|
34
|
+
for (const line of filesResult.stdout.split('\n')) {
|
|
35
|
+
const relPath = line.trim();
|
|
36
|
+
if (!relPath) continue;
|
|
37
|
+
ignored.push(path.join(project.path, relPath.replace(/\//g, sep)));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Get ignored directories (shown with --directory flag)
|
|
42
|
+
const dirsResult = await execGit(
|
|
43
|
+
['ls-files', '--others', '--ignored', '--exclude-standard', '--directory'],
|
|
44
|
+
project.path,
|
|
45
|
+
30_000
|
|
46
|
+
);
|
|
47
|
+
if (dirsResult.exitCode === 0) {
|
|
48
|
+
const seen = new Set(ignored);
|
|
49
|
+
const sep = project.path.includes('\\') ? '\\' : '/';
|
|
50
|
+
for (const line of dirsResult.stdout.split('\n')) {
|
|
51
|
+
const relPath = line.trim().replace(/\/$/, '');
|
|
52
|
+
if (!relPath) continue;
|
|
53
|
+
const absPath = path.join(project.path, relPath.replace(/\//g, sep));
|
|
54
|
+
if (!seen.has(absPath)) {
|
|
55
|
+
ignored.push(absPath);
|
|
56
|
+
seen.add(absPath);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
} catch {
|
|
61
|
+
// If git fails, return empty
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return { ignored };
|
|
65
|
+
});
|
package/backend/ws/git/index.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { remoteHandler } from './remote';
|
|
|
14
14
|
import { conflictHandler } from './conflict';
|
|
15
15
|
import { commitMessageHandler } from './commit-message';
|
|
16
16
|
import { branchNameHandler } from './branch-name';
|
|
17
|
+
import { ignoredHandler } from './ignored';
|
|
17
18
|
|
|
18
19
|
export const gitRouter = createRouter()
|
|
19
20
|
.merge(statusHandler)
|
|
@@ -25,4 +26,5 @@ export const gitRouter = createRouter()
|
|
|
25
26
|
.merge(remoteHandler)
|
|
26
27
|
.merge(conflictHandler)
|
|
27
28
|
.merge(commitMessageHandler)
|
|
28
|
-
.merge(branchNameHandler)
|
|
29
|
+
.merge(branchNameHandler)
|
|
30
|
+
.merge(ignoredHandler);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e={};export{e as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{s as _,_ as d,r as s,a as u}from"./main-
|
|
1
|
+
import{s as _,_ as d,r as s,a as u}from"./main-BkCc3WEB.js";import{C as T,P as y,W as E,d as L,b as g,c as v,h as P,l as b,m as k,e as D,n as O,f as R,g as S,t as V}from"./main-BkCc3WEB.js";async function h(o,e={}){const i=e.loading===!1?void 0:_(o,e.loadingText??"Loading…"),[{Terminal:l},{FitAddon:c}]=await Promise.all([d(()=>import("./xterm-B-qIQCd3.js"),[]),d(()=>import("./addon-fit-DX4qG4td.js"),[])]).catch(r=>{throw i?.(),r}),a=new l({scrollback:e.scrollback??5e3,fontSize:e.fontSize??13,fontFamily:e.fontFamily??"ui-monospace, SFMono-Regular, Menlo, monospace",lineHeight:e.lineHeight??1,cursorBlink:e.cursorBlink??!1,cursorStyle:e.cursorStyle??"block",disableStdin:e.stdin!==!0,allowProposedApi:!0,convertEol:!0,theme:s(e.theme),...e.cols?{cols:e.cols}:{},...e.rows?{rows:e.rows}:{},...e.terminalOptions??{}}),t=e.fit===!1?void 0:new c;if(t&&a.loadAddon(t),e.clipboard)try{const{ClipboardAddon:r}=await d(()=>import("./addon-clipboard-wHJhZAA4.js"),[]);a.loadAddon(new r)}catch{}if(e.webLinks)try{const{WebLinksAddon:r}=await d(()=>import("./addon-web-links-DIbG5aQx.js"),[]);a.loadAddon(new r)}catch{}if(e.unicode11)try{const{Unicode11Addon:r}=await d(()=>import("./addon-unicode11-Bt8F3D7-.js"),[]);a.loadAddon(new r),a.unicode.activeVersion="11"}catch{}for(const r of e.addons??[])a.loadAddon(r);if(a.open(o),e.ligatures)try{const{LigaturesAddon:r}=await d(()=>import("./addon-ligatures-DpDY8N_X.js"),[]);a.loadAddon(new r)}catch{}const m=t?u({resize:async()=>{}},a,t,{debounceMs:e.fitDebounceMs??100}):void 0;e.onReady?.(a),i?.();let n=!1;return{terminal:a,fitAddon:t,write:r=>a.write(r),clear:()=>{a.clear(),a.reset()},fit:()=>t?.fit(),setTheme:r=>{a.options.theme=s(r)},dispose(){n||(n=!0,m?.(),a.dispose())}}}export{T as ClientSession,y as PtyKitClient,E as WsCore,u as attachFit,L as darkTheme,g as defaultPersistence,v as draculaTheme,P as hostSocket,b as lightTheme,k as matrixTheme,D as mountTerminal,h as mountViewer,O as nordTheme,s as resolveTheme,_ as showLoadingOverlay,R as solarizedDarkTheme,S as solarizedLightTheme,V as themes};
|