@myrialabs/clopen 0.4.14 → 0.4.15
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/auth/permissions.ts +2 -0
- package/backend/database/migrations/056_support_mssql_driver.ts +137 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/engine-queries.ts +13 -0
- package/backend/database/queries/message-queries.ts +43 -1
- package/backend/db-client/connection-manager.ts +8 -2
- package/backend/db-client/drivers/mssql.ts +829 -0
- package/backend/db-client/drivers/mysql.ts +33 -4
- package/backend/db-client/drivers/postgres.ts +55 -5
- package/backend/db-client/drivers/sql-builders.test.ts +70 -0
- package/backend/db-client/drivers/sql-builders.ts +9 -2
- package/backend/db-client/pool-config.ts +32 -0
- package/backend/db-client/query-executor.test.ts +42 -0
- package/backend/db-client/query-executor.ts +47 -3
- package/backend/engine/adapters/opencode/config.ts +9 -0
- package/backend/engine/adapters/opencode/models.ts +10 -1
- package/backend/engine/adapters/opencode/server.ts +110 -2
- package/backend/index.ts +6 -0
- package/backend/preview/browser/browser-preview-service.ts +15 -6
- package/backend/preview/browser/browser-video-capture.ts +232 -100
- package/backend/preview/browser/scripts/video-stream.ts +216 -56
- package/backend/preview/browser/types.ts +24 -12
- package/backend/ws/chat/stream.ts +12 -4
- package/backend/ws/db-client/connections.ts +2 -1
- package/backend/ws/db-client/query.ts +41 -4
- package/backend/ws/db-client/schema.ts +45 -1
- package/backend/ws/engine/claude/accounts.ts +37 -13
- package/backend/ws/engine/codex/accounts.ts +36 -4
- package/backend/ws/engine/copilot/accounts.ts +12 -0
- package/backend/ws/engine/opencode/providers.ts +72 -1
- package/backend/ws/engine/qwen/accounts.ts +22 -0
- package/backend/ws/messages/crud.ts +13 -0
- package/backend/ws/preview/browser/interact.ts +10 -8
- package/backend/ws/preview/browser/webcodecs.ts +26 -2
- package/dist/assets/{index-BWf-DDJN.js → index-ChF_jIXj.js} +1 -1
- package/dist/assets/{index-CDZf6lfv.js → index-EunAFLxP.js} +1 -1
- package/dist/assets/{main-C15mQTCW.js → main-CTs4NXwP.js} +407 -367
- package/dist/assets/main-moCAkEwm.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +5 -1
- package/shared/types/db-client/connection.ts +1 -1
- package/shared/types/db-client/query.ts +4 -1
- package/shared/utils/db-client/split-sql.test.ts +13 -0
- package/shared/utils/db-client/split-sql.ts +38 -1
- package/shared/utils/subagent-wire-trim.ts +87 -0
- package/dist/assets/main-Ba5ZGlY4.css +0 -1
|
@@ -0,0 +1,829 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MS SQL Server adapter using the 'mssql' npm library.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import sql from 'mssql';
|
|
6
|
+
import type {
|
|
7
|
+
DbClientConnection,
|
|
8
|
+
DbClientHealth,
|
|
9
|
+
DbClientObjectColumn,
|
|
10
|
+
DbClientObjectDetails,
|
|
11
|
+
DbClientObjectForeignKey,
|
|
12
|
+
DbClientObjectIndex,
|
|
13
|
+
DbClientOverview,
|
|
14
|
+
DbClientQueryResult,
|
|
15
|
+
DbClientSchemaNode,
|
|
16
|
+
DbClientSchemaNodeType,
|
|
17
|
+
DbClientBatchResult,
|
|
18
|
+
DbClientStatementResult
|
|
19
|
+
} from '$shared/types/db-client';
|
|
20
|
+
import type {
|
|
21
|
+
AlterOperation,
|
|
22
|
+
DbClientDriverAdapter,
|
|
23
|
+
DbClientTxContext,
|
|
24
|
+
IndexDefinition,
|
|
25
|
+
SchemaOpts,
|
|
26
|
+
TableDefinition
|
|
27
|
+
} from './types';
|
|
28
|
+
import {
|
|
29
|
+
assertSafeIdentifier,
|
|
30
|
+
buildDelete,
|
|
31
|
+
buildInsert,
|
|
32
|
+
buildUpdate,
|
|
33
|
+
qualified,
|
|
34
|
+
quoteMssql,
|
|
35
|
+
renderColumn,
|
|
36
|
+
renderCreateIndex,
|
|
37
|
+
renderCreateTable
|
|
38
|
+
} from './sql-builders';
|
|
39
|
+
import { POOL_MAX, POOL_IDLE_TIMEOUT_SEC } from '../pool-config';
|
|
40
|
+
|
|
41
|
+
const Q = quoteMssql;
|
|
42
|
+
|
|
43
|
+
function isBatchSensitive(q: string): boolean {
|
|
44
|
+
let clean = q.trim();
|
|
45
|
+
while (true) {
|
|
46
|
+
if (clean.startsWith('--')) {
|
|
47
|
+
const idx = clean.indexOf('\n');
|
|
48
|
+
if (idx === -1) {
|
|
49
|
+
clean = '';
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
clean = clean.slice(idx + 1).trim();
|
|
53
|
+
} else if (clean.startsWith('/*')) {
|
|
54
|
+
const idx = clean.indexOf('*/');
|
|
55
|
+
if (idx === -1) {
|
|
56
|
+
clean = '';
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
clean = clean.slice(idx + 2).trim();
|
|
60
|
+
} else {
|
|
61
|
+
break;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const match = clean.match(/^(create|alter)\s+(procedure|proc|function|view|trigger|schema|queue|default|rule|partition)\b/i);
|
|
65
|
+
return !!match;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class MssqlAdapter implements DbClientDriverAdapter {
|
|
69
|
+
readonly kind = 'mssql' as const;
|
|
70
|
+
|
|
71
|
+
private pool: sql.ConnectionPool | null = null;
|
|
72
|
+
private alive = false;
|
|
73
|
+
private conn: DbClientConnection | null = null;
|
|
74
|
+
|
|
75
|
+
async connect(conn: DbClientConnection, tunnelPort?: number): Promise<void> {
|
|
76
|
+
const host = tunnelPort ? '127.0.0.1' : (conn.host ?? '127.0.0.1');
|
|
77
|
+
const port = tunnelPort ?? conn.port ?? 1433;
|
|
78
|
+
|
|
79
|
+
const sslMode = conn.sslMode ?? 'disable';
|
|
80
|
+
const encrypt = sslMode !== 'disable';
|
|
81
|
+
// Only skip certificate validation for the non-verifying modes. In
|
|
82
|
+
// `verify-ca`/`verify-full` the user explicitly asked us to validate the
|
|
83
|
+
// server certificate, so trusting any cert there would be an MITM hole.
|
|
84
|
+
const trustServerCertificate = sslMode !== 'verify-ca' && sslMode !== 'verify-full';
|
|
85
|
+
|
|
86
|
+
const config: sql.config = {
|
|
87
|
+
server: host,
|
|
88
|
+
port: port,
|
|
89
|
+
user: conn.username ?? undefined,
|
|
90
|
+
password: conn.password ?? undefined,
|
|
91
|
+
database: conn.database ?? undefined,
|
|
92
|
+
options: {
|
|
93
|
+
encrypt,
|
|
94
|
+
trustServerCertificate,
|
|
95
|
+
enableArithAbort: true
|
|
96
|
+
},
|
|
97
|
+
pool: {
|
|
98
|
+
max: POOL_MAX,
|
|
99
|
+
min: 0,
|
|
100
|
+
idleTimeoutMillis: POOL_IDLE_TIMEOUT_SEC * 1000
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
this.pool = new sql.ConnectionPool(config);
|
|
105
|
+
await this.pool.connect();
|
|
106
|
+
this.conn = conn;
|
|
107
|
+
this.alive = true;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async close(): Promise<void> {
|
|
111
|
+
this.alive = false;
|
|
112
|
+
if (this.pool) {
|
|
113
|
+
await this.pool.close();
|
|
114
|
+
this.pool = null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
isAlive(): boolean {
|
|
119
|
+
return this.alive && this.pool !== null && this.pool.connected;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private requirePool(): sql.ConnectionPool {
|
|
123
|
+
if (!this.pool || !this.pool.connected) {
|
|
124
|
+
throw new Error('SQL Server not connected');
|
|
125
|
+
}
|
|
126
|
+
return this.pool;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async health(): Promise<DbClientHealth> {
|
|
130
|
+
if (!this.pool) return notConnected();
|
|
131
|
+
const start = performance.now();
|
|
132
|
+
try {
|
|
133
|
+
const request = this.pool.request();
|
|
134
|
+
const res = await request.query('SELECT @@VERSION AS version');
|
|
135
|
+
const version = res.recordset[0]?.version ?? null;
|
|
136
|
+
return {
|
|
137
|
+
ok: true,
|
|
138
|
+
latencyMs: Math.round(performance.now() - start),
|
|
139
|
+
serverVersion: version,
|
|
140
|
+
sshOk: null,
|
|
141
|
+
error: null
|
|
142
|
+
};
|
|
143
|
+
} catch (err) {
|
|
144
|
+
return {
|
|
145
|
+
ok: false,
|
|
146
|
+
latencyMs: null,
|
|
147
|
+
serverVersion: null,
|
|
148
|
+
sshOk: null,
|
|
149
|
+
error: err instanceof Error ? err.message : String(err)
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Bind positional params as @p0, @p1, … on an mssql request. */
|
|
155
|
+
private bindParams(request: sql.Request, params: unknown[]): void {
|
|
156
|
+
if (params && params.length > 0) {
|
|
157
|
+
params.forEach((val, idx) => {
|
|
158
|
+
request.input(`p${idx}`, val);
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Map a raw mssql result into a DbClientQueryResult, attaching a per-statement
|
|
164
|
+
* `batch` report when the query produced multiple recordsets. */
|
|
165
|
+
private buildResult(result: sql.IResult<any>, q: string, durationMs: number): DbClientQueryResult {
|
|
166
|
+
const toColumns = (rows: any[]) => rows.length > 0
|
|
167
|
+
? Object.keys(rows[0]).map((name) => ({ name, type: null as string | null }))
|
|
168
|
+
: [];
|
|
169
|
+
|
|
170
|
+
const recordsets = result.recordsets as any[] | undefined;
|
|
171
|
+
if (recordsets && recordsets.length > 1) {
|
|
172
|
+
const candidateSplit = q.split(/;|\n\s*\n/).map(s => s.trim()).filter(Boolean);
|
|
173
|
+
const hasMatchingSplit = candidateSplit.length === recordsets.length;
|
|
174
|
+
const statements: DbClientStatementResult[] = recordsets.map((recordset: any, idx: number) => ({
|
|
175
|
+
index: idx,
|
|
176
|
+
query: hasMatchingSplit ? candidateSplit[idx] : `Statement ${idx + 1}`,
|
|
177
|
+
queryClass: 'read' as const,
|
|
178
|
+
status: 'success' as const,
|
|
179
|
+
result: {
|
|
180
|
+
columns: toColumns(recordset),
|
|
181
|
+
rows: recordset,
|
|
182
|
+
rowCount: recordset.length,
|
|
183
|
+
affectedRows: result.rowsAffected ? (result.rowsAffected[idx] ?? null) : null,
|
|
184
|
+
durationMs: 0,
|
|
185
|
+
driverMeta: {}
|
|
186
|
+
},
|
|
187
|
+
error: null,
|
|
188
|
+
durationMs: 0
|
|
189
|
+
}));
|
|
190
|
+
const batchResult: DbClientBatchResult = {
|
|
191
|
+
statements,
|
|
192
|
+
totalDurationMs: durationMs,
|
|
193
|
+
transaction: false,
|
|
194
|
+
ok: true
|
|
195
|
+
};
|
|
196
|
+
return {
|
|
197
|
+
columns: statements[0].result?.columns ?? [],
|
|
198
|
+
rows: recordsets[0] || [],
|
|
199
|
+
rowCount: recordsets[0]?.length ?? 0,
|
|
200
|
+
affectedRows: result.rowsAffected ? (result.rowsAffected[0] ?? null) : null,
|
|
201
|
+
durationMs,
|
|
202
|
+
driverMeta: {},
|
|
203
|
+
batch: batchResult
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const rows = result.recordset || [];
|
|
208
|
+
return {
|
|
209
|
+
columns: toColumns(rows),
|
|
210
|
+
rows,
|
|
211
|
+
rowCount: rows.length,
|
|
212
|
+
affectedRows: result.rowsAffected ? result.rowsAffected[0] : null,
|
|
213
|
+
durationMs,
|
|
214
|
+
driverMeta: {}
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async executeRead(q: string, params: unknown[] = [], opts?: { database?: string; limit?: number }): Promise<DbClientQueryResult> {
|
|
219
|
+
const pool = this.requirePool();
|
|
220
|
+
const start = performance.now();
|
|
221
|
+
const needUse = opts?.database && opts.database.toLowerCase() !== this.conn?.database?.toLowerCase();
|
|
222
|
+
|
|
223
|
+
if (needUse && isBatchSensitive(q)) {
|
|
224
|
+
// Batch-sensitive DDL (CREATE PROCEDURE, …) can't share a batch with
|
|
225
|
+
// `USE`, so run the database switch as a separate request first, wrapped
|
|
226
|
+
// in a transaction for atomicity.
|
|
227
|
+
const transaction = new sql.Transaction(pool);
|
|
228
|
+
await transaction.begin();
|
|
229
|
+
try {
|
|
230
|
+
const useRequest = new sql.Request(transaction);
|
|
231
|
+
await useRequest.query(`USE ${Q(opts!.database as string)}`);
|
|
232
|
+
|
|
233
|
+
const request = new sql.Request(transaction);
|
|
234
|
+
this.bindParams(request, params);
|
|
235
|
+
const result = await request.query(q);
|
|
236
|
+
await transaction.commit();
|
|
237
|
+
return this.buildResult(result, q, Math.round(performance.now() - start));
|
|
238
|
+
} catch (err) {
|
|
239
|
+
try {
|
|
240
|
+
await transaction.rollback();
|
|
241
|
+
} catch {
|
|
242
|
+
// Ignore rollback failures to avoid swallowing the original error
|
|
243
|
+
}
|
|
244
|
+
throw err;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const request = pool.request();
|
|
249
|
+
this.bindParams(request, params);
|
|
250
|
+
const finalQuery = needUse ? `USE ${Q(opts!.database as string)};\n${q}` : q;
|
|
251
|
+
const result = await request.query(finalQuery);
|
|
252
|
+
return this.buildResult(result, q, Math.round(performance.now() - start));
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async executeWrite(q: string, params: unknown[] = [], opts?: { database?: string }): Promise<DbClientQueryResult> {
|
|
256
|
+
return this.executeRead(q, params, opts);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async withTransaction<T>(
|
|
260
|
+
fn: (tx: DbClientTxContext) => Promise<T>,
|
|
261
|
+
opts?: { database?: string }
|
|
262
|
+
): Promise<T> {
|
|
263
|
+
const pool = this.requirePool();
|
|
264
|
+
const transaction = new sql.Transaction(pool);
|
|
265
|
+
await transaction.begin();
|
|
266
|
+
|
|
267
|
+
const txDb = opts?.database;
|
|
268
|
+
|
|
269
|
+
try {
|
|
270
|
+
const txContext: DbClientTxContext = {
|
|
271
|
+
executeRead: async (q, params, txOpts) => {
|
|
272
|
+
const db = txOpts?.database || txDb;
|
|
273
|
+
const needUse = db && db.toLowerCase() !== this.conn?.database?.toLowerCase();
|
|
274
|
+
if (needUse) {
|
|
275
|
+
const useRequest = new sql.Request(transaction);
|
|
276
|
+
await useRequest.query(`USE ${Q(db as string)}`);
|
|
277
|
+
}
|
|
278
|
+
const request = new sql.Request(transaction);
|
|
279
|
+
this.bindParams(request, params ?? []);
|
|
280
|
+
const start = performance.now();
|
|
281
|
+
const result = await request.query(q);
|
|
282
|
+
const durationMs = Math.round(performance.now() - start);
|
|
283
|
+
const rows = result.recordset || [];
|
|
284
|
+
const columns = rows.length > 0
|
|
285
|
+
? Object.keys(rows[0]).map((name) => ({ name, type: null as string | null }))
|
|
286
|
+
: [];
|
|
287
|
+
return {
|
|
288
|
+
columns,
|
|
289
|
+
rows,
|
|
290
|
+
rowCount: rows.length,
|
|
291
|
+
affectedRows: result.rowsAffected ? result.rowsAffected[0] : null,
|
|
292
|
+
durationMs,
|
|
293
|
+
driverMeta: {}
|
|
294
|
+
};
|
|
295
|
+
},
|
|
296
|
+
executeWrite: async (q, params, txOpts) => {
|
|
297
|
+
const db = txOpts?.database || txDb;
|
|
298
|
+
const needUse = db && db.toLowerCase() !== this.conn?.database?.toLowerCase();
|
|
299
|
+
if (needUse) {
|
|
300
|
+
const useRequest = new sql.Request(transaction);
|
|
301
|
+
await useRequest.query(`USE ${Q(db as string)}`);
|
|
302
|
+
}
|
|
303
|
+
const request = new sql.Request(transaction);
|
|
304
|
+
this.bindParams(request, params ?? []);
|
|
305
|
+
const start = performance.now();
|
|
306
|
+
const result = await request.query(q);
|
|
307
|
+
const durationMs = Math.round(performance.now() - start);
|
|
308
|
+
return {
|
|
309
|
+
columns: [],
|
|
310
|
+
rows: [],
|
|
311
|
+
rowCount: 0,
|
|
312
|
+
affectedRows: result.rowsAffected ? result.rowsAffected[0] : null,
|
|
313
|
+
durationMs,
|
|
314
|
+
driverMeta: {}
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
const out = await fn(txContext);
|
|
320
|
+
await transaction.commit();
|
|
321
|
+
return out;
|
|
322
|
+
} catch (err) {
|
|
323
|
+
try {
|
|
324
|
+
await transaction.rollback();
|
|
325
|
+
} catch {
|
|
326
|
+
// Ignore rollback failures
|
|
327
|
+
}
|
|
328
|
+
throw err;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// ── Overview ──────────────────────────────────────────────────────────
|
|
333
|
+
|
|
334
|
+
async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
|
|
335
|
+
const pool = this.requirePool();
|
|
336
|
+
const start = performance.now();
|
|
337
|
+
const db = opts?.database || this.conn?.database || 'master';
|
|
338
|
+
|
|
339
|
+
const health = await this.health();
|
|
340
|
+
const latencyMs = Math.round(performance.now() - start);
|
|
341
|
+
|
|
342
|
+
// Size overview
|
|
343
|
+
const sizeRes = await this.executeRead(`
|
|
344
|
+
SELECT SUM(CAST(size AS BIGINT) * 8 * 1024) AS size_bytes
|
|
345
|
+
FROM sys.master_files
|
|
346
|
+
WHERE database_id = DB_ID(@p0)
|
|
347
|
+
`, [db]);
|
|
348
|
+
const sizeBytes = Number(sizeRes.rows[0]?.size_bytes ?? 0);
|
|
349
|
+
|
|
350
|
+
// Tables and views count
|
|
351
|
+
const tablesRes = await this.executeRead(`
|
|
352
|
+
SELECT COUNT(*) AS tables_count
|
|
353
|
+
FROM sys.tables
|
|
354
|
+
`);
|
|
355
|
+
const viewsRes = await this.executeRead(`
|
|
356
|
+
SELECT COUNT(*) AS views_count
|
|
357
|
+
FROM sys.views
|
|
358
|
+
`);
|
|
359
|
+
|
|
360
|
+
return {
|
|
361
|
+
serverVersion: health.serverVersion,
|
|
362
|
+
latencyMs,
|
|
363
|
+
sizeBytes,
|
|
364
|
+
tableCount: Number(tablesRes.rows[0]?.tables_count ?? 0),
|
|
365
|
+
viewCount: Number(viewsRes.rows[0]?.views_count ?? 0),
|
|
366
|
+
extra: [
|
|
367
|
+
{ label: 'Database', value: db }
|
|
368
|
+
]
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// ── Schema ────────────────────────────────────────────────────────────
|
|
373
|
+
|
|
374
|
+
async listDatabases(): Promise<DbClientSchemaNode[]> {
|
|
375
|
+
const res = await this.executeRead(`
|
|
376
|
+
SELECT name
|
|
377
|
+
FROM sys.databases
|
|
378
|
+
WHERE state = 0 AND name NOT IN ('master', 'tempdb', 'model', 'msdb')
|
|
379
|
+
ORDER BY name
|
|
380
|
+
`);
|
|
381
|
+
return res.rows.map((r) => ({
|
|
382
|
+
name: String(r.name),
|
|
383
|
+
type: 'database' as const
|
|
384
|
+
}));
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async listSchemas(database?: string): Promise<DbClientSchemaNode[]> {
|
|
388
|
+
const dbPrefix = database ? `${Q(database)}.` : '';
|
|
389
|
+
const res = await this.executeRead(`
|
|
390
|
+
SELECT name FROM ${dbPrefix}sys.schemas
|
|
391
|
+
WHERE name NOT IN ('sys', 'INFORMATION_SCHEMA')
|
|
392
|
+
ORDER BY name
|
|
393
|
+
`);
|
|
394
|
+
return res.rows.map((r) => ({
|
|
395
|
+
name: String(r.name),
|
|
396
|
+
type: 'schema' as const
|
|
397
|
+
}));
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async listObjects(database?: string, schema?: string): Promise<DbClientSchemaNode[]> {
|
|
401
|
+
const dbPrefix = database ? `${Q(database)}.` : '';
|
|
402
|
+
const schemaName = schema || 'dbo';
|
|
403
|
+
const res = await this.executeRead(`
|
|
404
|
+
SELECT t.name, t.type_desc
|
|
405
|
+
FROM ${dbPrefix}sys.objects t
|
|
406
|
+
INNER JOIN ${dbPrefix}sys.schemas s ON t.schema_id = s.schema_id
|
|
407
|
+
WHERE t.type IN ('U', 'V', 'P', 'FN', 'TF', 'IF') AND s.name = @p0
|
|
408
|
+
ORDER BY t.name
|
|
409
|
+
`, [schemaName]);
|
|
410
|
+
|
|
411
|
+
return res.rows.map((r) => {
|
|
412
|
+
const typeDesc = String(r.type_desc);
|
|
413
|
+
let type: DbClientSchemaNodeType = 'table';
|
|
414
|
+
if (typeDesc === 'VIEW') {
|
|
415
|
+
type = 'view';
|
|
416
|
+
} else if (typeDesc === 'SQL_STORED_PROCEDURE') {
|
|
417
|
+
type = 'procedure';
|
|
418
|
+
} else if (
|
|
419
|
+
typeDesc === 'SQL_SCALAR_FUNCTION' ||
|
|
420
|
+
typeDesc === 'SQL_TABLE_VALUED_FUNCTION' ||
|
|
421
|
+
typeDesc === 'SQL_INLINE_TABLE_VALUED_FUNCTION'
|
|
422
|
+
) {
|
|
423
|
+
type = 'function';
|
|
424
|
+
}
|
|
425
|
+
return {
|
|
426
|
+
name: String(r.name),
|
|
427
|
+
type
|
|
428
|
+
};
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
async getObjectDetails(
|
|
433
|
+
name: string,
|
|
434
|
+
_type: DbClientSchemaNodeType,
|
|
435
|
+
database?: string,
|
|
436
|
+
schema?: string
|
|
437
|
+
): Promise<DbClientObjectDetails> {
|
|
438
|
+
const targetSchema = schema || 'dbo';
|
|
439
|
+
const dbPrefix = database ? `${Q(database)}.` : '';
|
|
440
|
+
|
|
441
|
+
if (_type === 'function' || _type === 'procedure') {
|
|
442
|
+
// Bind the object name as a parameter so an object name containing a
|
|
443
|
+
// quote can't break out of the OBJECT_ID string literal.
|
|
444
|
+
const objectRef = `${dbPrefix}${Q(targetSchema)}.${Q(name)}`;
|
|
445
|
+
const res = await this.executeRead(`
|
|
446
|
+
SELECT definition
|
|
447
|
+
FROM ${dbPrefix}sys.sql_modules
|
|
448
|
+
WHERE object_id = OBJECT_ID(@p0)
|
|
449
|
+
`, [objectRef]);
|
|
450
|
+
const definition = res.rows[0]?.definition ?? '';
|
|
451
|
+
return {
|
|
452
|
+
name,
|
|
453
|
+
type: _type,
|
|
454
|
+
ddl: String(definition)
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// Columns details
|
|
459
|
+
const colQuery = `
|
|
460
|
+
SELECT
|
|
461
|
+
c.COLUMN_NAME,
|
|
462
|
+
c.DATA_TYPE,
|
|
463
|
+
c.IS_NULLABLE,
|
|
464
|
+
c.COLUMN_DEFAULT,
|
|
465
|
+
CASE WHEN pk.COLUMN_NAME IS NOT NULL THEN 1 ELSE 0 END AS IS_PRIMARY,
|
|
466
|
+
CASE WHEN uk.COLUMN_NAME IS NOT NULL THEN 1 ELSE 0 END AS IS_UNIQUE
|
|
467
|
+
FROM ${dbPrefix}INFORMATION_SCHEMA.COLUMNS c
|
|
468
|
+
LEFT JOIN (
|
|
469
|
+
SELECT kcu.COLUMN_NAME, kcu.TABLE_SCHEMA, kcu.TABLE_NAME
|
|
470
|
+
FROM ${dbPrefix}INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
|
|
471
|
+
JOIN ${dbPrefix}INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
|
|
472
|
+
ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
|
|
473
|
+
AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA
|
|
474
|
+
WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
|
|
475
|
+
) pk ON pk.TABLE_SCHEMA = c.TABLE_SCHEMA AND pk.TABLE_NAME = c.TABLE_NAME AND pk.COLUMN_NAME = c.COLUMN_NAME
|
|
476
|
+
LEFT JOIN (
|
|
477
|
+
SELECT kcu.COLUMN_NAME, kcu.TABLE_SCHEMA, kcu.TABLE_NAME
|
|
478
|
+
FROM ${dbPrefix}INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
|
|
479
|
+
JOIN ${dbPrefix}INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
|
|
480
|
+
ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
|
|
481
|
+
AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA
|
|
482
|
+
WHERE tc.CONSTRAINT_TYPE = 'UNIQUE'
|
|
483
|
+
) uk ON uk.TABLE_SCHEMA = c.TABLE_SCHEMA AND uk.TABLE_NAME = c.TABLE_NAME AND uk.COLUMN_NAME = c.COLUMN_NAME
|
|
484
|
+
WHERE c.TABLE_SCHEMA = @p0 AND c.TABLE_NAME = @p1
|
|
485
|
+
ORDER BY c.ORDINAL_POSITION
|
|
486
|
+
`;
|
|
487
|
+
const colRows = await this.executeRead(colQuery, [targetSchema, name]);
|
|
488
|
+
|
|
489
|
+
const columns: DbClientObjectColumn[] = colRows.rows.map((r) => ({
|
|
490
|
+
name: String(r.COLUMN_NAME),
|
|
491
|
+
type: String(r.DATA_TYPE ?? ''),
|
|
492
|
+
nullable: r.IS_NULLABLE === 'YES',
|
|
493
|
+
default: r.COLUMN_DEFAULT === null ? null : String(r.COLUMN_DEFAULT),
|
|
494
|
+
isPrimary: r.IS_PRIMARY === 1,
|
|
495
|
+
isUnique: r.IS_UNIQUE === 1
|
|
496
|
+
}));
|
|
497
|
+
|
|
498
|
+
// Indexes
|
|
499
|
+
const idxQuery = `
|
|
500
|
+
SELECT
|
|
501
|
+
i.name AS index_name,
|
|
502
|
+
c.name AS column_name,
|
|
503
|
+
i.is_unique
|
|
504
|
+
FROM ${dbPrefix}sys.indexes i
|
|
505
|
+
INNER JOIN ${dbPrefix}sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
|
|
506
|
+
INNER JOIN ${dbPrefix}sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
|
|
507
|
+
INNER JOIN ${dbPrefix}sys.tables t ON i.object_id = t.object_id
|
|
508
|
+
INNER JOIN ${dbPrefix}sys.schemas s ON t.schema_id = s.schema_id
|
|
509
|
+
WHERE s.name = @p0 AND t.name = @p1 AND i.name IS NOT NULL
|
|
510
|
+
ORDER BY i.name, ic.key_ordinal
|
|
511
|
+
`;
|
|
512
|
+
const idxRows = await this.executeRead(idxQuery, [targetSchema, name]);
|
|
513
|
+
|
|
514
|
+
const indexes: DbClientObjectIndex[] = [];
|
|
515
|
+
const indexGroups = new Map<string, { columns: string[]; unique: boolean }>();
|
|
516
|
+
for (const r of idxRows.rows) {
|
|
517
|
+
const idxName = String(r.index_name);
|
|
518
|
+
const colName = String(r.column_name);
|
|
519
|
+
const isUnique = r.is_unique === 1 || r.is_unique === true;
|
|
520
|
+
|
|
521
|
+
if (!indexGroups.has(idxName)) {
|
|
522
|
+
indexGroups.set(idxName, { columns: [], unique: isUnique });
|
|
523
|
+
}
|
|
524
|
+
indexGroups.get(idxName)!.columns.push(colName);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
for (const [idxName, val] of indexGroups.entries()) {
|
|
528
|
+
indexes.push({
|
|
529
|
+
name: idxName,
|
|
530
|
+
columns: val.columns,
|
|
531
|
+
unique: val.unique
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// Foreign Keys
|
|
536
|
+
const fkQuery = `
|
|
537
|
+
SELECT
|
|
538
|
+
fk.name AS constraint_name,
|
|
539
|
+
tp.name AS column_name,
|
|
540
|
+
rt.name AS ref_table,
|
|
541
|
+
rp.name AS ref_column
|
|
542
|
+
FROM ${dbPrefix}sys.foreign_keys fk
|
|
543
|
+
INNER JOIN ${dbPrefix}sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id
|
|
544
|
+
INNER JOIN ${dbPrefix}sys.tables t ON fkc.parent_object_id = t.object_id
|
|
545
|
+
INNER JOIN ${dbPrefix}sys.schemas s ON t.schema_id = s.schema_id
|
|
546
|
+
INNER JOIN ${dbPrefix}sys.columns tp ON fkc.parent_object_id = tp.object_id AND fkc.parent_column_id = tp.column_id
|
|
547
|
+
INNER JOIN ${dbPrefix}sys.tables rt ON fkc.referenced_object_id = rt.object_id
|
|
548
|
+
INNER JOIN ${dbPrefix}sys.columns rp ON fkc.referenced_object_id = rp.object_id AND fkc.referenced_column_id = rp.column_id
|
|
549
|
+
WHERE s.name = @p0 AND t.name = @p1
|
|
550
|
+
`;
|
|
551
|
+
const fkRows = await this.executeRead(fkQuery, [targetSchema, name]);
|
|
552
|
+
|
|
553
|
+
const foreignKeys: DbClientObjectForeignKey[] = fkRows.rows.map((r) => ({
|
|
554
|
+
column: String(r.column_name),
|
|
555
|
+
refTable: String(r.ref_table),
|
|
556
|
+
refColumn: String(r.ref_column)
|
|
557
|
+
}));
|
|
558
|
+
|
|
559
|
+
return { name, type: 'table', columns, indexes, foreignKeys };
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// ── Structure ─────────────────────────────────────────────────────────
|
|
563
|
+
|
|
564
|
+
async createDatabase(name: string): Promise<string> {
|
|
565
|
+
assertSafeIdentifier(name);
|
|
566
|
+
const ddl = `CREATE DATABASE ${Q(name)}`;
|
|
567
|
+
await this.executeWrite(ddl);
|
|
568
|
+
return ddl;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
async dropDatabase(name: string): Promise<string> {
|
|
572
|
+
assertSafeIdentifier(name);
|
|
573
|
+
const ddl = `DROP DATABASE ${Q(name)}`;
|
|
574
|
+
await this.executeWrite(ddl);
|
|
575
|
+
return ddl;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
async renameDatabase(name: string, newName: string): Promise<string> {
|
|
579
|
+
assertSafeIdentifier(name);
|
|
580
|
+
assertSafeIdentifier(newName);
|
|
581
|
+
const ddl = `ALTER DATABASE ${Q(name)} MODIFY NAME = ${Q(newName)}`;
|
|
582
|
+
await this.executeWrite(ddl);
|
|
583
|
+
return ddl;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
async resetDatabase(opts?: SchemaOpts): Promise<string> {
|
|
587
|
+
const schema = opts?.schema || 'dbo';
|
|
588
|
+
const dbPrefix = opts?.database ? `${Q(opts.database)}.` : '';
|
|
589
|
+
|
|
590
|
+
const res = await this.executeRead(
|
|
591
|
+
`SELECT TABLE_NAME FROM ${dbPrefix}INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = @p0 AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME`,
|
|
592
|
+
[schema]
|
|
593
|
+
);
|
|
594
|
+
if (res.rows.length === 0) return '-- no tables to empty';
|
|
595
|
+
res.rows.forEach((r) => assertSafeIdentifier(String(r.TABLE_NAME)));
|
|
596
|
+
|
|
597
|
+
const ddls: string[] = [];
|
|
598
|
+
|
|
599
|
+
// Disable constraints
|
|
600
|
+
for (const r of res.rows) {
|
|
601
|
+
const tableName = qualified(Q, [opts?.database, schema, String(r.TABLE_NAME)]);
|
|
602
|
+
ddls.push(`ALTER TABLE ${tableName} NOCHECK CONSTRAINT ALL`);
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// Delete data & reset identity
|
|
606
|
+
for (const r of res.rows) {
|
|
607
|
+
const tableName = qualified(Q, [opts?.database, schema, String(r.TABLE_NAME)]);
|
|
608
|
+
ddls.push(`DELETE FROM ${tableName}`);
|
|
609
|
+
ddls.push(`IF OBJECTPROPERTY(OBJECT_ID('${tableName}'), 'TableHasIdentity') = 1 DBCC CHECKIDENT ('${tableName}', RESEED, 0)`);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// Re-enable constraints
|
|
613
|
+
for (const r of res.rows) {
|
|
614
|
+
const tableName = qualified(Q, [opts?.database, schema, String(r.TABLE_NAME)]);
|
|
615
|
+
ddls.push(`ALTER TABLE ${tableName} CHECK CONSTRAINT ALL`);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
const fullQuery = ddls.join(';\n');
|
|
619
|
+
await this.executeWrite(fullQuery);
|
|
620
|
+
return fullQuery;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
async createTable(definition: TableDefinition, opts?: SchemaOpts): Promise<string> {
|
|
624
|
+
assertSafeIdentifier(definition.name);
|
|
625
|
+
const ddl = renderCreateTable({
|
|
626
|
+
quote: Q,
|
|
627
|
+
definition,
|
|
628
|
+
schema: opts?.schema || 'dbo',
|
|
629
|
+
database: opts?.database,
|
|
630
|
+
driver: 'mssql'
|
|
631
|
+
});
|
|
632
|
+
await this.executeWrite(ddl);
|
|
633
|
+
return ddl;
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
async alterTable(name: string, operations: AlterOperation[], opts?: SchemaOpts): Promise<string> {
|
|
637
|
+
assertSafeIdentifier(name);
|
|
638
|
+
const schema = opts?.schema || 'dbo';
|
|
639
|
+
const fqt = qualified(Q, [opts?.database, schema, name]);
|
|
640
|
+
const ddls: string[] = [];
|
|
641
|
+
|
|
642
|
+
for (const op of operations) {
|
|
643
|
+
switch (op.kind) {
|
|
644
|
+
case 'add-column':
|
|
645
|
+
assertSafeIdentifier(op.column.name);
|
|
646
|
+
ddls.push(`ALTER TABLE ${fqt} ADD ${renderColumn({ quote: Q, column: op.column, driver: 'mssql' })}`);
|
|
647
|
+
break;
|
|
648
|
+
case 'drop-column':
|
|
649
|
+
assertSafeIdentifier(op.name);
|
|
650
|
+
ddls.push(`ALTER TABLE ${fqt} DROP COLUMN ${Q(op.name)}`);
|
|
651
|
+
break;
|
|
652
|
+
case 'rename-column':
|
|
653
|
+
assertSafeIdentifier(op.name);
|
|
654
|
+
assertSafeIdentifier(op.newName);
|
|
655
|
+
const objectPath = `${schema}.${name}.${op.name}`;
|
|
656
|
+
ddls.push(`EXEC sp_rename '${objectPath}', '${op.newName}', 'COLUMN'`);
|
|
657
|
+
break;
|
|
658
|
+
case 'modify-column':
|
|
659
|
+
assertSafeIdentifier(op.column.name);
|
|
660
|
+
const parts = [Q(op.column.name), op.column.type];
|
|
661
|
+
if (op.column.nullable === false) parts.push('NOT NULL');
|
|
662
|
+
else parts.push('NULL');
|
|
663
|
+
ddls.push(`ALTER TABLE ${fqt} ALTER COLUMN ${parts.join(' ')}`);
|
|
664
|
+
break;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const fullQuery = ddls.join(';\n');
|
|
669
|
+
await this.executeWrite(fullQuery);
|
|
670
|
+
return fullQuery;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
async dropTable(name: string, opts?: SchemaOpts): Promise<string> {
|
|
674
|
+
assertSafeIdentifier(name);
|
|
675
|
+
const ddl = `DROP TABLE ${qualified(Q, [opts?.database, opts?.schema || 'dbo', name])}`;
|
|
676
|
+
await this.executeWrite(ddl);
|
|
677
|
+
return ddl;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
async truncateTable(name: string, opts?: SchemaOpts): Promise<string> {
|
|
681
|
+
assertSafeIdentifier(name);
|
|
682
|
+
const ddl = `TRUNCATE TABLE ${qualified(Q, [opts?.database, opts?.schema || 'dbo', name])}`;
|
|
683
|
+
await this.executeWrite(ddl);
|
|
684
|
+
return ddl;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
async resetTable(name: string, opts?: SchemaOpts): Promise<string> {
|
|
688
|
+
// TRUNCATE TABLE resets identity naturally in SQL Server
|
|
689
|
+
return this.truncateTable(name, opts);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
async renameTable(name: string, newName: string, opts?: SchemaOpts): Promise<string> {
|
|
693
|
+
assertSafeIdentifier(name);
|
|
694
|
+
assertSafeIdentifier(newName);
|
|
695
|
+
const schema = opts?.schema || 'dbo';
|
|
696
|
+
const objectPath = `${schema}.${name}`;
|
|
697
|
+
const ddl = `EXEC sp_rename '${objectPath}', '${newName}'`;
|
|
698
|
+
await this.executeWrite(ddl);
|
|
699
|
+
return ddl;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
async duplicateTable(name: string, newName: string, opts?: SchemaOpts & { withData?: boolean }): Promise<string> {
|
|
703
|
+
assertSafeIdentifier(name);
|
|
704
|
+
assertSafeIdentifier(newName);
|
|
705
|
+
const schema = opts?.schema || 'dbo';
|
|
706
|
+
const source = qualified(Q, [opts?.database, schema, name]);
|
|
707
|
+
const target = qualified(Q, [opts?.database, schema, newName]);
|
|
708
|
+
const where = opts?.withData ? '' : ' WHERE 1 = 0';
|
|
709
|
+
const ddl = `SELECT * INTO ${target} FROM ${source}${where}`;
|
|
710
|
+
await this.executeWrite(ddl);
|
|
711
|
+
return ddl;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
async getCreateStatement(name: string, type: DbClientSchemaNodeType, opts?: SchemaOpts): Promise<string> {
|
|
715
|
+
const details = await this.getObjectDetails(name, type, opts?.database, opts?.schema);
|
|
716
|
+
const schema = opts?.schema || 'dbo';
|
|
717
|
+
const detailColumns = details.columns ?? [];
|
|
718
|
+
const cols = detailColumns.map((c) => {
|
|
719
|
+
const parts = [Q(c.name), c.type];
|
|
720
|
+
if (!c.nullable) parts.push('NOT NULL');
|
|
721
|
+
if (c.default !== null && c.default !== undefined && c.default !== '') parts.push(`DEFAULT ${c.default}`);
|
|
722
|
+
return ` ${parts.join(' ')}`;
|
|
723
|
+
});
|
|
724
|
+
const pk = detailColumns.filter((c) => c.isPrimary).map((c) => Q(c.name));
|
|
725
|
+
if (pk.length > 0) cols.push(` PRIMARY KEY (${pk.join(', ')})`);
|
|
726
|
+
const lines = [`CREATE TABLE ${qualified(Q, [opts?.database, schema, name])} (`, cols.join(',\n'), ');'];
|
|
727
|
+
return lines.join('\n');
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
async createIndex(tableName: string, def: IndexDefinition, opts?: SchemaOpts): Promise<string> {
|
|
731
|
+
assertSafeIdentifier(tableName);
|
|
732
|
+
assertSafeIdentifier(def.name);
|
|
733
|
+
def.columns.forEach(assertSafeIdentifier);
|
|
734
|
+
const ddl = renderCreateIndex({
|
|
735
|
+
quote: Q,
|
|
736
|
+
tableName,
|
|
737
|
+
def,
|
|
738
|
+
schema: opts?.schema || 'dbo',
|
|
739
|
+
database: opts?.database
|
|
740
|
+
});
|
|
741
|
+
await this.executeWrite(ddl);
|
|
742
|
+
return ddl;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
async dropIndex(tableName: string, indexName: string, opts?: SchemaOpts): Promise<string> {
|
|
746
|
+
assertSafeIdentifier(tableName);
|
|
747
|
+
assertSafeIdentifier(indexName);
|
|
748
|
+
const fqt = qualified(Q, [opts?.database, opts?.schema || 'dbo', tableName]);
|
|
749
|
+
const ddl = `DROP INDEX ${Q(indexName)} ON ${fqt}`;
|
|
750
|
+
await this.executeWrite(ddl);
|
|
751
|
+
return ddl;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
async createView(name: string, query: string, opts?: SchemaOpts): Promise<string> {
|
|
755
|
+
assertSafeIdentifier(name);
|
|
756
|
+
const fqt = qualified(Q, [opts?.database, opts?.schema || 'dbo', name]);
|
|
757
|
+
const ddl = `CREATE VIEW ${fqt} AS ${query}`;
|
|
758
|
+
await this.executeWrite(ddl);
|
|
759
|
+
return ddl;
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
async dropView(name: string, opts?: SchemaOpts): Promise<string> {
|
|
763
|
+
assertSafeIdentifier(name);
|
|
764
|
+
const fqt = qualified(Q, [opts?.database, opts?.schema || 'dbo', name]);
|
|
765
|
+
const ddl = `DROP VIEW ${fqt}`;
|
|
766
|
+
await this.executeWrite(ddl);
|
|
767
|
+
return ddl;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
// ── Data CRUD ─────────────────────────────────────────────────────────
|
|
771
|
+
|
|
772
|
+
async insertRow(table: string, row: Record<string, unknown>, opts?: SchemaOpts): Promise<DbClientQueryResult> {
|
|
773
|
+
assertSafeIdentifier(table);
|
|
774
|
+
Object.keys(row).forEach(assertSafeIdentifier);
|
|
775
|
+
const { sql: query, params } = buildInsert({
|
|
776
|
+
quote: Q,
|
|
777
|
+
table,
|
|
778
|
+
row,
|
|
779
|
+
schema: opts?.schema || 'dbo',
|
|
780
|
+
database: opts?.database,
|
|
781
|
+
placeholder: (i) => `@p${i}`
|
|
782
|
+
});
|
|
783
|
+
return this.executeWrite(query, params);
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
async updateRow(
|
|
787
|
+
table: string,
|
|
788
|
+
pk: Record<string, unknown>,
|
|
789
|
+
changes: Record<string, unknown>,
|
|
790
|
+
opts?: SchemaOpts
|
|
791
|
+
): Promise<DbClientQueryResult> {
|
|
792
|
+
assertSafeIdentifier(table);
|
|
793
|
+
[...Object.keys(pk), ...Object.keys(changes)].forEach(assertSafeIdentifier);
|
|
794
|
+
const { sql: query, params } = buildUpdate({
|
|
795
|
+
quote: Q,
|
|
796
|
+
table,
|
|
797
|
+
pk,
|
|
798
|
+
changes,
|
|
799
|
+
schema: opts?.schema || 'dbo',
|
|
800
|
+
database: opts?.database,
|
|
801
|
+
placeholder: (i) => `@p${i}`
|
|
802
|
+
});
|
|
803
|
+
return this.executeWrite(query, params);
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
async deleteRows(table: string, pks: Record<string, unknown>[], opts?: SchemaOpts): Promise<DbClientQueryResult> {
|
|
807
|
+
assertSafeIdentifier(table);
|
|
808
|
+
if (pks.length > 0) Object.keys(pks[0]).forEach(assertSafeIdentifier);
|
|
809
|
+
const { sql: query, params } = buildDelete({
|
|
810
|
+
quote: Q,
|
|
811
|
+
table,
|
|
812
|
+
pks,
|
|
813
|
+
schema: opts?.schema || 'dbo',
|
|
814
|
+
database: opts?.database,
|
|
815
|
+
placeholder: (i) => `@p${i}`
|
|
816
|
+
});
|
|
817
|
+
return this.executeWrite(query, params);
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function notConnected(): DbClientHealth {
|
|
822
|
+
return {
|
|
823
|
+
ok: false,
|
|
824
|
+
latencyMs: null,
|
|
825
|
+
serverVersion: null,
|
|
826
|
+
sshOk: null,
|
|
827
|
+
error: 'Not connected'
|
|
828
|
+
};
|
|
829
|
+
}
|