@bytebase/dbhub 0.19.1 → 0.21.0
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/dist/chunk-BRXZ5ZQB.js +127 -0
- package/dist/chunk-C7WEAPX4.js +485 -0
- package/dist/{chunk-LUNM7TUY.js → chunk-GRGEI5QT.js} +24 -476
- package/dist/chunk-JFWX35TB.js +34 -0
- package/dist/chunk-RTB262PR.js +60 -0
- package/dist/index.js +79 -2377
- package/dist/mariadb-VGTS4WXE.js +462 -0
- package/dist/mysql-I35IQ2GH.js +469 -0
- package/dist/postgres-B7YSSZMH.js +480 -0
- package/dist/{registry-6VNMKD6G.js → registry-XSMMLRC4.js} +2 -1
- package/dist/sqlite-FSCLCRIH.js +320 -0
- package/dist/sqlserver-FDBRUELV.js +479 -0
- package/package.json +8 -6
package/dist/index.js
CHANGED
|
@@ -3,2370 +3,27 @@ import {
|
|
|
3
3
|
BUILTIN_TOOL_EXECUTE_SQL,
|
|
4
4
|
BUILTIN_TOOL_SEARCH_OBJECTS,
|
|
5
5
|
ConnectorManager,
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
// src/utils/sql-row-limiter.ts
|
|
29
|
-
var SQLRowLimiter = class {
|
|
30
|
-
/**
|
|
31
|
-
* Check if a SQL statement is a SELECT query that can benefit from row limiting
|
|
32
|
-
* Only handles SELECT queries
|
|
33
|
-
*/
|
|
34
|
-
static isSelectQuery(sql2) {
|
|
35
|
-
const trimmed = sql2.trim().toLowerCase();
|
|
36
|
-
return trimmed.startsWith("select");
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* Check if a SQL statement already has a LIMIT clause.
|
|
40
|
-
* Strips comments and string literals first to avoid false positives.
|
|
41
|
-
*/
|
|
42
|
-
static hasLimitClause(sql2) {
|
|
43
|
-
const cleanedSQL = stripCommentsAndStrings(sql2);
|
|
44
|
-
const limitRegex = /\blimit\s+(?:\d+|\$\d+|\?|@p\d+)/i;
|
|
45
|
-
return limitRegex.test(cleanedSQL);
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Check if a SQL statement already has a TOP clause (SQL Server).
|
|
49
|
-
* Strips comments and string literals first to avoid false positives.
|
|
50
|
-
*/
|
|
51
|
-
static hasTopClause(sql2) {
|
|
52
|
-
const cleanedSQL = stripCommentsAndStrings(sql2);
|
|
53
|
-
const topRegex = /\bselect\s+top\s+\d+/i;
|
|
54
|
-
return topRegex.test(cleanedSQL);
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
|
-
* Extract existing LIMIT value from SQL if present.
|
|
58
|
-
* Strips comments and string literals first to avoid false positives.
|
|
59
|
-
*/
|
|
60
|
-
static extractLimitValue(sql2) {
|
|
61
|
-
const cleanedSQL = stripCommentsAndStrings(sql2);
|
|
62
|
-
const limitMatch = cleanedSQL.match(/\blimit\s+(\d+)/i);
|
|
63
|
-
if (limitMatch) {
|
|
64
|
-
return parseInt(limitMatch[1], 10);
|
|
65
|
-
}
|
|
66
|
-
return null;
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* Extract existing TOP value from SQL if present (SQL Server).
|
|
70
|
-
* Strips comments and string literals first to avoid false positives.
|
|
71
|
-
*/
|
|
72
|
-
static extractTopValue(sql2) {
|
|
73
|
-
const cleanedSQL = stripCommentsAndStrings(sql2);
|
|
74
|
-
const topMatch = cleanedSQL.match(/\bselect\s+top\s+(\d+)/i);
|
|
75
|
-
if (topMatch) {
|
|
76
|
-
return parseInt(topMatch[1], 10);
|
|
77
|
-
}
|
|
78
|
-
return null;
|
|
79
|
-
}
|
|
80
|
-
/**
|
|
81
|
-
* Add or modify LIMIT clause in a SQL statement
|
|
82
|
-
*/
|
|
83
|
-
static applyLimitToQuery(sql2, maxRows) {
|
|
84
|
-
const existingLimit = this.extractLimitValue(sql2);
|
|
85
|
-
if (existingLimit !== null) {
|
|
86
|
-
const effectiveLimit = Math.min(existingLimit, maxRows);
|
|
87
|
-
return sql2.replace(/\blimit\s+\d+/i, `LIMIT ${effectiveLimit}`);
|
|
88
|
-
} else {
|
|
89
|
-
const trimmed = sql2.trim();
|
|
90
|
-
const hasSemicolon = trimmed.endsWith(";");
|
|
91
|
-
const sqlWithoutSemicolon = hasSemicolon ? trimmed.slice(0, -1) : trimmed;
|
|
92
|
-
return `${sqlWithoutSemicolon} LIMIT ${maxRows}${hasSemicolon ? ";" : ""}`;
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Add or modify TOP clause in a SQL statement (SQL Server)
|
|
97
|
-
*/
|
|
98
|
-
static applyTopToQuery(sql2, maxRows) {
|
|
99
|
-
const existingTop = this.extractTopValue(sql2);
|
|
100
|
-
if (existingTop !== null) {
|
|
101
|
-
const effectiveTop = Math.min(existingTop, maxRows);
|
|
102
|
-
return sql2.replace(/\bselect\s+top\s+\d+/i, `SELECT TOP ${effectiveTop}`);
|
|
103
|
-
} else {
|
|
104
|
-
return sql2.replace(/\bselect\s+/i, `SELECT TOP ${maxRows} `);
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Check if a LIMIT clause uses a parameter placeholder (not a literal number).
|
|
109
|
-
* Strips comments and string literals first to avoid false positives.
|
|
110
|
-
*/
|
|
111
|
-
static hasParameterizedLimit(sql2) {
|
|
112
|
-
const cleanedSQL = stripCommentsAndStrings(sql2);
|
|
113
|
-
const parameterizedLimitRegex = /\blimit\s+(?:\$\d+|\?|@p\d+)/i;
|
|
114
|
-
return parameterizedLimitRegex.test(cleanedSQL);
|
|
115
|
-
}
|
|
116
|
-
/**
|
|
117
|
-
* Apply maxRows limit to a SELECT query only
|
|
118
|
-
*
|
|
119
|
-
* This method is used by PostgreSQL, MySQL, MariaDB, and SQLite connectors which all support
|
|
120
|
-
* the LIMIT clause syntax. SQL Server uses applyMaxRowsForSQLServer() instead with TOP syntax.
|
|
121
|
-
*
|
|
122
|
-
* For parameterized LIMIT clauses (e.g., LIMIT $1 or LIMIT ?), we wrap the query in a subquery
|
|
123
|
-
* to enforce max_rows as a hard cap, since the parameter value is not known until runtime.
|
|
124
|
-
*/
|
|
125
|
-
static applyMaxRows(sql2, maxRows) {
|
|
126
|
-
if (!maxRows || !this.isSelectQuery(sql2)) {
|
|
127
|
-
return sql2;
|
|
128
|
-
}
|
|
129
|
-
if (this.hasParameterizedLimit(sql2)) {
|
|
130
|
-
const trimmed = sql2.trim();
|
|
131
|
-
const hasSemicolon = trimmed.endsWith(";");
|
|
132
|
-
const sqlWithoutSemicolon = hasSemicolon ? trimmed.slice(0, -1) : trimmed;
|
|
133
|
-
return `SELECT * FROM (${sqlWithoutSemicolon}) AS subq LIMIT ${maxRows}${hasSemicolon ? ";" : ""}`;
|
|
134
|
-
}
|
|
135
|
-
return this.applyLimitToQuery(sql2, maxRows);
|
|
136
|
-
}
|
|
137
|
-
/**
|
|
138
|
-
* Apply maxRows limit to a SELECT query using SQL Server TOP syntax
|
|
139
|
-
*/
|
|
140
|
-
static applyMaxRowsForSQLServer(sql2, maxRows) {
|
|
141
|
-
if (!maxRows || !this.isSelectQuery(sql2)) {
|
|
142
|
-
return sql2;
|
|
143
|
-
}
|
|
144
|
-
return this.applyTopToQuery(sql2, maxRows);
|
|
145
|
-
}
|
|
146
|
-
};
|
|
147
|
-
|
|
148
|
-
// src/utils/identifier-quoter.ts
|
|
149
|
-
function quoteIdentifier(identifier, dbType) {
|
|
150
|
-
if (/[\0\x08\x09\x1a\n\r]/.test(identifier)) {
|
|
151
|
-
throw new Error(`Invalid identifier: contains control characters: ${identifier}`);
|
|
152
|
-
}
|
|
153
|
-
if (!identifier) {
|
|
154
|
-
throw new Error("Identifier cannot be empty");
|
|
155
|
-
}
|
|
156
|
-
switch (dbType) {
|
|
157
|
-
case "postgres":
|
|
158
|
-
case "sqlite":
|
|
159
|
-
return `"${identifier.replace(/"/g, '""')}"`;
|
|
160
|
-
case "mysql":
|
|
161
|
-
case "mariadb":
|
|
162
|
-
return `\`${identifier.replace(/`/g, "``")}\``;
|
|
163
|
-
case "sqlserver":
|
|
164
|
-
return `[${identifier.replace(/]/g, "]]")}]`;
|
|
165
|
-
default:
|
|
166
|
-
return `"${identifier.replace(/"/g, '""')}"`;
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
function quoteQualifiedIdentifier(tableName, schemaName, dbType) {
|
|
170
|
-
const quotedTable = quoteIdentifier(tableName, dbType);
|
|
171
|
-
if (schemaName) {
|
|
172
|
-
const quotedSchema = quoteIdentifier(schemaName, dbType);
|
|
173
|
-
return `${quotedSchema}.${quotedTable}`;
|
|
174
|
-
}
|
|
175
|
-
return quotedTable;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
// src/connectors/postgres/index.ts
|
|
179
|
-
var { Pool } = pg;
|
|
180
|
-
var PostgresDSNParser = class {
|
|
181
|
-
async parse(dsn, config) {
|
|
182
|
-
const connectionTimeoutSeconds = config?.connectionTimeoutSeconds;
|
|
183
|
-
const queryTimeoutSeconds = config?.queryTimeoutSeconds;
|
|
184
|
-
if (!this.isValidDSN(dsn)) {
|
|
185
|
-
const obfuscatedDSN = obfuscateDSNPassword(dsn);
|
|
186
|
-
const expectedFormat = this.getSampleDSN();
|
|
187
|
-
throw new Error(
|
|
188
|
-
`Invalid PostgreSQL DSN format.
|
|
189
|
-
Provided: ${obfuscatedDSN}
|
|
190
|
-
Expected: ${expectedFormat}`
|
|
191
|
-
);
|
|
192
|
-
}
|
|
193
|
-
try {
|
|
194
|
-
const url = new SafeURL(dsn);
|
|
195
|
-
const poolConfig = {
|
|
196
|
-
host: url.hostname,
|
|
197
|
-
port: url.port ? parseInt(url.port) : 5432,
|
|
198
|
-
database: url.pathname ? url.pathname.substring(1) : "",
|
|
199
|
-
// Remove leading '/' if exists
|
|
200
|
-
user: url.username,
|
|
201
|
-
password: url.password
|
|
202
|
-
};
|
|
203
|
-
url.forEachSearchParam((value, key) => {
|
|
204
|
-
if (key === "sslmode") {
|
|
205
|
-
if (value === "disable") {
|
|
206
|
-
poolConfig.ssl = false;
|
|
207
|
-
} else if (value === "require") {
|
|
208
|
-
poolConfig.ssl = { rejectUnauthorized: false };
|
|
209
|
-
} else {
|
|
210
|
-
poolConfig.ssl = true;
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
});
|
|
214
|
-
if (connectionTimeoutSeconds !== void 0) {
|
|
215
|
-
poolConfig.connectionTimeoutMillis = connectionTimeoutSeconds * 1e3;
|
|
216
|
-
}
|
|
217
|
-
if (queryTimeoutSeconds !== void 0) {
|
|
218
|
-
poolConfig.query_timeout = queryTimeoutSeconds * 1e3;
|
|
219
|
-
}
|
|
220
|
-
return poolConfig;
|
|
221
|
-
} catch (error) {
|
|
222
|
-
throw new Error(
|
|
223
|
-
`Failed to parse PostgreSQL DSN: ${error instanceof Error ? error.message : String(error)}`
|
|
224
|
-
);
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
getSampleDSN() {
|
|
228
|
-
return "postgres://postgres:password@localhost:5432/postgres?sslmode=require";
|
|
229
|
-
}
|
|
230
|
-
isValidDSN(dsn) {
|
|
231
|
-
try {
|
|
232
|
-
return dsn.startsWith("postgres://") || dsn.startsWith("postgresql://");
|
|
233
|
-
} catch (error) {
|
|
234
|
-
return false;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
};
|
|
238
|
-
var PostgresConnector = class _PostgresConnector {
|
|
239
|
-
constructor() {
|
|
240
|
-
this.id = "postgres";
|
|
241
|
-
this.name = "PostgreSQL";
|
|
242
|
-
this.dsnParser = new PostgresDSNParser();
|
|
243
|
-
this.pool = null;
|
|
244
|
-
// Source ID is set by ConnectorManager after cloning
|
|
245
|
-
this.sourceId = "default";
|
|
246
|
-
// Default schema for discovery methods (first entry from search_path, or "public")
|
|
247
|
-
this.defaultSchema = "public";
|
|
248
|
-
}
|
|
249
|
-
getId() {
|
|
250
|
-
return this.sourceId;
|
|
251
|
-
}
|
|
252
|
-
clone() {
|
|
253
|
-
return new _PostgresConnector();
|
|
254
|
-
}
|
|
255
|
-
async connect(dsn, initScript, config) {
|
|
256
|
-
this.defaultSchema = "public";
|
|
257
|
-
try {
|
|
258
|
-
const poolConfig = await this.dsnParser.parse(dsn, config);
|
|
259
|
-
if (config?.readonly) {
|
|
260
|
-
poolConfig.options = (poolConfig.options || "") + " -c default_transaction_read_only=on";
|
|
261
|
-
}
|
|
262
|
-
if (config?.searchPath) {
|
|
263
|
-
const schemas = config.searchPath.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
|
|
264
|
-
if (schemas.length > 0) {
|
|
265
|
-
this.defaultSchema = schemas[0];
|
|
266
|
-
const quotedSchemas = schemas.map((s) => quoteIdentifier(s, "postgres"));
|
|
267
|
-
const optionsValue = quotedSchemas.join(",").replace(/\\/g, "\\\\").replace(/ /g, "\\ ");
|
|
268
|
-
poolConfig.options = (poolConfig.options || "") + ` -c search_path=${optionsValue}`;
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
this.pool = new Pool(poolConfig);
|
|
272
|
-
const client = await this.pool.connect();
|
|
273
|
-
client.release();
|
|
274
|
-
} catch (err) {
|
|
275
|
-
console.error("Failed to connect to PostgreSQL database:", err);
|
|
276
|
-
throw err;
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
async disconnect() {
|
|
280
|
-
if (this.pool) {
|
|
281
|
-
await this.pool.end();
|
|
282
|
-
this.pool = null;
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
async getSchemas() {
|
|
286
|
-
if (!this.pool) {
|
|
287
|
-
throw new Error("Not connected to database");
|
|
288
|
-
}
|
|
289
|
-
const client = await this.pool.connect();
|
|
290
|
-
try {
|
|
291
|
-
const result = await client.query(`
|
|
292
|
-
SELECT schema_name
|
|
293
|
-
FROM information_schema.schemata
|
|
294
|
-
WHERE schema_name NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
|
|
295
|
-
ORDER BY schema_name
|
|
296
|
-
`);
|
|
297
|
-
return result.rows.map((row) => row.schema_name);
|
|
298
|
-
} finally {
|
|
299
|
-
client.release();
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
async getTables(schema) {
|
|
303
|
-
if (!this.pool) {
|
|
304
|
-
throw new Error("Not connected to database");
|
|
305
|
-
}
|
|
306
|
-
const client = await this.pool.connect();
|
|
307
|
-
try {
|
|
308
|
-
const schemaToUse = schema || this.defaultSchema;
|
|
309
|
-
const result = await client.query(
|
|
310
|
-
`
|
|
311
|
-
SELECT table_name
|
|
312
|
-
FROM information_schema.tables
|
|
313
|
-
WHERE table_schema = $1
|
|
314
|
-
ORDER BY table_name
|
|
315
|
-
`,
|
|
316
|
-
[schemaToUse]
|
|
317
|
-
);
|
|
318
|
-
return result.rows.map((row) => row.table_name);
|
|
319
|
-
} finally {
|
|
320
|
-
client.release();
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
async tableExists(tableName, schema) {
|
|
324
|
-
if (!this.pool) {
|
|
325
|
-
throw new Error("Not connected to database");
|
|
326
|
-
}
|
|
327
|
-
const client = await this.pool.connect();
|
|
328
|
-
try {
|
|
329
|
-
const schemaToUse = schema || this.defaultSchema;
|
|
330
|
-
const result = await client.query(
|
|
331
|
-
`
|
|
332
|
-
SELECT EXISTS (
|
|
333
|
-
SELECT FROM information_schema.tables
|
|
334
|
-
WHERE table_schema = $1
|
|
335
|
-
AND table_name = $2
|
|
336
|
-
)
|
|
337
|
-
`,
|
|
338
|
-
[schemaToUse, tableName]
|
|
339
|
-
);
|
|
340
|
-
return result.rows[0].exists;
|
|
341
|
-
} finally {
|
|
342
|
-
client.release();
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
async getTableIndexes(tableName, schema) {
|
|
346
|
-
if (!this.pool) {
|
|
347
|
-
throw new Error("Not connected to database");
|
|
348
|
-
}
|
|
349
|
-
const client = await this.pool.connect();
|
|
350
|
-
try {
|
|
351
|
-
const schemaToUse = schema || this.defaultSchema;
|
|
352
|
-
const result = await client.query(
|
|
353
|
-
`
|
|
354
|
-
SELECT
|
|
355
|
-
i.relname as index_name,
|
|
356
|
-
array_agg(a.attname) as column_names,
|
|
357
|
-
ix.indisunique as is_unique,
|
|
358
|
-
ix.indisprimary as is_primary
|
|
359
|
-
FROM
|
|
360
|
-
pg_class t,
|
|
361
|
-
pg_class i,
|
|
362
|
-
pg_index ix,
|
|
363
|
-
pg_attribute a,
|
|
364
|
-
pg_namespace ns
|
|
365
|
-
WHERE
|
|
366
|
-
t.oid = ix.indrelid
|
|
367
|
-
AND i.oid = ix.indexrelid
|
|
368
|
-
AND a.attrelid = t.oid
|
|
369
|
-
AND a.attnum = ANY(ix.indkey)
|
|
370
|
-
AND t.relkind = 'r'
|
|
371
|
-
AND t.relname = $1
|
|
372
|
-
AND ns.oid = t.relnamespace
|
|
373
|
-
AND ns.nspname = $2
|
|
374
|
-
GROUP BY
|
|
375
|
-
i.relname,
|
|
376
|
-
ix.indisunique,
|
|
377
|
-
ix.indisprimary
|
|
378
|
-
ORDER BY
|
|
379
|
-
i.relname
|
|
380
|
-
`,
|
|
381
|
-
[tableName, schemaToUse]
|
|
382
|
-
);
|
|
383
|
-
return result.rows.map((row) => ({
|
|
384
|
-
index_name: row.index_name,
|
|
385
|
-
column_names: row.column_names,
|
|
386
|
-
is_unique: row.is_unique,
|
|
387
|
-
is_primary: row.is_primary
|
|
388
|
-
}));
|
|
389
|
-
} finally {
|
|
390
|
-
client.release();
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
async getTableSchema(tableName, schema) {
|
|
394
|
-
if (!this.pool) {
|
|
395
|
-
throw new Error("Not connected to database");
|
|
396
|
-
}
|
|
397
|
-
const client = await this.pool.connect();
|
|
398
|
-
try {
|
|
399
|
-
const schemaToUse = schema || this.defaultSchema;
|
|
400
|
-
const result = await client.query(
|
|
401
|
-
`
|
|
402
|
-
SELECT
|
|
403
|
-
c.column_name,
|
|
404
|
-
c.data_type,
|
|
405
|
-
c.is_nullable,
|
|
406
|
-
c.column_default,
|
|
407
|
-
pgd.description
|
|
408
|
-
FROM information_schema.columns c
|
|
409
|
-
LEFT JOIN pg_catalog.pg_namespace nsp
|
|
410
|
-
ON nsp.nspname = c.table_schema
|
|
411
|
-
LEFT JOIN pg_catalog.pg_class cls
|
|
412
|
-
ON cls.relnamespace = nsp.oid
|
|
413
|
-
AND cls.relname = c.table_name
|
|
414
|
-
LEFT JOIN pg_catalog.pg_description pgd
|
|
415
|
-
ON pgd.objoid = cls.oid
|
|
416
|
-
AND pgd.objsubid = c.ordinal_position
|
|
417
|
-
WHERE c.table_schema = $1
|
|
418
|
-
AND c.table_name = $2
|
|
419
|
-
ORDER BY c.ordinal_position
|
|
420
|
-
`,
|
|
421
|
-
[schemaToUse, tableName]
|
|
422
|
-
);
|
|
423
|
-
return result.rows;
|
|
424
|
-
} finally {
|
|
425
|
-
client.release();
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
async getTableRowCount(tableName, schema) {
|
|
429
|
-
if (!this.pool) {
|
|
430
|
-
throw new Error("Not connected to database");
|
|
431
|
-
}
|
|
432
|
-
const client = await this.pool.connect();
|
|
433
|
-
try {
|
|
434
|
-
const schemaToUse = schema || this.defaultSchema;
|
|
435
|
-
const result = await client.query(
|
|
436
|
-
`
|
|
437
|
-
SELECT c.reltuples::bigint as count
|
|
438
|
-
FROM pg_class c
|
|
439
|
-
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
440
|
-
WHERE c.relname = $1
|
|
441
|
-
AND n.nspname = $2
|
|
442
|
-
AND c.relkind IN ('r','p','m','f')
|
|
443
|
-
`,
|
|
444
|
-
[tableName, schemaToUse]
|
|
445
|
-
);
|
|
446
|
-
if (result.rows.length > 0) {
|
|
447
|
-
const count = Number(result.rows[0].count);
|
|
448
|
-
return count >= 0 ? count : null;
|
|
449
|
-
}
|
|
450
|
-
return null;
|
|
451
|
-
} finally {
|
|
452
|
-
client.release();
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
async getTableComment(tableName, schema) {
|
|
456
|
-
if (!this.pool) {
|
|
457
|
-
throw new Error("Not connected to database");
|
|
458
|
-
}
|
|
459
|
-
const client = await this.pool.connect();
|
|
460
|
-
try {
|
|
461
|
-
const schemaToUse = schema || this.defaultSchema;
|
|
462
|
-
const result = await client.query(
|
|
463
|
-
`
|
|
464
|
-
SELECT obj_description(c.oid) as table_comment
|
|
465
|
-
FROM pg_catalog.pg_class c
|
|
466
|
-
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
467
|
-
WHERE c.relname = $1
|
|
468
|
-
AND n.nspname = $2
|
|
469
|
-
AND c.relkind IN ('r','p','m','f')
|
|
470
|
-
`,
|
|
471
|
-
[tableName, schemaToUse]
|
|
472
|
-
);
|
|
473
|
-
if (result.rows.length > 0) {
|
|
474
|
-
return result.rows[0].table_comment || null;
|
|
475
|
-
}
|
|
476
|
-
return null;
|
|
477
|
-
} finally {
|
|
478
|
-
client.release();
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
async getStoredProcedures(schema, routineType) {
|
|
482
|
-
if (!this.pool) {
|
|
483
|
-
throw new Error("Not connected to database");
|
|
484
|
-
}
|
|
485
|
-
const client = await this.pool.connect();
|
|
486
|
-
try {
|
|
487
|
-
const schemaToUse = schema || this.defaultSchema;
|
|
488
|
-
const params = [schemaToUse];
|
|
489
|
-
let typeFilter = "";
|
|
490
|
-
if (routineType === "function") {
|
|
491
|
-
typeFilter = " AND routine_type = 'FUNCTION'";
|
|
492
|
-
} else if (routineType === "procedure") {
|
|
493
|
-
typeFilter = " AND routine_type = 'PROCEDURE'";
|
|
494
|
-
}
|
|
495
|
-
const result = await client.query(
|
|
496
|
-
`
|
|
497
|
-
SELECT
|
|
498
|
-
routine_name
|
|
499
|
-
FROM information_schema.routines
|
|
500
|
-
WHERE routine_schema = $1${typeFilter}
|
|
501
|
-
ORDER BY routine_name
|
|
502
|
-
`,
|
|
503
|
-
params
|
|
504
|
-
);
|
|
505
|
-
return result.rows.map((row) => row.routine_name);
|
|
506
|
-
} finally {
|
|
507
|
-
client.release();
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
async getStoredProcedureDetail(procedureName, schema) {
|
|
511
|
-
if (!this.pool) {
|
|
512
|
-
throw new Error("Not connected to database");
|
|
513
|
-
}
|
|
514
|
-
const client = await this.pool.connect();
|
|
515
|
-
try {
|
|
516
|
-
const schemaToUse = schema || this.defaultSchema;
|
|
517
|
-
const result = await client.query(
|
|
518
|
-
`
|
|
519
|
-
SELECT
|
|
520
|
-
routine_name as procedure_name,
|
|
521
|
-
routine_type,
|
|
522
|
-
CASE WHEN routine_type = 'PROCEDURE' THEN 'procedure' ELSE 'function' END as procedure_type,
|
|
523
|
-
external_language as language,
|
|
524
|
-
data_type as return_type,
|
|
525
|
-
routine_definition as definition,
|
|
526
|
-
(
|
|
527
|
-
SELECT string_agg(
|
|
528
|
-
parameter_name || ' ' ||
|
|
529
|
-
parameter_mode || ' ' ||
|
|
530
|
-
data_type,
|
|
531
|
-
', '
|
|
532
|
-
)
|
|
533
|
-
FROM information_schema.parameters
|
|
534
|
-
WHERE specific_schema = $1
|
|
535
|
-
AND specific_name = $2
|
|
536
|
-
AND parameter_name IS NOT NULL
|
|
537
|
-
) as parameter_list
|
|
538
|
-
FROM information_schema.routines
|
|
539
|
-
WHERE routine_schema = $1
|
|
540
|
-
AND routine_name = $2
|
|
541
|
-
`,
|
|
542
|
-
[schemaToUse, procedureName]
|
|
543
|
-
);
|
|
544
|
-
if (result.rows.length === 0) {
|
|
545
|
-
throw new Error(`Stored procedure '${procedureName}' not found in schema '${schemaToUse}'`);
|
|
546
|
-
}
|
|
547
|
-
const procedure = result.rows[0];
|
|
548
|
-
let definition = procedure.definition;
|
|
549
|
-
try {
|
|
550
|
-
const oidResult = await client.query(
|
|
551
|
-
`
|
|
552
|
-
SELECT p.oid, p.prosrc
|
|
553
|
-
FROM pg_proc p
|
|
554
|
-
JOIN pg_namespace n ON p.pronamespace = n.oid
|
|
555
|
-
WHERE p.proname = $1
|
|
556
|
-
AND n.nspname = $2
|
|
557
|
-
`,
|
|
558
|
-
[procedureName, schemaToUse]
|
|
559
|
-
);
|
|
560
|
-
if (oidResult.rows.length > 0) {
|
|
561
|
-
if (!definition) {
|
|
562
|
-
const oid = oidResult.rows[0].oid;
|
|
563
|
-
const defResult = await client.query(`SELECT pg_get_functiondef($1)`, [oid]);
|
|
564
|
-
if (defResult.rows.length > 0) {
|
|
565
|
-
definition = defResult.rows[0].pg_get_functiondef;
|
|
566
|
-
} else {
|
|
567
|
-
definition = oidResult.rows[0].prosrc;
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
}
|
|
571
|
-
} catch (err) {
|
|
572
|
-
console.error(`Error getting procedure definition: ${err}`);
|
|
573
|
-
}
|
|
574
|
-
return {
|
|
575
|
-
procedure_name: procedure.procedure_name,
|
|
576
|
-
procedure_type: procedure.procedure_type,
|
|
577
|
-
language: procedure.language || "sql",
|
|
578
|
-
parameter_list: procedure.parameter_list || "",
|
|
579
|
-
return_type: procedure.return_type !== "void" ? procedure.return_type : void 0,
|
|
580
|
-
definition: definition || void 0
|
|
581
|
-
};
|
|
582
|
-
} finally {
|
|
583
|
-
client.release();
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
async executeSQL(sql2, options, parameters) {
|
|
587
|
-
if (!this.pool) {
|
|
588
|
-
throw new Error("Not connected to database");
|
|
589
|
-
}
|
|
590
|
-
const client = await this.pool.connect();
|
|
591
|
-
try {
|
|
592
|
-
const statements = splitSQLStatements(sql2, "postgres");
|
|
593
|
-
if (statements.length === 1) {
|
|
594
|
-
const processedStatement = SQLRowLimiter.applyMaxRows(statements[0], options.maxRows);
|
|
595
|
-
let result;
|
|
596
|
-
if (parameters && parameters.length > 0) {
|
|
597
|
-
try {
|
|
598
|
-
result = await client.query(processedStatement, parameters);
|
|
599
|
-
} catch (error) {
|
|
600
|
-
console.error(`[PostgreSQL executeSQL] ERROR: ${error.message}`);
|
|
601
|
-
console.error(`[PostgreSQL executeSQL] SQL: ${processedStatement}`);
|
|
602
|
-
console.error(`[PostgreSQL executeSQL] Parameters: ${JSON.stringify(parameters)}`);
|
|
603
|
-
throw error;
|
|
604
|
-
}
|
|
605
|
-
} else {
|
|
606
|
-
result = await client.query(processedStatement);
|
|
607
|
-
}
|
|
608
|
-
return { rows: result.rows, rowCount: result.rowCount ?? result.rows.length };
|
|
609
|
-
} else {
|
|
610
|
-
if (parameters && parameters.length > 0) {
|
|
611
|
-
throw new Error("Parameters are not supported for multi-statement queries in PostgreSQL");
|
|
612
|
-
}
|
|
613
|
-
let allRows = [];
|
|
614
|
-
let totalRowCount = 0;
|
|
615
|
-
await client.query("BEGIN");
|
|
616
|
-
try {
|
|
617
|
-
for (let statement of statements) {
|
|
618
|
-
const processedStatement = SQLRowLimiter.applyMaxRows(statement, options.maxRows);
|
|
619
|
-
const result = await client.query(processedStatement);
|
|
620
|
-
if (result.rows && result.rows.length > 0) {
|
|
621
|
-
allRows.push(...result.rows);
|
|
622
|
-
}
|
|
623
|
-
if (result.rowCount) {
|
|
624
|
-
totalRowCount += result.rowCount;
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
|
-
await client.query("COMMIT");
|
|
628
|
-
} catch (error) {
|
|
629
|
-
await client.query("ROLLBACK");
|
|
630
|
-
throw error;
|
|
631
|
-
}
|
|
632
|
-
return { rows: allRows, rowCount: totalRowCount };
|
|
633
|
-
}
|
|
634
|
-
} finally {
|
|
635
|
-
client.release();
|
|
636
|
-
}
|
|
637
|
-
}
|
|
638
|
-
};
|
|
639
|
-
var postgresConnector = new PostgresConnector();
|
|
640
|
-
ConnectorRegistry.register(postgresConnector);
|
|
641
|
-
|
|
642
|
-
// src/connectors/sqlserver/index.ts
|
|
643
|
-
import sql from "mssql";
|
|
644
|
-
import { DefaultAzureCredential } from "@azure/identity";
|
|
645
|
-
var SQLServerDSNParser = class {
|
|
646
|
-
async parse(dsn, config) {
|
|
647
|
-
const connectionTimeoutSeconds = config?.connectionTimeoutSeconds;
|
|
648
|
-
const queryTimeoutSeconds = config?.queryTimeoutSeconds;
|
|
649
|
-
if (!this.isValidDSN(dsn)) {
|
|
650
|
-
const obfuscatedDSN = obfuscateDSNPassword(dsn);
|
|
651
|
-
const expectedFormat = this.getSampleDSN();
|
|
652
|
-
throw new Error(
|
|
653
|
-
`Invalid SQL Server DSN format.
|
|
654
|
-
Provided: ${obfuscatedDSN}
|
|
655
|
-
Expected: ${expectedFormat}`
|
|
656
|
-
);
|
|
657
|
-
}
|
|
658
|
-
try {
|
|
659
|
-
const url = new SafeURL(dsn);
|
|
660
|
-
const options = {};
|
|
661
|
-
url.forEachSearchParam((value, key) => {
|
|
662
|
-
if (key === "authentication") {
|
|
663
|
-
options.authentication = value;
|
|
664
|
-
} else if (key === "sslmode") {
|
|
665
|
-
options.sslmode = value;
|
|
666
|
-
} else if (key === "instanceName") {
|
|
667
|
-
options.instanceName = value;
|
|
668
|
-
} else if (key === "domain") {
|
|
669
|
-
options.domain = value;
|
|
670
|
-
}
|
|
671
|
-
});
|
|
672
|
-
if (options.authentication === "ntlm" && !options.domain) {
|
|
673
|
-
throw new Error("NTLM authentication requires 'domain' parameter");
|
|
674
|
-
}
|
|
675
|
-
if (options.domain && options.authentication !== "ntlm") {
|
|
676
|
-
throw new Error("Parameter 'domain' requires 'authentication=ntlm'");
|
|
677
|
-
}
|
|
678
|
-
if (options.sslmode) {
|
|
679
|
-
if (options.sslmode === "disable") {
|
|
680
|
-
options.encrypt = false;
|
|
681
|
-
options.trustServerCertificate = false;
|
|
682
|
-
} else if (options.sslmode === "require") {
|
|
683
|
-
options.encrypt = true;
|
|
684
|
-
options.trustServerCertificate = true;
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
const config2 = {
|
|
688
|
-
server: url.hostname,
|
|
689
|
-
port: url.port ? parseInt(url.port) : 1433,
|
|
690
|
-
// Default SQL Server port
|
|
691
|
-
database: url.pathname ? url.pathname.substring(1) : "",
|
|
692
|
-
// Remove leading slash
|
|
693
|
-
options: {
|
|
694
|
-
encrypt: options.encrypt ?? false,
|
|
695
|
-
// Default to unencrypted for development
|
|
696
|
-
trustServerCertificate: options.trustServerCertificate ?? false,
|
|
697
|
-
...connectionTimeoutSeconds !== void 0 && {
|
|
698
|
-
connectTimeout: connectionTimeoutSeconds * 1e3
|
|
699
|
-
},
|
|
700
|
-
...queryTimeoutSeconds !== void 0 && {
|
|
701
|
-
requestTimeout: queryTimeoutSeconds * 1e3
|
|
702
|
-
},
|
|
703
|
-
instanceName: options.instanceName
|
|
704
|
-
// Add named instance support
|
|
705
|
-
}
|
|
706
|
-
};
|
|
707
|
-
switch (options.authentication) {
|
|
708
|
-
case "azure-active-directory-access-token": {
|
|
709
|
-
try {
|
|
710
|
-
const credential = new DefaultAzureCredential();
|
|
711
|
-
const token = await credential.getToken("https://database.windows.net/");
|
|
712
|
-
config2.authentication = {
|
|
713
|
-
type: "azure-active-directory-access-token",
|
|
714
|
-
options: {
|
|
715
|
-
token: token.token
|
|
716
|
-
}
|
|
717
|
-
};
|
|
718
|
-
} catch (error) {
|
|
719
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
720
|
-
throw new Error(`Failed to get Azure AD token: ${errorMessage}`);
|
|
721
|
-
}
|
|
722
|
-
break;
|
|
723
|
-
}
|
|
724
|
-
case "ntlm":
|
|
725
|
-
config2.authentication = {
|
|
726
|
-
type: "ntlm",
|
|
727
|
-
options: {
|
|
728
|
-
domain: options.domain,
|
|
729
|
-
userName: url.username,
|
|
730
|
-
password: url.password
|
|
731
|
-
}
|
|
732
|
-
};
|
|
733
|
-
break;
|
|
734
|
-
default:
|
|
735
|
-
config2.user = url.username;
|
|
736
|
-
config2.password = url.password;
|
|
737
|
-
break;
|
|
738
|
-
}
|
|
739
|
-
return config2;
|
|
740
|
-
} catch (error) {
|
|
741
|
-
throw new Error(
|
|
742
|
-
`Failed to parse SQL Server DSN: ${error instanceof Error ? error.message : String(error)}`
|
|
743
|
-
);
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
getSampleDSN() {
|
|
747
|
-
return "sqlserver://username:password@localhost:1433/database?sslmode=disable&instanceName=INSTANCE1";
|
|
748
|
-
}
|
|
749
|
-
isValidDSN(dsn) {
|
|
750
|
-
try {
|
|
751
|
-
return dsn.startsWith("sqlserver://");
|
|
752
|
-
} catch (error) {
|
|
753
|
-
return false;
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
};
|
|
757
|
-
var SQLServerConnector = class _SQLServerConnector {
|
|
758
|
-
constructor() {
|
|
759
|
-
this.id = "sqlserver";
|
|
760
|
-
this.name = "SQL Server";
|
|
761
|
-
this.dsnParser = new SQLServerDSNParser();
|
|
762
|
-
// Source ID is set by ConnectorManager after cloning
|
|
763
|
-
this.sourceId = "default";
|
|
764
|
-
}
|
|
765
|
-
getId() {
|
|
766
|
-
return this.sourceId;
|
|
767
|
-
}
|
|
768
|
-
clone() {
|
|
769
|
-
return new _SQLServerConnector();
|
|
770
|
-
}
|
|
771
|
-
async connect(dsn, initScript, config) {
|
|
772
|
-
try {
|
|
773
|
-
this.config = await this.dsnParser.parse(dsn, config);
|
|
774
|
-
if (!this.config.options) {
|
|
775
|
-
this.config.options = {};
|
|
776
|
-
}
|
|
777
|
-
this.connection = await new sql.ConnectionPool(this.config).connect();
|
|
778
|
-
} catch (error) {
|
|
779
|
-
throw error;
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
async disconnect() {
|
|
783
|
-
if (this.connection) {
|
|
784
|
-
await this.connection.close();
|
|
785
|
-
this.connection = void 0;
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
async getSchemas() {
|
|
789
|
-
if (!this.connection) {
|
|
790
|
-
throw new Error("Not connected to SQL Server database");
|
|
791
|
-
}
|
|
792
|
-
try {
|
|
793
|
-
const result = await this.connection.request().query(`
|
|
794
|
-
SELECT SCHEMA_NAME
|
|
795
|
-
FROM INFORMATION_SCHEMA.SCHEMATA
|
|
796
|
-
ORDER BY SCHEMA_NAME
|
|
797
|
-
`);
|
|
798
|
-
return result.recordset.map((row) => row.SCHEMA_NAME);
|
|
799
|
-
} catch (error) {
|
|
800
|
-
throw new Error(`Failed to get schemas: ${error.message}`);
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
async getTables(schema) {
|
|
804
|
-
if (!this.connection) {
|
|
805
|
-
throw new Error("Not connected to SQL Server database");
|
|
806
|
-
}
|
|
807
|
-
try {
|
|
808
|
-
const schemaToUse = schema || "dbo";
|
|
809
|
-
const request = this.connection.request().input("schema", sql.VarChar, schemaToUse);
|
|
810
|
-
const query = `
|
|
811
|
-
SELECT TABLE_NAME
|
|
812
|
-
FROM INFORMATION_SCHEMA.TABLES
|
|
813
|
-
WHERE TABLE_SCHEMA = @schema
|
|
814
|
-
ORDER BY TABLE_NAME
|
|
815
|
-
`;
|
|
816
|
-
const result = await request.query(query);
|
|
817
|
-
return result.recordset.map((row) => row.TABLE_NAME);
|
|
818
|
-
} catch (error) {
|
|
819
|
-
throw new Error(`Failed to get tables: ${error.message}`);
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
async tableExists(tableName, schema) {
|
|
823
|
-
if (!this.connection) {
|
|
824
|
-
throw new Error("Not connected to SQL Server database");
|
|
825
|
-
}
|
|
826
|
-
try {
|
|
827
|
-
const schemaToUse = schema || "dbo";
|
|
828
|
-
const request = this.connection.request().input("tableName", sql.VarChar, tableName).input("schema", sql.VarChar, schemaToUse);
|
|
829
|
-
const query = `
|
|
830
|
-
SELECT COUNT(*) as count
|
|
831
|
-
FROM INFORMATION_SCHEMA.TABLES
|
|
832
|
-
WHERE TABLE_NAME = @tableName
|
|
833
|
-
AND TABLE_SCHEMA = @schema
|
|
834
|
-
`;
|
|
835
|
-
const result = await request.query(query);
|
|
836
|
-
return result.recordset[0].count > 0;
|
|
837
|
-
} catch (error) {
|
|
838
|
-
throw new Error(`Failed to check if table exists: ${error.message}`);
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
async getTableIndexes(tableName, schema) {
|
|
842
|
-
if (!this.connection) {
|
|
843
|
-
throw new Error("Not connected to SQL Server database");
|
|
844
|
-
}
|
|
845
|
-
try {
|
|
846
|
-
const schemaToUse = schema || "dbo";
|
|
847
|
-
const request = this.connection.request().input("tableName", sql.VarChar, tableName).input("schema", sql.VarChar, schemaToUse);
|
|
848
|
-
const query = `
|
|
849
|
-
SELECT i.name AS index_name,
|
|
850
|
-
i.is_unique,
|
|
851
|
-
i.is_primary_key,
|
|
852
|
-
c.name AS column_name,
|
|
853
|
-
ic.key_ordinal
|
|
854
|
-
FROM sys.indexes i
|
|
855
|
-
INNER JOIN
|
|
856
|
-
sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
|
|
857
|
-
INNER JOIN
|
|
858
|
-
sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
|
|
859
|
-
INNER JOIN
|
|
860
|
-
sys.tables t ON i.object_id = t.object_id
|
|
861
|
-
INNER JOIN
|
|
862
|
-
sys.schemas s ON t.schema_id = s.schema_id
|
|
863
|
-
WHERE t.name = @tableName
|
|
864
|
-
AND s.name = @schema
|
|
865
|
-
ORDER BY i.name,
|
|
866
|
-
ic.key_ordinal
|
|
867
|
-
`;
|
|
868
|
-
const result = await request.query(query);
|
|
869
|
-
const indexMap = /* @__PURE__ */ new Map();
|
|
870
|
-
for (const row of result.recordset) {
|
|
871
|
-
const indexName = row.index_name;
|
|
872
|
-
const columnName = row.column_name;
|
|
873
|
-
const isUnique = !!row.is_unique;
|
|
874
|
-
const isPrimary = !!row.is_primary_key;
|
|
875
|
-
if (!indexMap.has(indexName)) {
|
|
876
|
-
indexMap.set(indexName, {
|
|
877
|
-
columns: [],
|
|
878
|
-
is_unique: isUnique,
|
|
879
|
-
is_primary: isPrimary
|
|
880
|
-
});
|
|
881
|
-
}
|
|
882
|
-
const indexInfo = indexMap.get(indexName);
|
|
883
|
-
indexInfo.columns.push(columnName);
|
|
884
|
-
}
|
|
885
|
-
const indexes = [];
|
|
886
|
-
indexMap.forEach((info, name) => {
|
|
887
|
-
indexes.push({
|
|
888
|
-
index_name: name,
|
|
889
|
-
column_names: info.columns,
|
|
890
|
-
is_unique: info.is_unique,
|
|
891
|
-
is_primary: info.is_primary
|
|
892
|
-
});
|
|
893
|
-
});
|
|
894
|
-
return indexes;
|
|
895
|
-
} catch (error) {
|
|
896
|
-
throw new Error(`Failed to get indexes for table ${tableName}: ${error.message}`);
|
|
897
|
-
}
|
|
898
|
-
}
|
|
899
|
-
async getTableSchema(tableName, schema) {
|
|
900
|
-
if (!this.connection) {
|
|
901
|
-
throw new Error("Not connected to SQL Server database");
|
|
902
|
-
}
|
|
903
|
-
try {
|
|
904
|
-
const schemaToUse = schema || "dbo";
|
|
905
|
-
const request = this.connection.request().input("tableName", sql.VarChar, tableName).input("schema", sql.VarChar, schemaToUse);
|
|
906
|
-
const query = `
|
|
907
|
-
SELECT c.COLUMN_NAME as column_name,
|
|
908
|
-
c.DATA_TYPE as data_type,
|
|
909
|
-
c.IS_NULLABLE as is_nullable,
|
|
910
|
-
c.COLUMN_DEFAULT as column_default,
|
|
911
|
-
ep.value as description
|
|
912
|
-
FROM INFORMATION_SCHEMA.COLUMNS c
|
|
913
|
-
LEFT JOIN sys.columns sc
|
|
914
|
-
ON sc.name = c.COLUMN_NAME
|
|
915
|
-
AND sc.object_id = OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.' + QUOTENAME(c.TABLE_NAME))
|
|
916
|
-
LEFT JOIN sys.extended_properties ep
|
|
917
|
-
ON ep.major_id = sc.object_id
|
|
918
|
-
AND ep.minor_id = sc.column_id
|
|
919
|
-
AND ep.name = 'MS_Description'
|
|
920
|
-
WHERE c.TABLE_NAME = @tableName
|
|
921
|
-
AND c.TABLE_SCHEMA = @schema
|
|
922
|
-
ORDER BY c.ORDINAL_POSITION
|
|
923
|
-
`;
|
|
924
|
-
const result = await request.query(query);
|
|
925
|
-
return result.recordset.map((row) => ({
|
|
926
|
-
...row,
|
|
927
|
-
description: row.description || null
|
|
928
|
-
}));
|
|
929
|
-
} catch (error) {
|
|
930
|
-
throw new Error(`Failed to get schema for table ${tableName}: ${error.message}`);
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
async getTableComment(tableName, schema) {
|
|
934
|
-
if (!this.connection) {
|
|
935
|
-
throw new Error("Not connected to SQL Server database");
|
|
936
|
-
}
|
|
937
|
-
try {
|
|
938
|
-
const schemaToUse = schema || "dbo";
|
|
939
|
-
const request = this.connection.request().input("tableName", sql.VarChar, tableName).input("schema", sql.VarChar, schemaToUse);
|
|
940
|
-
const query = `
|
|
941
|
-
SELECT ep.value as table_comment
|
|
942
|
-
FROM sys.extended_properties ep
|
|
943
|
-
JOIN sys.tables t ON ep.major_id = t.object_id
|
|
944
|
-
JOIN sys.schemas s ON t.schema_id = s.schema_id
|
|
945
|
-
WHERE ep.minor_id = 0
|
|
946
|
-
AND ep.name = 'MS_Description'
|
|
947
|
-
AND t.name = @tableName
|
|
948
|
-
AND s.name = @schema
|
|
949
|
-
`;
|
|
950
|
-
const result = await request.query(query);
|
|
951
|
-
if (result.recordset.length > 0) {
|
|
952
|
-
return result.recordset[0].table_comment || null;
|
|
953
|
-
}
|
|
954
|
-
return null;
|
|
955
|
-
} catch (error) {
|
|
956
|
-
return null;
|
|
957
|
-
}
|
|
958
|
-
}
|
|
959
|
-
async getStoredProcedures(schema, routineType) {
|
|
960
|
-
if (!this.connection) {
|
|
961
|
-
throw new Error("Not connected to SQL Server database");
|
|
962
|
-
}
|
|
963
|
-
try {
|
|
964
|
-
const schemaToUse = schema || "dbo";
|
|
965
|
-
const request = this.connection.request().input("schema", sql.VarChar, schemaToUse);
|
|
966
|
-
let typeFilter;
|
|
967
|
-
if (routineType === "function") {
|
|
968
|
-
typeFilter = "AND ROUTINE_TYPE = 'FUNCTION'";
|
|
969
|
-
} else if (routineType === "procedure") {
|
|
970
|
-
typeFilter = "AND ROUTINE_TYPE = 'PROCEDURE'";
|
|
971
|
-
} else {
|
|
972
|
-
typeFilter = "AND (ROUTINE_TYPE = 'PROCEDURE' OR ROUTINE_TYPE = 'FUNCTION')";
|
|
973
|
-
}
|
|
974
|
-
const query = `
|
|
975
|
-
SELECT ROUTINE_NAME
|
|
976
|
-
FROM INFORMATION_SCHEMA.ROUTINES
|
|
977
|
-
WHERE ROUTINE_SCHEMA = @schema
|
|
978
|
-
${typeFilter}
|
|
979
|
-
ORDER BY ROUTINE_NAME
|
|
980
|
-
`;
|
|
981
|
-
const result = await request.query(query);
|
|
982
|
-
return result.recordset.map((row) => row.ROUTINE_NAME);
|
|
983
|
-
} catch (error) {
|
|
984
|
-
throw new Error(`Failed to get stored procedures: ${error.message}`);
|
|
985
|
-
}
|
|
986
|
-
}
|
|
987
|
-
async getStoredProcedureDetail(procedureName, schema) {
|
|
988
|
-
if (!this.connection) {
|
|
989
|
-
throw new Error("Not connected to SQL Server database");
|
|
990
|
-
}
|
|
991
|
-
try {
|
|
992
|
-
const schemaToUse = schema || "dbo";
|
|
993
|
-
const request = this.connection.request().input("procedureName", sql.VarChar, procedureName).input("schema", sql.VarChar, schemaToUse);
|
|
994
|
-
const routineQuery = `
|
|
995
|
-
SELECT ROUTINE_NAME as procedure_name,
|
|
996
|
-
ROUTINE_TYPE,
|
|
997
|
-
DATA_TYPE as return_data_type
|
|
998
|
-
FROM INFORMATION_SCHEMA.ROUTINES
|
|
999
|
-
WHERE ROUTINE_NAME = @procedureName
|
|
1000
|
-
AND ROUTINE_SCHEMA = @schema
|
|
1001
|
-
`;
|
|
1002
|
-
const routineResult = await request.query(routineQuery);
|
|
1003
|
-
if (routineResult.recordset.length === 0) {
|
|
1004
|
-
throw new Error(`Stored procedure '${procedureName}' not found in schema '${schemaToUse}'`);
|
|
1005
|
-
}
|
|
1006
|
-
const routine = routineResult.recordset[0];
|
|
1007
|
-
const parameterQuery = `
|
|
1008
|
-
SELECT PARAMETER_NAME,
|
|
1009
|
-
PARAMETER_MODE,
|
|
1010
|
-
DATA_TYPE,
|
|
1011
|
-
CHARACTER_MAXIMUM_LENGTH,
|
|
1012
|
-
ORDINAL_POSITION
|
|
1013
|
-
FROM INFORMATION_SCHEMA.PARAMETERS
|
|
1014
|
-
WHERE SPECIFIC_NAME = @procedureName
|
|
1015
|
-
AND SPECIFIC_SCHEMA = @schema
|
|
1016
|
-
ORDER BY ORDINAL_POSITION
|
|
1017
|
-
`;
|
|
1018
|
-
const parameterResult = await request.query(parameterQuery);
|
|
1019
|
-
let parameterList = "";
|
|
1020
|
-
if (parameterResult.recordset.length > 0) {
|
|
1021
|
-
parameterList = parameterResult.recordset.map(
|
|
1022
|
-
(param) => {
|
|
1023
|
-
const lengthStr = param.CHARACTER_MAXIMUM_LENGTH > 0 ? `(${param.CHARACTER_MAXIMUM_LENGTH})` : "";
|
|
1024
|
-
return `${param.PARAMETER_NAME} ${param.PARAMETER_MODE} ${param.DATA_TYPE}${lengthStr}`;
|
|
1025
|
-
}
|
|
1026
|
-
).join(", ");
|
|
1027
|
-
}
|
|
1028
|
-
const definitionQuery = `
|
|
1029
|
-
SELECT definition
|
|
1030
|
-
FROM sys.sql_modules sm
|
|
1031
|
-
JOIN sys.objects o ON sm.object_id = o.object_id
|
|
1032
|
-
JOIN sys.schemas s ON o.schema_id = s.schema_id
|
|
1033
|
-
WHERE o.name = @procedureName
|
|
1034
|
-
AND s.name = @schema
|
|
1035
|
-
`;
|
|
1036
|
-
const definitionResult = await request.query(definitionQuery);
|
|
1037
|
-
let definition = void 0;
|
|
1038
|
-
if (definitionResult.recordset.length > 0) {
|
|
1039
|
-
definition = definitionResult.recordset[0].definition;
|
|
1040
|
-
}
|
|
1041
|
-
return {
|
|
1042
|
-
procedure_name: routine.procedure_name,
|
|
1043
|
-
procedure_type: routine.ROUTINE_TYPE === "PROCEDURE" ? "procedure" : "function",
|
|
1044
|
-
language: "sql",
|
|
1045
|
-
// SQL Server procedures are typically in T-SQL
|
|
1046
|
-
parameter_list: parameterList,
|
|
1047
|
-
return_type: routine.ROUTINE_TYPE === "FUNCTION" ? routine.return_data_type : void 0,
|
|
1048
|
-
definition
|
|
1049
|
-
};
|
|
1050
|
-
} catch (error) {
|
|
1051
|
-
throw new Error(`Failed to get stored procedure details: ${error.message}`);
|
|
1052
|
-
}
|
|
1053
|
-
}
|
|
1054
|
-
async executeSQL(sqlQuery, options, parameters) {
|
|
1055
|
-
if (!this.connection) {
|
|
1056
|
-
throw new Error("Not connected to SQL Server database");
|
|
1057
|
-
}
|
|
1058
|
-
try {
|
|
1059
|
-
let processedSQL = sqlQuery;
|
|
1060
|
-
if (options.maxRows) {
|
|
1061
|
-
processedSQL = SQLRowLimiter.applyMaxRowsForSQLServer(sqlQuery, options.maxRows);
|
|
1062
|
-
}
|
|
1063
|
-
const request = this.connection.request();
|
|
1064
|
-
if (parameters && parameters.length > 0) {
|
|
1065
|
-
parameters.forEach((param, index) => {
|
|
1066
|
-
const paramName = `p${index + 1}`;
|
|
1067
|
-
if (typeof param === "string") {
|
|
1068
|
-
request.input(paramName, sql.VarChar, param);
|
|
1069
|
-
} else if (typeof param === "number") {
|
|
1070
|
-
if (Number.isInteger(param)) {
|
|
1071
|
-
request.input(paramName, sql.Int, param);
|
|
1072
|
-
} else {
|
|
1073
|
-
request.input(paramName, sql.Float, param);
|
|
1074
|
-
}
|
|
1075
|
-
} else if (typeof param === "boolean") {
|
|
1076
|
-
request.input(paramName, sql.Bit, param);
|
|
1077
|
-
} else if (param === null || param === void 0) {
|
|
1078
|
-
request.input(paramName, sql.VarChar, param);
|
|
1079
|
-
} else if (Array.isArray(param)) {
|
|
1080
|
-
request.input(paramName, sql.VarChar, JSON.stringify(param));
|
|
1081
|
-
} else {
|
|
1082
|
-
request.input(paramName, sql.VarChar, JSON.stringify(param));
|
|
1083
|
-
}
|
|
1084
|
-
});
|
|
1085
|
-
}
|
|
1086
|
-
let result;
|
|
1087
|
-
try {
|
|
1088
|
-
result = await request.query(processedSQL);
|
|
1089
|
-
} catch (error) {
|
|
1090
|
-
if (parameters && parameters.length > 0) {
|
|
1091
|
-
console.error(`[SQL Server executeSQL] ERROR: ${error.message}`);
|
|
1092
|
-
console.error(`[SQL Server executeSQL] SQL: ${processedSQL}`);
|
|
1093
|
-
console.error(`[SQL Server executeSQL] Parameters: ${JSON.stringify(parameters)}`);
|
|
1094
|
-
}
|
|
1095
|
-
throw error;
|
|
1096
|
-
}
|
|
1097
|
-
return {
|
|
1098
|
-
rows: result.recordset || [],
|
|
1099
|
-
rowCount: result.rowsAffected[0] || 0
|
|
1100
|
-
};
|
|
1101
|
-
} catch (error) {
|
|
1102
|
-
throw new Error(`Failed to execute query: ${error.message}`);
|
|
1103
|
-
}
|
|
1104
|
-
}
|
|
1105
|
-
};
|
|
1106
|
-
var sqlServerConnector = new SQLServerConnector();
|
|
1107
|
-
ConnectorRegistry.register(sqlServerConnector);
|
|
1108
|
-
|
|
1109
|
-
// src/connectors/sqlite/index.ts
|
|
1110
|
-
import Database from "better-sqlite3";
|
|
1111
|
-
var SQLiteDSNParser = class {
|
|
1112
|
-
async parse(dsn, config) {
|
|
1113
|
-
if (!this.isValidDSN(dsn)) {
|
|
1114
|
-
const obfuscatedDSN = obfuscateDSNPassword(dsn);
|
|
1115
|
-
const expectedFormat = this.getSampleDSN();
|
|
1116
|
-
throw new Error(
|
|
1117
|
-
`Invalid SQLite DSN format.
|
|
1118
|
-
Provided: ${obfuscatedDSN}
|
|
1119
|
-
Expected: ${expectedFormat}`
|
|
1120
|
-
);
|
|
1121
|
-
}
|
|
1122
|
-
try {
|
|
1123
|
-
const url = new SafeURL(dsn);
|
|
1124
|
-
let dbPath;
|
|
1125
|
-
if (url.hostname === "" && url.pathname === "/:memory:") {
|
|
1126
|
-
dbPath = ":memory:";
|
|
1127
|
-
} else {
|
|
1128
|
-
if (url.pathname.startsWith("//")) {
|
|
1129
|
-
dbPath = url.pathname.substring(2);
|
|
1130
|
-
} else if (url.pathname.match(/^\/[A-Za-z]:\//)) {
|
|
1131
|
-
dbPath = url.pathname.substring(1);
|
|
1132
|
-
} else {
|
|
1133
|
-
dbPath = url.pathname;
|
|
1134
|
-
}
|
|
1135
|
-
}
|
|
1136
|
-
return { dbPath };
|
|
1137
|
-
} catch (error) {
|
|
1138
|
-
throw new Error(
|
|
1139
|
-
`Failed to parse SQLite DSN: ${error instanceof Error ? error.message : String(error)}`
|
|
1140
|
-
);
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
getSampleDSN() {
|
|
1144
|
-
return "sqlite:///path/to/database.db";
|
|
1145
|
-
}
|
|
1146
|
-
isValidDSN(dsn) {
|
|
1147
|
-
try {
|
|
1148
|
-
return dsn.startsWith("sqlite://");
|
|
1149
|
-
} catch (error) {
|
|
1150
|
-
return false;
|
|
1151
|
-
}
|
|
1152
|
-
}
|
|
1153
|
-
};
|
|
1154
|
-
var SQLiteConnector = class _SQLiteConnector {
|
|
1155
|
-
constructor() {
|
|
1156
|
-
this.id = "sqlite";
|
|
1157
|
-
this.name = "SQLite";
|
|
1158
|
-
this.dsnParser = new SQLiteDSNParser();
|
|
1159
|
-
this.db = null;
|
|
1160
|
-
this.dbPath = ":memory:";
|
|
1161
|
-
// Default to in-memory database
|
|
1162
|
-
// Source ID is set by ConnectorManager after cloning
|
|
1163
|
-
this.sourceId = "default";
|
|
1164
|
-
}
|
|
1165
|
-
getId() {
|
|
1166
|
-
return this.sourceId;
|
|
1167
|
-
}
|
|
1168
|
-
clone() {
|
|
1169
|
-
return new _SQLiteConnector();
|
|
1170
|
-
}
|
|
1171
|
-
/**
|
|
1172
|
-
* Connect to SQLite database
|
|
1173
|
-
* Note: SQLite does not support connection timeouts as it's a local file-based database.
|
|
1174
|
-
* The config parameter is accepted for interface compliance but ignored.
|
|
1175
|
-
*/
|
|
1176
|
-
async connect(dsn, initScript, config) {
|
|
1177
|
-
const parsedConfig = await this.dsnParser.parse(dsn, config);
|
|
1178
|
-
this.dbPath = parsedConfig.dbPath;
|
|
1179
|
-
try {
|
|
1180
|
-
const dbOptions = {};
|
|
1181
|
-
if (config?.readonly && this.dbPath !== ":memory:") {
|
|
1182
|
-
dbOptions.readonly = true;
|
|
1183
|
-
}
|
|
1184
|
-
this.db = new Database(this.dbPath, dbOptions);
|
|
1185
|
-
this.db.defaultSafeIntegers(true);
|
|
1186
|
-
if (initScript) {
|
|
1187
|
-
this.db.exec(initScript);
|
|
1188
|
-
}
|
|
1189
|
-
} catch (error) {
|
|
1190
|
-
console.error("Failed to connect to SQLite database:", error);
|
|
1191
|
-
throw error;
|
|
1192
|
-
}
|
|
1193
|
-
}
|
|
1194
|
-
async disconnect() {
|
|
1195
|
-
if (this.db) {
|
|
1196
|
-
try {
|
|
1197
|
-
if (!this.db.inTransaction) {
|
|
1198
|
-
this.db.close();
|
|
1199
|
-
} else {
|
|
1200
|
-
try {
|
|
1201
|
-
this.db.exec("ROLLBACK");
|
|
1202
|
-
} catch (rollbackError) {
|
|
1203
|
-
}
|
|
1204
|
-
this.db.close();
|
|
1205
|
-
}
|
|
1206
|
-
this.db = null;
|
|
1207
|
-
} catch (error) {
|
|
1208
|
-
console.error("Error during SQLite disconnect:", error);
|
|
1209
|
-
this.db = null;
|
|
1210
|
-
}
|
|
1211
|
-
}
|
|
1212
|
-
return Promise.resolve();
|
|
1213
|
-
}
|
|
1214
|
-
async getSchemas() {
|
|
1215
|
-
if (!this.db) {
|
|
1216
|
-
throw new Error("Not connected to SQLite database");
|
|
1217
|
-
}
|
|
1218
|
-
return ["main"];
|
|
1219
|
-
}
|
|
1220
|
-
async getTables(schema) {
|
|
1221
|
-
if (!this.db) {
|
|
1222
|
-
throw new Error("Not connected to SQLite database");
|
|
1223
|
-
}
|
|
1224
|
-
try {
|
|
1225
|
-
const rows = this.db.prepare(
|
|
1226
|
-
`
|
|
1227
|
-
SELECT name FROM sqlite_master
|
|
1228
|
-
WHERE type='table' AND name NOT LIKE 'sqlite_%'
|
|
1229
|
-
ORDER BY name
|
|
1230
|
-
`
|
|
1231
|
-
).all();
|
|
1232
|
-
return rows.map((row) => row.name);
|
|
1233
|
-
} catch (error) {
|
|
1234
|
-
throw error;
|
|
1235
|
-
}
|
|
1236
|
-
}
|
|
1237
|
-
async tableExists(tableName, schema) {
|
|
1238
|
-
if (!this.db) {
|
|
1239
|
-
throw new Error("Not connected to SQLite database");
|
|
1240
|
-
}
|
|
1241
|
-
try {
|
|
1242
|
-
const row = this.db.prepare(
|
|
1243
|
-
`
|
|
1244
|
-
SELECT name FROM sqlite_master
|
|
1245
|
-
WHERE type='table' AND name = ?
|
|
1246
|
-
`
|
|
1247
|
-
).get(tableName);
|
|
1248
|
-
return !!row;
|
|
1249
|
-
} catch (error) {
|
|
1250
|
-
throw error;
|
|
1251
|
-
}
|
|
1252
|
-
}
|
|
1253
|
-
async getTableIndexes(tableName, schema) {
|
|
1254
|
-
if (!this.db) {
|
|
1255
|
-
throw new Error("Not connected to SQLite database");
|
|
1256
|
-
}
|
|
1257
|
-
try {
|
|
1258
|
-
const indexInfoRows = this.db.prepare(
|
|
1259
|
-
`
|
|
1260
|
-
SELECT
|
|
1261
|
-
name as index_name,
|
|
1262
|
-
0 as is_unique
|
|
1263
|
-
FROM sqlite_master
|
|
1264
|
-
WHERE type = 'index'
|
|
1265
|
-
AND tbl_name = ?
|
|
1266
|
-
`
|
|
1267
|
-
).all(tableName);
|
|
1268
|
-
const quotedTableName = quoteIdentifier(tableName, "sqlite");
|
|
1269
|
-
const indexListRows = this.db.prepare(`PRAGMA index_list(${quotedTableName})`).all();
|
|
1270
|
-
const indexUniqueMap = /* @__PURE__ */ new Map();
|
|
1271
|
-
for (const indexListRow of indexListRows) {
|
|
1272
|
-
indexUniqueMap.set(indexListRow.name, indexListRow.unique === 1);
|
|
1273
|
-
}
|
|
1274
|
-
const tableInfo = this.db.prepare(`PRAGMA table_info(${quotedTableName})`).all();
|
|
1275
|
-
const pkColumns = tableInfo.filter((col) => col.pk > 0).map((col) => col.name);
|
|
1276
|
-
const results = [];
|
|
1277
|
-
for (const indexInfo of indexInfoRows) {
|
|
1278
|
-
const quotedIndexName = quoteIdentifier(indexInfo.index_name, "sqlite");
|
|
1279
|
-
const indexDetailRows = this.db.prepare(`PRAGMA index_info(${quotedIndexName})`).all();
|
|
1280
|
-
const columnNames = indexDetailRows.map((row) => row.name);
|
|
1281
|
-
results.push({
|
|
1282
|
-
index_name: indexInfo.index_name,
|
|
1283
|
-
column_names: columnNames,
|
|
1284
|
-
is_unique: indexUniqueMap.get(indexInfo.index_name) || false,
|
|
1285
|
-
is_primary: false
|
|
1286
|
-
});
|
|
1287
|
-
}
|
|
1288
|
-
if (pkColumns.length > 0) {
|
|
1289
|
-
results.push({
|
|
1290
|
-
index_name: "PRIMARY",
|
|
1291
|
-
column_names: pkColumns,
|
|
1292
|
-
is_unique: true,
|
|
1293
|
-
is_primary: true
|
|
1294
|
-
});
|
|
1295
|
-
}
|
|
1296
|
-
return results;
|
|
1297
|
-
} catch (error) {
|
|
1298
|
-
throw error;
|
|
1299
|
-
}
|
|
1300
|
-
}
|
|
1301
|
-
async getTableSchema(tableName, schema) {
|
|
1302
|
-
if (!this.db) {
|
|
1303
|
-
throw new Error("Not connected to SQLite database");
|
|
1304
|
-
}
|
|
1305
|
-
try {
|
|
1306
|
-
const quotedTableName = quoteIdentifier(tableName, "sqlite");
|
|
1307
|
-
const rows = this.db.prepare(`PRAGMA table_info(${quotedTableName})`).all();
|
|
1308
|
-
const columns = rows.map((row) => ({
|
|
1309
|
-
column_name: row.name,
|
|
1310
|
-
data_type: row.type,
|
|
1311
|
-
// In SQLite, primary key columns are automatically NOT NULL even if notnull=0
|
|
1312
|
-
is_nullable: row.notnull === 1 || row.pk > 0 ? "NO" : "YES",
|
|
1313
|
-
column_default: row.dflt_value,
|
|
1314
|
-
description: null
|
|
1315
|
-
}));
|
|
1316
|
-
return columns;
|
|
1317
|
-
} catch (error) {
|
|
1318
|
-
throw error;
|
|
1319
|
-
}
|
|
1320
|
-
}
|
|
1321
|
-
async getStoredProcedures(schema, routineType) {
|
|
1322
|
-
if (!this.db) {
|
|
1323
|
-
throw new Error("Not connected to SQLite database");
|
|
1324
|
-
}
|
|
1325
|
-
return [];
|
|
1326
|
-
}
|
|
1327
|
-
async getStoredProcedureDetail(procedureName, schema) {
|
|
1328
|
-
if (!this.db) {
|
|
1329
|
-
throw new Error("Not connected to SQLite database");
|
|
1330
|
-
}
|
|
1331
|
-
throw new Error(
|
|
1332
|
-
"SQLite does not support stored procedures. Functions are defined programmatically through the SQLite API, not stored in the database."
|
|
1333
|
-
);
|
|
1334
|
-
}
|
|
1335
|
-
async executeSQL(sql2, options, parameters) {
|
|
1336
|
-
if (!this.db) {
|
|
1337
|
-
throw new Error("Not connected to SQLite database");
|
|
1338
|
-
}
|
|
1339
|
-
try {
|
|
1340
|
-
const statements = splitSQLStatements(sql2, "sqlite");
|
|
1341
|
-
if (statements.length === 1) {
|
|
1342
|
-
let processedStatement = statements[0];
|
|
1343
|
-
const trimmedStatement = statements[0].toLowerCase().trim();
|
|
1344
|
-
const isReadStatement = trimmedStatement.startsWith("select") || trimmedStatement.startsWith("with") || trimmedStatement.startsWith("explain") || trimmedStatement.startsWith("analyze") || trimmedStatement.startsWith("pragma") && (trimmedStatement.includes("table_info") || trimmedStatement.includes("index_info") || trimmedStatement.includes("index_list") || trimmedStatement.includes("foreign_key_list"));
|
|
1345
|
-
if (options.maxRows) {
|
|
1346
|
-
processedStatement = SQLRowLimiter.applyMaxRows(processedStatement, options.maxRows);
|
|
1347
|
-
}
|
|
1348
|
-
if (isReadStatement) {
|
|
1349
|
-
if (parameters && parameters.length > 0) {
|
|
1350
|
-
try {
|
|
1351
|
-
const rows = this.db.prepare(processedStatement).all(...parameters);
|
|
1352
|
-
return { rows, rowCount: rows.length };
|
|
1353
|
-
} catch (error) {
|
|
1354
|
-
console.error(`[SQLite executeSQL] ERROR: ${error.message}`);
|
|
1355
|
-
console.error(`[SQLite executeSQL] SQL: ${processedStatement}`);
|
|
1356
|
-
console.error(`[SQLite executeSQL] Parameters: ${JSON.stringify(parameters)}`);
|
|
1357
|
-
throw error;
|
|
1358
|
-
}
|
|
1359
|
-
} else {
|
|
1360
|
-
const rows = this.db.prepare(processedStatement).all();
|
|
1361
|
-
return { rows, rowCount: rows.length };
|
|
1362
|
-
}
|
|
1363
|
-
} else {
|
|
1364
|
-
let result;
|
|
1365
|
-
if (parameters && parameters.length > 0) {
|
|
1366
|
-
try {
|
|
1367
|
-
result = this.db.prepare(processedStatement).run(...parameters);
|
|
1368
|
-
} catch (error) {
|
|
1369
|
-
console.error(`[SQLite executeSQL] ERROR: ${error.message}`);
|
|
1370
|
-
console.error(`[SQLite executeSQL] SQL: ${processedStatement}`);
|
|
1371
|
-
console.error(`[SQLite executeSQL] Parameters: ${JSON.stringify(parameters)}`);
|
|
1372
|
-
throw error;
|
|
1373
|
-
}
|
|
1374
|
-
} else {
|
|
1375
|
-
result = this.db.prepare(processedStatement).run();
|
|
1376
|
-
}
|
|
1377
|
-
return { rows: [], rowCount: result.changes };
|
|
1378
|
-
}
|
|
1379
|
-
} else {
|
|
1380
|
-
if (parameters && parameters.length > 0) {
|
|
1381
|
-
throw new Error("Parameters are not supported for multi-statement queries in SQLite");
|
|
1382
|
-
}
|
|
1383
|
-
const readStatements = [];
|
|
1384
|
-
const writeStatements = [];
|
|
1385
|
-
for (const statement of statements) {
|
|
1386
|
-
const trimmedStatement = statement.toLowerCase().trim();
|
|
1387
|
-
if (trimmedStatement.startsWith("select") || trimmedStatement.startsWith("with") || trimmedStatement.startsWith("explain") || trimmedStatement.startsWith("analyze") || trimmedStatement.startsWith("pragma") && (trimmedStatement.includes("table_info") || trimmedStatement.includes("index_info") || trimmedStatement.includes("index_list") || trimmedStatement.includes("foreign_key_list"))) {
|
|
1388
|
-
readStatements.push(statement);
|
|
1389
|
-
} else {
|
|
1390
|
-
writeStatements.push(statement);
|
|
1391
|
-
}
|
|
1392
|
-
}
|
|
1393
|
-
let totalChanges = 0;
|
|
1394
|
-
for (const statement of writeStatements) {
|
|
1395
|
-
const result = this.db.prepare(statement).run();
|
|
1396
|
-
totalChanges += result.changes;
|
|
1397
|
-
}
|
|
1398
|
-
let allRows = [];
|
|
1399
|
-
for (let statement of readStatements) {
|
|
1400
|
-
statement = SQLRowLimiter.applyMaxRows(statement, options.maxRows);
|
|
1401
|
-
const result = this.db.prepare(statement).all();
|
|
1402
|
-
allRows.push(...result);
|
|
1403
|
-
}
|
|
1404
|
-
return { rows: allRows, rowCount: totalChanges + allRows.length };
|
|
1405
|
-
}
|
|
1406
|
-
} catch (error) {
|
|
1407
|
-
throw error;
|
|
1408
|
-
}
|
|
1409
|
-
}
|
|
1410
|
-
};
|
|
1411
|
-
var sqliteConnector = new SQLiteConnector();
|
|
1412
|
-
ConnectorRegistry.register(sqliteConnector);
|
|
1413
|
-
|
|
1414
|
-
// src/connectors/mysql/index.ts
|
|
1415
|
-
import mysql from "mysql2/promise";
|
|
1416
|
-
|
|
1417
|
-
// src/utils/multi-statement-result-parser.ts
|
|
1418
|
-
function isMetadataObject(element) {
|
|
1419
|
-
if (!element || typeof element !== "object" || Array.isArray(element)) {
|
|
1420
|
-
return false;
|
|
1421
|
-
}
|
|
1422
|
-
return "affectedRows" in element || "insertId" in element || "fieldCount" in element || "warningStatus" in element;
|
|
1423
|
-
}
|
|
1424
|
-
function isMultiStatementResult(results) {
|
|
1425
|
-
if (!Array.isArray(results) || results.length === 0) {
|
|
1426
|
-
return false;
|
|
1427
|
-
}
|
|
1428
|
-
const firstElement = results[0];
|
|
1429
|
-
return isMetadataObject(firstElement) || Array.isArray(firstElement);
|
|
1430
|
-
}
|
|
1431
|
-
function extractRowsFromMultiStatement(results) {
|
|
1432
|
-
if (!Array.isArray(results)) {
|
|
1433
|
-
return [];
|
|
1434
|
-
}
|
|
1435
|
-
const allRows = [];
|
|
1436
|
-
for (const result of results) {
|
|
1437
|
-
if (Array.isArray(result)) {
|
|
1438
|
-
allRows.push(...result);
|
|
1439
|
-
}
|
|
1440
|
-
}
|
|
1441
|
-
return allRows;
|
|
1442
|
-
}
|
|
1443
|
-
function extractAffectedRows(results) {
|
|
1444
|
-
if (isMetadataObject(results)) {
|
|
1445
|
-
return results.affectedRows || 0;
|
|
1446
|
-
}
|
|
1447
|
-
if (!Array.isArray(results)) {
|
|
1448
|
-
return 0;
|
|
1449
|
-
}
|
|
1450
|
-
if (isMultiStatementResult(results)) {
|
|
1451
|
-
let totalAffected = 0;
|
|
1452
|
-
for (const result of results) {
|
|
1453
|
-
if (isMetadataObject(result)) {
|
|
1454
|
-
totalAffected += result.affectedRows || 0;
|
|
1455
|
-
} else if (Array.isArray(result)) {
|
|
1456
|
-
totalAffected += result.length;
|
|
1457
|
-
}
|
|
1458
|
-
}
|
|
1459
|
-
return totalAffected;
|
|
1460
|
-
}
|
|
1461
|
-
return results.length;
|
|
1462
|
-
}
|
|
1463
|
-
function parseQueryResults(results) {
|
|
1464
|
-
if (!Array.isArray(results)) {
|
|
1465
|
-
return [];
|
|
1466
|
-
}
|
|
1467
|
-
if (isMultiStatementResult(results)) {
|
|
1468
|
-
return extractRowsFromMultiStatement(results);
|
|
1469
|
-
}
|
|
1470
|
-
return results;
|
|
1471
|
-
}
|
|
1472
|
-
|
|
1473
|
-
// src/connectors/mysql/index.ts
|
|
1474
|
-
var MySQLDSNParser = class {
|
|
1475
|
-
async parse(dsn, config) {
|
|
1476
|
-
const connectionTimeoutSeconds = config?.connectionTimeoutSeconds;
|
|
1477
|
-
if (!this.isValidDSN(dsn)) {
|
|
1478
|
-
const obfuscatedDSN = obfuscateDSNPassword(dsn);
|
|
1479
|
-
const expectedFormat = this.getSampleDSN();
|
|
1480
|
-
throw new Error(
|
|
1481
|
-
`Invalid MySQL DSN format.
|
|
1482
|
-
Provided: ${obfuscatedDSN}
|
|
1483
|
-
Expected: ${expectedFormat}`
|
|
1484
|
-
);
|
|
1485
|
-
}
|
|
1486
|
-
try {
|
|
1487
|
-
const url = new SafeURL(dsn);
|
|
1488
|
-
const config2 = {
|
|
1489
|
-
host: url.hostname,
|
|
1490
|
-
port: url.port ? parseInt(url.port) : 3306,
|
|
1491
|
-
database: url.pathname ? url.pathname.substring(1) : "",
|
|
1492
|
-
// Remove leading '/' if exists
|
|
1493
|
-
user: url.username,
|
|
1494
|
-
password: url.password,
|
|
1495
|
-
multipleStatements: true,
|
|
1496
|
-
// Enable native multi-statement support
|
|
1497
|
-
supportBigNumbers: true
|
|
1498
|
-
// Return BIGINT as string when value exceeds Number.MAX_SAFE_INTEGER
|
|
1499
|
-
};
|
|
1500
|
-
url.forEachSearchParam((value, key) => {
|
|
1501
|
-
if (key === "sslmode") {
|
|
1502
|
-
if (value === "disable") {
|
|
1503
|
-
config2.ssl = void 0;
|
|
1504
|
-
} else if (value === "require") {
|
|
1505
|
-
config2.ssl = { rejectUnauthorized: false };
|
|
1506
|
-
} else {
|
|
1507
|
-
config2.ssl = {};
|
|
1508
|
-
}
|
|
1509
|
-
}
|
|
1510
|
-
});
|
|
1511
|
-
if (connectionTimeoutSeconds !== void 0) {
|
|
1512
|
-
config2.connectTimeout = connectionTimeoutSeconds * 1e3;
|
|
1513
|
-
}
|
|
1514
|
-
if (url.password && url.password.includes("X-Amz-Credential")) {
|
|
1515
|
-
config2.authPlugins = {
|
|
1516
|
-
mysql_clear_password: () => () => {
|
|
1517
|
-
return Buffer.from(url.password + "\0");
|
|
1518
|
-
}
|
|
1519
|
-
};
|
|
1520
|
-
if (config2.ssl === void 0) {
|
|
1521
|
-
config2.ssl = { rejectUnauthorized: false };
|
|
1522
|
-
}
|
|
1523
|
-
}
|
|
1524
|
-
return config2;
|
|
1525
|
-
} catch (error) {
|
|
1526
|
-
throw new Error(
|
|
1527
|
-
`Failed to parse MySQL DSN: ${error instanceof Error ? error.message : String(error)}`
|
|
1528
|
-
);
|
|
1529
|
-
}
|
|
1530
|
-
}
|
|
1531
|
-
getSampleDSN() {
|
|
1532
|
-
return "mysql://root:password@localhost:3306/mysql?sslmode=require";
|
|
1533
|
-
}
|
|
1534
|
-
isValidDSN(dsn) {
|
|
1535
|
-
try {
|
|
1536
|
-
return dsn.startsWith("mysql://");
|
|
1537
|
-
} catch (error) {
|
|
1538
|
-
return false;
|
|
1539
|
-
}
|
|
1540
|
-
}
|
|
1541
|
-
};
|
|
1542
|
-
var MySQLConnector = class _MySQLConnector {
|
|
1543
|
-
constructor() {
|
|
1544
|
-
this.id = "mysql";
|
|
1545
|
-
this.name = "MySQL";
|
|
1546
|
-
this.dsnParser = new MySQLDSNParser();
|
|
1547
|
-
this.pool = null;
|
|
1548
|
-
// Source ID is set by ConnectorManager after cloning
|
|
1549
|
-
this.sourceId = "default";
|
|
1550
|
-
}
|
|
1551
|
-
getId() {
|
|
1552
|
-
return this.sourceId;
|
|
1553
|
-
}
|
|
1554
|
-
clone() {
|
|
1555
|
-
return new _MySQLConnector();
|
|
1556
|
-
}
|
|
1557
|
-
async connect(dsn, initScript, config) {
|
|
1558
|
-
try {
|
|
1559
|
-
const connectionOptions = await this.dsnParser.parse(dsn, config);
|
|
1560
|
-
this.pool = mysql.createPool(connectionOptions);
|
|
1561
|
-
if (config?.queryTimeoutSeconds !== void 0) {
|
|
1562
|
-
this.queryTimeoutMs = config.queryTimeoutSeconds * 1e3;
|
|
1563
|
-
}
|
|
1564
|
-
const [rows] = await this.pool.query("SELECT 1");
|
|
1565
|
-
} catch (err) {
|
|
1566
|
-
console.error("Failed to connect to MySQL database:", err);
|
|
1567
|
-
throw err;
|
|
1568
|
-
}
|
|
1569
|
-
}
|
|
1570
|
-
async disconnect() {
|
|
1571
|
-
if (this.pool) {
|
|
1572
|
-
await this.pool.end();
|
|
1573
|
-
this.pool = null;
|
|
1574
|
-
}
|
|
1575
|
-
}
|
|
1576
|
-
async getSchemas() {
|
|
1577
|
-
if (!this.pool) {
|
|
1578
|
-
throw new Error("Not connected to database");
|
|
1579
|
-
}
|
|
1580
|
-
try {
|
|
1581
|
-
const [rows] = await this.pool.query(`
|
|
1582
|
-
SELECT SCHEMA_NAME
|
|
1583
|
-
FROM INFORMATION_SCHEMA.SCHEMATA
|
|
1584
|
-
ORDER BY SCHEMA_NAME
|
|
1585
|
-
`);
|
|
1586
|
-
return rows.map((row) => row.SCHEMA_NAME);
|
|
1587
|
-
} catch (error) {
|
|
1588
|
-
console.error("Error getting schemas:", error);
|
|
1589
|
-
throw error;
|
|
1590
|
-
}
|
|
1591
|
-
}
|
|
1592
|
-
async getTables(schema) {
|
|
1593
|
-
if (!this.pool) {
|
|
1594
|
-
throw new Error("Not connected to database");
|
|
1595
|
-
}
|
|
1596
|
-
try {
|
|
1597
|
-
const schemaClause = schema ? "WHERE TABLE_SCHEMA = ?" : "WHERE TABLE_SCHEMA = DATABASE()";
|
|
1598
|
-
const queryParams = schema ? [schema] : [];
|
|
1599
|
-
const [rows] = await this.pool.query(
|
|
1600
|
-
`
|
|
1601
|
-
SELECT TABLE_NAME
|
|
1602
|
-
FROM INFORMATION_SCHEMA.TABLES
|
|
1603
|
-
${schemaClause}
|
|
1604
|
-
ORDER BY TABLE_NAME
|
|
1605
|
-
`,
|
|
1606
|
-
queryParams
|
|
1607
|
-
);
|
|
1608
|
-
return rows.map((row) => row.TABLE_NAME);
|
|
1609
|
-
} catch (error) {
|
|
1610
|
-
console.error("Error getting tables:", error);
|
|
1611
|
-
throw error;
|
|
1612
|
-
}
|
|
1613
|
-
}
|
|
1614
|
-
async tableExists(tableName, schema) {
|
|
1615
|
-
if (!this.pool) {
|
|
1616
|
-
throw new Error("Not connected to database");
|
|
1617
|
-
}
|
|
1618
|
-
try {
|
|
1619
|
-
const schemaClause = schema ? "WHERE TABLE_SCHEMA = ?" : "WHERE TABLE_SCHEMA = DATABASE()";
|
|
1620
|
-
const queryParams = schema ? [schema, tableName] : [tableName];
|
|
1621
|
-
const [rows] = await this.pool.query(
|
|
1622
|
-
`
|
|
1623
|
-
SELECT COUNT(*) AS COUNT
|
|
1624
|
-
FROM INFORMATION_SCHEMA.TABLES
|
|
1625
|
-
${schemaClause}
|
|
1626
|
-
AND TABLE_NAME = ?
|
|
1627
|
-
`,
|
|
1628
|
-
queryParams
|
|
1629
|
-
);
|
|
1630
|
-
return rows[0].COUNT > 0;
|
|
1631
|
-
} catch (error) {
|
|
1632
|
-
console.error("Error checking if table exists:", error);
|
|
1633
|
-
throw error;
|
|
1634
|
-
}
|
|
1635
|
-
}
|
|
1636
|
-
async getTableIndexes(tableName, schema) {
|
|
1637
|
-
if (!this.pool) {
|
|
1638
|
-
throw new Error("Not connected to database");
|
|
1639
|
-
}
|
|
1640
|
-
try {
|
|
1641
|
-
const schemaClause = schema ? "TABLE_SCHEMA = ?" : "TABLE_SCHEMA = DATABASE()";
|
|
1642
|
-
const queryParams = schema ? [schema, tableName] : [tableName];
|
|
1643
|
-
const [indexRows] = await this.pool.query(
|
|
1644
|
-
`
|
|
1645
|
-
SELECT
|
|
1646
|
-
INDEX_NAME,
|
|
1647
|
-
COLUMN_NAME,
|
|
1648
|
-
NON_UNIQUE,
|
|
1649
|
-
SEQ_IN_INDEX
|
|
1650
|
-
FROM
|
|
1651
|
-
INFORMATION_SCHEMA.STATISTICS
|
|
1652
|
-
WHERE
|
|
1653
|
-
${schemaClause}
|
|
1654
|
-
AND TABLE_NAME = ?
|
|
1655
|
-
ORDER BY
|
|
1656
|
-
INDEX_NAME,
|
|
1657
|
-
SEQ_IN_INDEX
|
|
1658
|
-
`,
|
|
1659
|
-
queryParams
|
|
1660
|
-
);
|
|
1661
|
-
const indexMap = /* @__PURE__ */ new Map();
|
|
1662
|
-
for (const row of indexRows) {
|
|
1663
|
-
const indexName = row.INDEX_NAME;
|
|
1664
|
-
const columnName = row.COLUMN_NAME;
|
|
1665
|
-
const isUnique = row.NON_UNIQUE === 0;
|
|
1666
|
-
const isPrimary = indexName === "PRIMARY";
|
|
1667
|
-
if (!indexMap.has(indexName)) {
|
|
1668
|
-
indexMap.set(indexName, {
|
|
1669
|
-
columns: [],
|
|
1670
|
-
is_unique: isUnique,
|
|
1671
|
-
is_primary: isPrimary
|
|
1672
|
-
});
|
|
1673
|
-
}
|
|
1674
|
-
const indexInfo = indexMap.get(indexName);
|
|
1675
|
-
indexInfo.columns.push(columnName);
|
|
1676
|
-
}
|
|
1677
|
-
const results = [];
|
|
1678
|
-
indexMap.forEach((indexInfo, indexName) => {
|
|
1679
|
-
results.push({
|
|
1680
|
-
index_name: indexName,
|
|
1681
|
-
column_names: indexInfo.columns,
|
|
1682
|
-
is_unique: indexInfo.is_unique,
|
|
1683
|
-
is_primary: indexInfo.is_primary
|
|
1684
|
-
});
|
|
1685
|
-
});
|
|
1686
|
-
return results;
|
|
1687
|
-
} catch (error) {
|
|
1688
|
-
console.error("Error getting table indexes:", error);
|
|
1689
|
-
throw error;
|
|
1690
|
-
}
|
|
1691
|
-
}
|
|
1692
|
-
async getTableSchema(tableName, schema) {
|
|
1693
|
-
if (!this.pool) {
|
|
1694
|
-
throw new Error("Not connected to database");
|
|
1695
|
-
}
|
|
1696
|
-
try {
|
|
1697
|
-
const schemaClause = schema ? "WHERE TABLE_SCHEMA = ?" : "WHERE TABLE_SCHEMA = DATABASE()";
|
|
1698
|
-
const queryParams = schema ? [schema, tableName] : [tableName];
|
|
1699
|
-
const [rows] = await this.pool.query(
|
|
1700
|
-
`
|
|
1701
|
-
SELECT
|
|
1702
|
-
COLUMN_NAME as column_name,
|
|
1703
|
-
DATA_TYPE as data_type,
|
|
1704
|
-
IS_NULLABLE as is_nullable,
|
|
1705
|
-
COLUMN_DEFAULT as column_default,
|
|
1706
|
-
COLUMN_COMMENT as description
|
|
1707
|
-
FROM INFORMATION_SCHEMA.COLUMNS
|
|
1708
|
-
${schemaClause}
|
|
1709
|
-
AND TABLE_NAME = ?
|
|
1710
|
-
ORDER BY ORDINAL_POSITION
|
|
1711
|
-
`,
|
|
1712
|
-
queryParams
|
|
1713
|
-
);
|
|
1714
|
-
return rows.map((row) => ({
|
|
1715
|
-
...row,
|
|
1716
|
-
description: row.description || null
|
|
1717
|
-
}));
|
|
1718
|
-
} catch (error) {
|
|
1719
|
-
console.error("Error getting table schema:", error);
|
|
1720
|
-
throw error;
|
|
1721
|
-
}
|
|
1722
|
-
}
|
|
1723
|
-
async getTableComment(tableName, schema) {
|
|
1724
|
-
if (!this.pool) {
|
|
1725
|
-
throw new Error("Not connected to database");
|
|
1726
|
-
}
|
|
1727
|
-
try {
|
|
1728
|
-
const schemaClause = schema ? "WHERE TABLE_SCHEMA = ?" : "WHERE TABLE_SCHEMA = DATABASE()";
|
|
1729
|
-
const queryParams = schema ? [schema, tableName] : [tableName];
|
|
1730
|
-
const [rows] = await this.pool.query(
|
|
1731
|
-
`
|
|
1732
|
-
SELECT TABLE_COMMENT
|
|
1733
|
-
FROM INFORMATION_SCHEMA.TABLES
|
|
1734
|
-
${schemaClause}
|
|
1735
|
-
AND TABLE_NAME = ?
|
|
1736
|
-
`,
|
|
1737
|
-
queryParams
|
|
1738
|
-
);
|
|
1739
|
-
if (rows.length > 0) {
|
|
1740
|
-
return rows[0].TABLE_COMMENT || null;
|
|
1741
|
-
}
|
|
1742
|
-
return null;
|
|
1743
|
-
} catch (error) {
|
|
1744
|
-
return null;
|
|
1745
|
-
}
|
|
1746
|
-
}
|
|
1747
|
-
async getStoredProcedures(schema, routineType) {
|
|
1748
|
-
if (!this.pool) {
|
|
1749
|
-
throw new Error("Not connected to database");
|
|
1750
|
-
}
|
|
1751
|
-
try {
|
|
1752
|
-
const schemaClause = schema ? "WHERE ROUTINE_SCHEMA = ?" : "WHERE ROUTINE_SCHEMA = DATABASE()";
|
|
1753
|
-
const queryParams = schema ? [schema] : [];
|
|
1754
|
-
let typeFilter = "";
|
|
1755
|
-
if (routineType === "function") {
|
|
1756
|
-
typeFilter = " AND ROUTINE_TYPE = 'FUNCTION'";
|
|
1757
|
-
} else if (routineType === "procedure") {
|
|
1758
|
-
typeFilter = " AND ROUTINE_TYPE = 'PROCEDURE'";
|
|
1759
|
-
}
|
|
1760
|
-
const [rows] = await this.pool.query(
|
|
1761
|
-
`
|
|
1762
|
-
SELECT ROUTINE_NAME
|
|
1763
|
-
FROM INFORMATION_SCHEMA.ROUTINES
|
|
1764
|
-
${schemaClause}${typeFilter}
|
|
1765
|
-
ORDER BY ROUTINE_NAME
|
|
1766
|
-
`,
|
|
1767
|
-
queryParams
|
|
1768
|
-
);
|
|
1769
|
-
return rows.map((row) => row.ROUTINE_NAME);
|
|
1770
|
-
} catch (error) {
|
|
1771
|
-
console.error("Error getting stored procedures:", error);
|
|
1772
|
-
throw error;
|
|
1773
|
-
}
|
|
1774
|
-
}
|
|
1775
|
-
async getStoredProcedureDetail(procedureName, schema) {
|
|
1776
|
-
if (!this.pool) {
|
|
1777
|
-
throw new Error("Not connected to database");
|
|
1778
|
-
}
|
|
1779
|
-
try {
|
|
1780
|
-
const schemaClause = schema ? "WHERE r.ROUTINE_SCHEMA = ?" : "WHERE r.ROUTINE_SCHEMA = DATABASE()";
|
|
1781
|
-
const queryParams = schema ? [schema, procedureName] : [procedureName];
|
|
1782
|
-
const [rows] = await this.pool.query(
|
|
1783
|
-
`
|
|
1784
|
-
SELECT
|
|
1785
|
-
r.ROUTINE_NAME AS procedure_name,
|
|
1786
|
-
CASE
|
|
1787
|
-
WHEN r.ROUTINE_TYPE = 'PROCEDURE' THEN 'procedure'
|
|
1788
|
-
ELSE 'function'
|
|
1789
|
-
END AS procedure_type,
|
|
1790
|
-
LOWER(r.ROUTINE_TYPE) AS routine_type,
|
|
1791
|
-
r.ROUTINE_DEFINITION,
|
|
1792
|
-
r.DTD_IDENTIFIER AS return_type,
|
|
1793
|
-
(
|
|
1794
|
-
SELECT GROUP_CONCAT(
|
|
1795
|
-
CONCAT(p.PARAMETER_NAME, ' ', p.PARAMETER_MODE, ' ', p.DATA_TYPE)
|
|
1796
|
-
ORDER BY p.ORDINAL_POSITION
|
|
1797
|
-
SEPARATOR ', '
|
|
1798
|
-
)
|
|
1799
|
-
FROM INFORMATION_SCHEMA.PARAMETERS p
|
|
1800
|
-
WHERE p.SPECIFIC_SCHEMA = r.ROUTINE_SCHEMA
|
|
1801
|
-
AND p.SPECIFIC_NAME = r.ROUTINE_NAME
|
|
1802
|
-
AND p.PARAMETER_NAME IS NOT NULL
|
|
1803
|
-
) AS parameter_list
|
|
1804
|
-
FROM INFORMATION_SCHEMA.ROUTINES r
|
|
1805
|
-
${schemaClause}
|
|
1806
|
-
AND r.ROUTINE_NAME = ?
|
|
1807
|
-
`,
|
|
1808
|
-
queryParams
|
|
1809
|
-
);
|
|
1810
|
-
if (rows.length === 0) {
|
|
1811
|
-
const schemaName = schema || "current schema";
|
|
1812
|
-
throw new Error(`Stored procedure '${procedureName}' not found in ${schemaName}`);
|
|
1813
|
-
}
|
|
1814
|
-
const procedure = rows[0];
|
|
1815
|
-
let definition = procedure.ROUTINE_DEFINITION;
|
|
1816
|
-
try {
|
|
1817
|
-
const schemaValue = schema || await this.getCurrentSchema();
|
|
1818
|
-
if (procedure.procedure_type === "procedure") {
|
|
1819
|
-
try {
|
|
1820
|
-
const [defRows] = await this.pool.query(`
|
|
1821
|
-
SHOW CREATE PROCEDURE ${schemaValue}.${procedureName}
|
|
1822
|
-
`);
|
|
1823
|
-
if (defRows && defRows.length > 0) {
|
|
1824
|
-
definition = defRows[0]["Create Procedure"];
|
|
1825
|
-
}
|
|
1826
|
-
} catch (err) {
|
|
1827
|
-
console.error(`Error getting procedure definition with SHOW CREATE: ${err}`);
|
|
1828
|
-
}
|
|
1829
|
-
} else {
|
|
1830
|
-
try {
|
|
1831
|
-
const [defRows] = await this.pool.query(`
|
|
1832
|
-
SHOW CREATE FUNCTION ${schemaValue}.${procedureName}
|
|
1833
|
-
`);
|
|
1834
|
-
if (defRows && defRows.length > 0) {
|
|
1835
|
-
definition = defRows[0]["Create Function"];
|
|
1836
|
-
}
|
|
1837
|
-
} catch (innerErr) {
|
|
1838
|
-
console.error(`Error getting function definition with SHOW CREATE: ${innerErr}`);
|
|
1839
|
-
}
|
|
1840
|
-
}
|
|
1841
|
-
if (!definition) {
|
|
1842
|
-
const [bodyRows] = await this.pool.query(
|
|
1843
|
-
`
|
|
1844
|
-
SELECT ROUTINE_DEFINITION, ROUTINE_BODY
|
|
1845
|
-
FROM INFORMATION_SCHEMA.ROUTINES
|
|
1846
|
-
WHERE ROUTINE_SCHEMA = ? AND ROUTINE_NAME = ?
|
|
1847
|
-
`,
|
|
1848
|
-
[schemaValue, procedureName]
|
|
1849
|
-
);
|
|
1850
|
-
if (bodyRows && bodyRows.length > 0) {
|
|
1851
|
-
if (bodyRows[0].ROUTINE_DEFINITION) {
|
|
1852
|
-
definition = bodyRows[0].ROUTINE_DEFINITION;
|
|
1853
|
-
} else if (bodyRows[0].ROUTINE_BODY) {
|
|
1854
|
-
definition = bodyRows[0].ROUTINE_BODY;
|
|
1855
|
-
}
|
|
1856
|
-
}
|
|
1857
|
-
}
|
|
1858
|
-
} catch (error) {
|
|
1859
|
-
console.error(`Error getting procedure/function details: ${error}`);
|
|
1860
|
-
}
|
|
1861
|
-
return {
|
|
1862
|
-
procedure_name: procedure.procedure_name,
|
|
1863
|
-
procedure_type: procedure.procedure_type,
|
|
1864
|
-
language: "sql",
|
|
1865
|
-
// MySQL procedures are generally in SQL
|
|
1866
|
-
parameter_list: procedure.parameter_list || "",
|
|
1867
|
-
return_type: procedure.routine_type === "function" ? procedure.return_type : void 0,
|
|
1868
|
-
definition: definition || void 0
|
|
1869
|
-
};
|
|
1870
|
-
} catch (error) {
|
|
1871
|
-
console.error("Error getting stored procedure detail:", error);
|
|
1872
|
-
throw error;
|
|
1873
|
-
}
|
|
1874
|
-
}
|
|
1875
|
-
// Helper method to get current schema (database) name
|
|
1876
|
-
async getCurrentSchema() {
|
|
1877
|
-
const [rows] = await this.pool.query("SELECT DATABASE() AS DB");
|
|
1878
|
-
return rows[0].DB;
|
|
1879
|
-
}
|
|
1880
|
-
async executeSQL(sql2, options, parameters) {
|
|
1881
|
-
if (!this.pool) {
|
|
1882
|
-
throw new Error("Not connected to database");
|
|
1883
|
-
}
|
|
1884
|
-
const conn = await this.pool.getConnection();
|
|
1885
|
-
try {
|
|
1886
|
-
let processedSQL = sql2;
|
|
1887
|
-
if (options.maxRows) {
|
|
1888
|
-
const statements = splitSQLStatements(sql2, "mysql");
|
|
1889
|
-
const processedStatements = statements.map(
|
|
1890
|
-
(statement) => SQLRowLimiter.applyMaxRows(statement, options.maxRows)
|
|
1891
|
-
);
|
|
1892
|
-
processedSQL = processedStatements.join("; ");
|
|
1893
|
-
if (sql2.trim().endsWith(";")) {
|
|
1894
|
-
processedSQL += ";";
|
|
1895
|
-
}
|
|
1896
|
-
}
|
|
1897
|
-
let results;
|
|
1898
|
-
if (parameters && parameters.length > 0) {
|
|
1899
|
-
try {
|
|
1900
|
-
results = await conn.query({ sql: processedSQL, timeout: this.queryTimeoutMs }, parameters);
|
|
1901
|
-
} catch (error) {
|
|
1902
|
-
console.error(`[MySQL executeSQL] ERROR: ${error.message}`);
|
|
1903
|
-
console.error(`[MySQL executeSQL] SQL: ${processedSQL}`);
|
|
1904
|
-
console.error(`[MySQL executeSQL] Parameters: ${JSON.stringify(parameters)}`);
|
|
1905
|
-
throw error;
|
|
1906
|
-
}
|
|
1907
|
-
} else {
|
|
1908
|
-
results = await conn.query({ sql: processedSQL, timeout: this.queryTimeoutMs });
|
|
1909
|
-
}
|
|
1910
|
-
const [firstResult] = results;
|
|
1911
|
-
const rows = parseQueryResults(firstResult);
|
|
1912
|
-
const rowCount = extractAffectedRows(firstResult);
|
|
1913
|
-
return { rows, rowCount };
|
|
1914
|
-
} catch (error) {
|
|
1915
|
-
console.error("Error executing query:", error);
|
|
1916
|
-
throw error;
|
|
1917
|
-
} finally {
|
|
1918
|
-
conn.release();
|
|
1919
|
-
}
|
|
1920
|
-
}
|
|
1921
|
-
};
|
|
1922
|
-
var mysqlConnector = new MySQLConnector();
|
|
1923
|
-
ConnectorRegistry.register(mysqlConnector);
|
|
1924
|
-
|
|
1925
|
-
// src/connectors/mariadb/index.ts
|
|
1926
|
-
import * as mariadb from "mariadb";
|
|
1927
|
-
var MariadbDSNParser = class {
|
|
1928
|
-
async parse(dsn, config) {
|
|
1929
|
-
const connectionTimeoutSeconds = config?.connectionTimeoutSeconds;
|
|
1930
|
-
const queryTimeoutSeconds = config?.queryTimeoutSeconds;
|
|
1931
|
-
if (!this.isValidDSN(dsn)) {
|
|
1932
|
-
const obfuscatedDSN = obfuscateDSNPassword(dsn);
|
|
1933
|
-
const expectedFormat = this.getSampleDSN();
|
|
1934
|
-
throw new Error(
|
|
1935
|
-
`Invalid MariaDB DSN format.
|
|
1936
|
-
Provided: ${obfuscatedDSN}
|
|
1937
|
-
Expected: ${expectedFormat}`
|
|
1938
|
-
);
|
|
1939
|
-
}
|
|
1940
|
-
try {
|
|
1941
|
-
const url = new SafeURL(dsn);
|
|
1942
|
-
const connectionConfig = {
|
|
1943
|
-
host: url.hostname,
|
|
1944
|
-
port: url.port ? parseInt(url.port) : 3306,
|
|
1945
|
-
database: url.pathname ? url.pathname.substring(1) : "",
|
|
1946
|
-
// Remove leading '/' if exists
|
|
1947
|
-
user: url.username,
|
|
1948
|
-
password: url.password,
|
|
1949
|
-
multipleStatements: true,
|
|
1950
|
-
// Enable native multi-statement support
|
|
1951
|
-
...connectionTimeoutSeconds !== void 0 && {
|
|
1952
|
-
connectTimeout: connectionTimeoutSeconds * 1e3
|
|
1953
|
-
},
|
|
1954
|
-
...queryTimeoutSeconds !== void 0 && {
|
|
1955
|
-
queryTimeout: queryTimeoutSeconds * 1e3
|
|
1956
|
-
}
|
|
1957
|
-
};
|
|
1958
|
-
url.forEachSearchParam((value, key) => {
|
|
1959
|
-
if (key === "sslmode") {
|
|
1960
|
-
if (value === "disable") {
|
|
1961
|
-
connectionConfig.ssl = void 0;
|
|
1962
|
-
} else if (value === "require") {
|
|
1963
|
-
connectionConfig.ssl = { rejectUnauthorized: false };
|
|
1964
|
-
} else {
|
|
1965
|
-
connectionConfig.ssl = {};
|
|
1966
|
-
}
|
|
1967
|
-
}
|
|
1968
|
-
});
|
|
1969
|
-
if (url.password && url.password.includes("X-Amz-Credential")) {
|
|
1970
|
-
if (connectionConfig.ssl === void 0) {
|
|
1971
|
-
connectionConfig.ssl = { rejectUnauthorized: false };
|
|
1972
|
-
}
|
|
1973
|
-
}
|
|
1974
|
-
return connectionConfig;
|
|
1975
|
-
} catch (error) {
|
|
1976
|
-
throw new Error(
|
|
1977
|
-
`Failed to parse MariaDB DSN: ${error instanceof Error ? error.message : String(error)}`
|
|
1978
|
-
);
|
|
1979
|
-
}
|
|
1980
|
-
}
|
|
1981
|
-
getSampleDSN() {
|
|
1982
|
-
return "mariadb://root:password@localhost:3306/db?sslmode=require";
|
|
1983
|
-
}
|
|
1984
|
-
isValidDSN(dsn) {
|
|
1985
|
-
try {
|
|
1986
|
-
return dsn.startsWith("mariadb://");
|
|
1987
|
-
} catch (error) {
|
|
1988
|
-
return false;
|
|
1989
|
-
}
|
|
1990
|
-
}
|
|
1991
|
-
};
|
|
1992
|
-
var MariaDBConnector = class _MariaDBConnector {
|
|
1993
|
-
constructor() {
|
|
1994
|
-
this.id = "mariadb";
|
|
1995
|
-
this.name = "MariaDB";
|
|
1996
|
-
this.dsnParser = new MariadbDSNParser();
|
|
1997
|
-
this.pool = null;
|
|
1998
|
-
// Source ID is set by ConnectorManager after cloning
|
|
1999
|
-
this.sourceId = "default";
|
|
2000
|
-
}
|
|
2001
|
-
getId() {
|
|
2002
|
-
return this.sourceId;
|
|
2003
|
-
}
|
|
2004
|
-
clone() {
|
|
2005
|
-
return new _MariaDBConnector();
|
|
2006
|
-
}
|
|
2007
|
-
async connect(dsn, initScript, config) {
|
|
2008
|
-
try {
|
|
2009
|
-
const connectionConfig = await this.dsnParser.parse(dsn, config);
|
|
2010
|
-
this.pool = mariadb.createPool(connectionConfig);
|
|
2011
|
-
await this.pool.query("SELECT 1");
|
|
2012
|
-
} catch (err) {
|
|
2013
|
-
console.error("Failed to connect to MariaDB database:", err);
|
|
2014
|
-
throw err;
|
|
2015
|
-
}
|
|
2016
|
-
}
|
|
2017
|
-
async disconnect() {
|
|
2018
|
-
if (this.pool) {
|
|
2019
|
-
await this.pool.end();
|
|
2020
|
-
this.pool = null;
|
|
2021
|
-
}
|
|
2022
|
-
}
|
|
2023
|
-
async getSchemas() {
|
|
2024
|
-
if (!this.pool) {
|
|
2025
|
-
throw new Error("Not connected to database");
|
|
2026
|
-
}
|
|
2027
|
-
try {
|
|
2028
|
-
const rows = await this.pool.query(`
|
|
2029
|
-
SELECT SCHEMA_NAME
|
|
2030
|
-
FROM INFORMATION_SCHEMA.SCHEMATA
|
|
2031
|
-
ORDER BY SCHEMA_NAME
|
|
2032
|
-
`);
|
|
2033
|
-
return rows.map((row) => row.SCHEMA_NAME);
|
|
2034
|
-
} catch (error) {
|
|
2035
|
-
console.error("Error getting schemas:", error);
|
|
2036
|
-
throw error;
|
|
2037
|
-
}
|
|
2038
|
-
}
|
|
2039
|
-
async getTables(schema) {
|
|
2040
|
-
if (!this.pool) {
|
|
2041
|
-
throw new Error("Not connected to database");
|
|
2042
|
-
}
|
|
2043
|
-
try {
|
|
2044
|
-
const schemaClause = schema ? "WHERE TABLE_SCHEMA = ?" : "WHERE TABLE_SCHEMA = DATABASE()";
|
|
2045
|
-
const queryParams = schema ? [schema] : [];
|
|
2046
|
-
const rows = await this.pool.query(
|
|
2047
|
-
`
|
|
2048
|
-
SELECT TABLE_NAME
|
|
2049
|
-
FROM INFORMATION_SCHEMA.TABLES
|
|
2050
|
-
${schemaClause}
|
|
2051
|
-
ORDER BY TABLE_NAME
|
|
2052
|
-
`,
|
|
2053
|
-
queryParams
|
|
2054
|
-
);
|
|
2055
|
-
return rows.map((row) => row.TABLE_NAME);
|
|
2056
|
-
} catch (error) {
|
|
2057
|
-
console.error("Error getting tables:", error);
|
|
2058
|
-
throw error;
|
|
2059
|
-
}
|
|
2060
|
-
}
|
|
2061
|
-
async tableExists(tableName, schema) {
|
|
2062
|
-
if (!this.pool) {
|
|
2063
|
-
throw new Error("Not connected to database");
|
|
2064
|
-
}
|
|
2065
|
-
try {
|
|
2066
|
-
const schemaClause = schema ? "WHERE TABLE_SCHEMA = ?" : "WHERE TABLE_SCHEMA = DATABASE()";
|
|
2067
|
-
const queryParams = schema ? [schema, tableName] : [tableName];
|
|
2068
|
-
const rows = await this.pool.query(
|
|
2069
|
-
`
|
|
2070
|
-
SELECT COUNT(*) AS COUNT
|
|
2071
|
-
FROM INFORMATION_SCHEMA.TABLES
|
|
2072
|
-
${schemaClause}
|
|
2073
|
-
AND TABLE_NAME = ?
|
|
2074
|
-
`,
|
|
2075
|
-
queryParams
|
|
2076
|
-
);
|
|
2077
|
-
return rows[0].COUNT > 0;
|
|
2078
|
-
} catch (error) {
|
|
2079
|
-
console.error("Error checking if table exists:", error);
|
|
2080
|
-
throw error;
|
|
2081
|
-
}
|
|
2082
|
-
}
|
|
2083
|
-
async getTableIndexes(tableName, schema) {
|
|
2084
|
-
if (!this.pool) {
|
|
2085
|
-
throw new Error("Not connected to database");
|
|
2086
|
-
}
|
|
2087
|
-
try {
|
|
2088
|
-
const schemaClause = schema ? "TABLE_SCHEMA = ?" : "TABLE_SCHEMA = DATABASE()";
|
|
2089
|
-
const queryParams = schema ? [schema, tableName] : [tableName];
|
|
2090
|
-
const indexRows = await this.pool.query(
|
|
2091
|
-
`
|
|
2092
|
-
SELECT
|
|
2093
|
-
INDEX_NAME,
|
|
2094
|
-
COLUMN_NAME,
|
|
2095
|
-
NON_UNIQUE,
|
|
2096
|
-
SEQ_IN_INDEX
|
|
2097
|
-
FROM
|
|
2098
|
-
INFORMATION_SCHEMA.STATISTICS
|
|
2099
|
-
WHERE
|
|
2100
|
-
${schemaClause}
|
|
2101
|
-
AND TABLE_NAME = ?
|
|
2102
|
-
ORDER BY
|
|
2103
|
-
INDEX_NAME,
|
|
2104
|
-
SEQ_IN_INDEX
|
|
2105
|
-
`,
|
|
2106
|
-
queryParams
|
|
2107
|
-
);
|
|
2108
|
-
const indexMap = /* @__PURE__ */ new Map();
|
|
2109
|
-
for (const row of indexRows) {
|
|
2110
|
-
const indexName = row.INDEX_NAME;
|
|
2111
|
-
const columnName = row.COLUMN_NAME;
|
|
2112
|
-
const isUnique = row.NON_UNIQUE === 0;
|
|
2113
|
-
const isPrimary = indexName === "PRIMARY";
|
|
2114
|
-
if (!indexMap.has(indexName)) {
|
|
2115
|
-
indexMap.set(indexName, {
|
|
2116
|
-
columns: [],
|
|
2117
|
-
is_unique: isUnique,
|
|
2118
|
-
is_primary: isPrimary
|
|
2119
|
-
});
|
|
2120
|
-
}
|
|
2121
|
-
const indexInfo = indexMap.get(indexName);
|
|
2122
|
-
indexInfo.columns.push(columnName);
|
|
2123
|
-
}
|
|
2124
|
-
const results = [];
|
|
2125
|
-
indexMap.forEach((indexInfo, indexName) => {
|
|
2126
|
-
results.push({
|
|
2127
|
-
index_name: indexName,
|
|
2128
|
-
column_names: indexInfo.columns,
|
|
2129
|
-
is_unique: indexInfo.is_unique,
|
|
2130
|
-
is_primary: indexInfo.is_primary
|
|
2131
|
-
});
|
|
2132
|
-
});
|
|
2133
|
-
return results;
|
|
2134
|
-
} catch (error) {
|
|
2135
|
-
console.error("Error getting table indexes:", error);
|
|
2136
|
-
throw error;
|
|
2137
|
-
}
|
|
2138
|
-
}
|
|
2139
|
-
async getTableSchema(tableName, schema) {
|
|
2140
|
-
if (!this.pool) {
|
|
2141
|
-
throw new Error("Not connected to database");
|
|
2142
|
-
}
|
|
2143
|
-
try {
|
|
2144
|
-
const schemaClause = schema ? "WHERE TABLE_SCHEMA = ?" : "WHERE TABLE_SCHEMA = DATABASE()";
|
|
2145
|
-
const queryParams = schema ? [schema, tableName] : [tableName];
|
|
2146
|
-
const rows = await this.pool.query(
|
|
2147
|
-
`
|
|
2148
|
-
SELECT
|
|
2149
|
-
COLUMN_NAME as column_name,
|
|
2150
|
-
DATA_TYPE as data_type,
|
|
2151
|
-
IS_NULLABLE as is_nullable,
|
|
2152
|
-
COLUMN_DEFAULT as column_default,
|
|
2153
|
-
COLUMN_COMMENT as description
|
|
2154
|
-
FROM INFORMATION_SCHEMA.COLUMNS
|
|
2155
|
-
${schemaClause}
|
|
2156
|
-
AND TABLE_NAME = ?
|
|
2157
|
-
ORDER BY ORDINAL_POSITION
|
|
2158
|
-
`,
|
|
2159
|
-
queryParams
|
|
2160
|
-
);
|
|
2161
|
-
return rows.map((row) => ({
|
|
2162
|
-
...row,
|
|
2163
|
-
description: row.description || null
|
|
2164
|
-
}));
|
|
2165
|
-
} catch (error) {
|
|
2166
|
-
console.error("Error getting table schema:", error);
|
|
2167
|
-
throw error;
|
|
2168
|
-
}
|
|
2169
|
-
}
|
|
2170
|
-
async getTableComment(tableName, schema) {
|
|
2171
|
-
if (!this.pool) {
|
|
2172
|
-
throw new Error("Not connected to database");
|
|
2173
|
-
}
|
|
2174
|
-
try {
|
|
2175
|
-
const schemaClause = schema ? "WHERE TABLE_SCHEMA = ?" : "WHERE TABLE_SCHEMA = DATABASE()";
|
|
2176
|
-
const queryParams = schema ? [schema, tableName] : [tableName];
|
|
2177
|
-
const rows = await this.pool.query(
|
|
2178
|
-
`
|
|
2179
|
-
SELECT TABLE_COMMENT
|
|
2180
|
-
FROM INFORMATION_SCHEMA.TABLES
|
|
2181
|
-
${schemaClause}
|
|
2182
|
-
AND TABLE_NAME = ?
|
|
2183
|
-
`,
|
|
2184
|
-
queryParams
|
|
2185
|
-
);
|
|
2186
|
-
if (rows.length > 0) {
|
|
2187
|
-
return rows[0].TABLE_COMMENT || null;
|
|
2188
|
-
}
|
|
2189
|
-
return null;
|
|
2190
|
-
} catch (error) {
|
|
2191
|
-
return null;
|
|
2192
|
-
}
|
|
2193
|
-
}
|
|
2194
|
-
async getStoredProcedures(schema, routineType) {
|
|
2195
|
-
if (!this.pool) {
|
|
2196
|
-
throw new Error("Not connected to database");
|
|
2197
|
-
}
|
|
2198
|
-
try {
|
|
2199
|
-
const schemaClause = schema ? "WHERE ROUTINE_SCHEMA = ?" : "WHERE ROUTINE_SCHEMA = DATABASE()";
|
|
2200
|
-
const queryParams = schema ? [schema] : [];
|
|
2201
|
-
let typeFilter = "";
|
|
2202
|
-
if (routineType === "function") {
|
|
2203
|
-
typeFilter = " AND ROUTINE_TYPE = 'FUNCTION'";
|
|
2204
|
-
} else if (routineType === "procedure") {
|
|
2205
|
-
typeFilter = " AND ROUTINE_TYPE = 'PROCEDURE'";
|
|
2206
|
-
}
|
|
2207
|
-
const rows = await this.pool.query(
|
|
2208
|
-
`
|
|
2209
|
-
SELECT ROUTINE_NAME
|
|
2210
|
-
FROM INFORMATION_SCHEMA.ROUTINES
|
|
2211
|
-
${schemaClause}${typeFilter}
|
|
2212
|
-
ORDER BY ROUTINE_NAME
|
|
2213
|
-
`,
|
|
2214
|
-
queryParams
|
|
2215
|
-
);
|
|
2216
|
-
return rows.map((row) => row.ROUTINE_NAME);
|
|
2217
|
-
} catch (error) {
|
|
2218
|
-
console.error("Error getting stored procedures:", error);
|
|
2219
|
-
throw error;
|
|
2220
|
-
}
|
|
2221
|
-
}
|
|
2222
|
-
async getStoredProcedureDetail(procedureName, schema) {
|
|
2223
|
-
if (!this.pool) {
|
|
2224
|
-
throw new Error("Not connected to database");
|
|
2225
|
-
}
|
|
2226
|
-
try {
|
|
2227
|
-
const schemaClause = schema ? "WHERE r.ROUTINE_SCHEMA = ?" : "WHERE r.ROUTINE_SCHEMA = DATABASE()";
|
|
2228
|
-
const queryParams = schema ? [schema, procedureName] : [procedureName];
|
|
2229
|
-
const rows = await this.pool.query(
|
|
2230
|
-
`
|
|
2231
|
-
SELECT
|
|
2232
|
-
r.ROUTINE_NAME AS procedure_name,
|
|
2233
|
-
CASE
|
|
2234
|
-
WHEN r.ROUTINE_TYPE = 'PROCEDURE' THEN 'procedure'
|
|
2235
|
-
ELSE 'function'
|
|
2236
|
-
END AS procedure_type,
|
|
2237
|
-
LOWER(r.ROUTINE_TYPE) AS routine_type,
|
|
2238
|
-
r.ROUTINE_DEFINITION,
|
|
2239
|
-
r.DTD_IDENTIFIER AS return_type,
|
|
2240
|
-
(
|
|
2241
|
-
SELECT GROUP_CONCAT(
|
|
2242
|
-
CONCAT(p.PARAMETER_NAME, ' ', p.PARAMETER_MODE, ' ', p.DATA_TYPE)
|
|
2243
|
-
ORDER BY p.ORDINAL_POSITION
|
|
2244
|
-
SEPARATOR ', '
|
|
2245
|
-
)
|
|
2246
|
-
FROM INFORMATION_SCHEMA.PARAMETERS p
|
|
2247
|
-
WHERE p.SPECIFIC_SCHEMA = r.ROUTINE_SCHEMA
|
|
2248
|
-
AND p.SPECIFIC_NAME = r.ROUTINE_NAME
|
|
2249
|
-
AND p.PARAMETER_NAME IS NOT NULL
|
|
2250
|
-
) AS parameter_list
|
|
2251
|
-
FROM INFORMATION_SCHEMA.ROUTINES r
|
|
2252
|
-
${schemaClause}
|
|
2253
|
-
AND r.ROUTINE_NAME = ?
|
|
2254
|
-
`,
|
|
2255
|
-
queryParams
|
|
2256
|
-
);
|
|
2257
|
-
if (rows.length === 0) {
|
|
2258
|
-
const schemaName = schema || "current schema";
|
|
2259
|
-
throw new Error(`Stored procedure '${procedureName}' not found in ${schemaName}`);
|
|
2260
|
-
}
|
|
2261
|
-
const procedure = rows[0];
|
|
2262
|
-
let definition = procedure.ROUTINE_DEFINITION;
|
|
2263
|
-
try {
|
|
2264
|
-
const schemaValue = schema || await this.getCurrentSchema();
|
|
2265
|
-
if (procedure.procedure_type === "procedure") {
|
|
2266
|
-
try {
|
|
2267
|
-
const defRows = await this.pool.query(`
|
|
2268
|
-
SHOW CREATE PROCEDURE ${schemaValue}.${procedureName}
|
|
2269
|
-
`);
|
|
2270
|
-
if (defRows && defRows.length > 0) {
|
|
2271
|
-
definition = defRows[0]["Create Procedure"];
|
|
2272
|
-
}
|
|
2273
|
-
} catch (err) {
|
|
2274
|
-
console.error(`Error getting procedure definition with SHOW CREATE: ${err}`);
|
|
2275
|
-
}
|
|
2276
|
-
} else {
|
|
2277
|
-
try {
|
|
2278
|
-
const defRows = await this.pool.query(`
|
|
2279
|
-
SHOW CREATE FUNCTION ${schemaValue}.${procedureName}
|
|
2280
|
-
`);
|
|
2281
|
-
if (defRows && defRows.length > 0) {
|
|
2282
|
-
definition = defRows[0]["Create Function"];
|
|
2283
|
-
}
|
|
2284
|
-
} catch (innerErr) {
|
|
2285
|
-
console.error(`Error getting function definition with SHOW CREATE: ${innerErr}`);
|
|
2286
|
-
}
|
|
2287
|
-
}
|
|
2288
|
-
if (!definition) {
|
|
2289
|
-
const bodyRows = await this.pool.query(
|
|
2290
|
-
`
|
|
2291
|
-
SELECT ROUTINE_DEFINITION, ROUTINE_BODY
|
|
2292
|
-
FROM INFORMATION_SCHEMA.ROUTINES
|
|
2293
|
-
WHERE ROUTINE_SCHEMA = ? AND ROUTINE_NAME = ?
|
|
2294
|
-
`,
|
|
2295
|
-
[schemaValue, procedureName]
|
|
2296
|
-
);
|
|
2297
|
-
if (bodyRows && bodyRows.length > 0) {
|
|
2298
|
-
if (bodyRows[0].ROUTINE_DEFINITION) {
|
|
2299
|
-
definition = bodyRows[0].ROUTINE_DEFINITION;
|
|
2300
|
-
} else if (bodyRows[0].ROUTINE_BODY) {
|
|
2301
|
-
definition = bodyRows[0].ROUTINE_BODY;
|
|
2302
|
-
}
|
|
2303
|
-
}
|
|
2304
|
-
}
|
|
2305
|
-
} catch (error) {
|
|
2306
|
-
console.error(`Error getting procedure/function details: ${error}`);
|
|
2307
|
-
}
|
|
2308
|
-
return {
|
|
2309
|
-
procedure_name: procedure.procedure_name,
|
|
2310
|
-
procedure_type: procedure.procedure_type,
|
|
2311
|
-
language: "sql",
|
|
2312
|
-
// MariaDB procedures are generally in SQL
|
|
2313
|
-
parameter_list: procedure.parameter_list || "",
|
|
2314
|
-
return_type: procedure.routine_type === "function" ? procedure.return_type : void 0,
|
|
2315
|
-
definition: definition || void 0
|
|
2316
|
-
};
|
|
2317
|
-
} catch (error) {
|
|
2318
|
-
console.error("Error getting stored procedure detail:", error);
|
|
2319
|
-
throw error;
|
|
2320
|
-
}
|
|
2321
|
-
}
|
|
2322
|
-
// Helper method to get current schema (database) name
|
|
2323
|
-
async getCurrentSchema() {
|
|
2324
|
-
const rows = await this.pool.query("SELECT DATABASE() AS DB");
|
|
2325
|
-
return rows[0].DB;
|
|
2326
|
-
}
|
|
2327
|
-
async executeSQL(sql2, options, parameters) {
|
|
2328
|
-
if (!this.pool) {
|
|
2329
|
-
throw new Error("Not connected to database");
|
|
2330
|
-
}
|
|
2331
|
-
const conn = await this.pool.getConnection();
|
|
2332
|
-
try {
|
|
2333
|
-
let processedSQL = sql2;
|
|
2334
|
-
if (options.maxRows) {
|
|
2335
|
-
const statements = splitSQLStatements(sql2, "mariadb");
|
|
2336
|
-
const processedStatements = statements.map(
|
|
2337
|
-
(statement) => SQLRowLimiter.applyMaxRows(statement, options.maxRows)
|
|
2338
|
-
);
|
|
2339
|
-
processedSQL = processedStatements.join("; ");
|
|
2340
|
-
if (sql2.trim().endsWith(";")) {
|
|
2341
|
-
processedSQL += ";";
|
|
2342
|
-
}
|
|
2343
|
-
}
|
|
2344
|
-
let results;
|
|
2345
|
-
if (parameters && parameters.length > 0) {
|
|
2346
|
-
try {
|
|
2347
|
-
results = await conn.query(processedSQL, parameters);
|
|
2348
|
-
} catch (error) {
|
|
2349
|
-
console.error(`[MariaDB executeSQL] ERROR: ${error.message}`);
|
|
2350
|
-
console.error(`[MariaDB executeSQL] SQL: ${processedSQL}`);
|
|
2351
|
-
console.error(`[MariaDB executeSQL] Parameters: ${JSON.stringify(parameters)}`);
|
|
2352
|
-
throw error;
|
|
2353
|
-
}
|
|
2354
|
-
} else {
|
|
2355
|
-
results = await conn.query(processedSQL);
|
|
2356
|
-
}
|
|
2357
|
-
const rows = parseQueryResults(results);
|
|
2358
|
-
const rowCount = extractAffectedRows(results);
|
|
2359
|
-
return { rows, rowCount };
|
|
2360
|
-
} catch (error) {
|
|
2361
|
-
console.error("Error executing query:", error);
|
|
2362
|
-
throw error;
|
|
2363
|
-
} finally {
|
|
2364
|
-
conn.release();
|
|
2365
|
-
}
|
|
2366
|
-
}
|
|
2367
|
-
};
|
|
2368
|
-
var mariadbConnector = new MariaDBConnector();
|
|
2369
|
-
ConnectorRegistry.register(mariadbConnector);
|
|
6
|
+
getToolRegistry,
|
|
7
|
+
initializeToolRegistry,
|
|
8
|
+
isDemoMode,
|
|
9
|
+
loadTomlConfig,
|
|
10
|
+
mapArgumentsToArray,
|
|
11
|
+
resolvePort,
|
|
12
|
+
resolveSourceConfigs,
|
|
13
|
+
resolveTomlConfigPath,
|
|
14
|
+
resolveTransport
|
|
15
|
+
} from "./chunk-GRGEI5QT.js";
|
|
16
|
+
import {
|
|
17
|
+
quoteQualifiedIdentifier
|
|
18
|
+
} from "./chunk-JFWX35TB.js";
|
|
19
|
+
import {
|
|
20
|
+
ConnectorRegistry,
|
|
21
|
+
getDatabaseTypeFromDSN,
|
|
22
|
+
getDefaultPortForType,
|
|
23
|
+
parseConnectionInfoFromDSN,
|
|
24
|
+
splitSQLStatements,
|
|
25
|
+
stripCommentsAndStrings
|
|
26
|
+
} from "./chunk-C7WEAPX4.js";
|
|
2370
27
|
|
|
2371
28
|
// src/server.ts
|
|
2372
29
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
@@ -2439,10 +96,10 @@ var allowedKeywords = {
|
|
|
2439
96
|
sqlite: ["select", "with", "explain", "analyze", "pragma"],
|
|
2440
97
|
sqlserver: ["select", "with", "explain", "showplan"]
|
|
2441
98
|
};
|
|
2442
|
-
function isReadOnlySQL(
|
|
2443
|
-
const cleanedSQL = stripCommentsAndStrings(
|
|
99
|
+
function isReadOnlySQL(sql, connectorType) {
|
|
100
|
+
const cleanedSQL = stripCommentsAndStrings(sql, connectorType).trim().toLowerCase();
|
|
2444
101
|
if (!cleanedSQL) {
|
|
2445
|
-
return
|
|
102
|
+
return false;
|
|
2446
103
|
}
|
|
2447
104
|
const firstWord = cleanedSQL.split(/\s+/)[0];
|
|
2448
105
|
const keywordList = allowedKeywords[connectorType] || [];
|
|
@@ -2533,13 +190,13 @@ function trackToolRequest(metadata, startTime, extra, success, error) {
|
|
|
2533
190
|
var executeSqlSchema = {
|
|
2534
191
|
sql: z.string().describe("SQL to execute (multiple statements separated by ;)")
|
|
2535
192
|
};
|
|
2536
|
-
function areAllStatementsReadOnly(
|
|
2537
|
-
const statements = splitSQLStatements(
|
|
193
|
+
function areAllStatementsReadOnly(sql, connectorType) {
|
|
194
|
+
const statements = splitSQLStatements(sql, connectorType);
|
|
2538
195
|
return statements.every((statement) => isReadOnlySQL(statement, connectorType));
|
|
2539
196
|
}
|
|
2540
197
|
function createExecuteSqlToolHandler(sourceId) {
|
|
2541
198
|
return async (args, extra) => {
|
|
2542
|
-
const { sql
|
|
199
|
+
const { sql } = args;
|
|
2543
200
|
const startTime = Date.now();
|
|
2544
201
|
const effectiveSourceId = getEffectiveSourceId(sourceId);
|
|
2545
202
|
let success = true;
|
|
@@ -2552,7 +209,7 @@ function createExecuteSqlToolHandler(sourceId) {
|
|
|
2552
209
|
const registry = getToolRegistry();
|
|
2553
210
|
const toolConfig = registry.getBuiltinToolConfig(BUILTIN_TOOL_EXECUTE_SQL, actualSourceId);
|
|
2554
211
|
const isReadonly = toolConfig?.readonly === true;
|
|
2555
|
-
if (isReadonly && !areAllStatementsReadOnly(
|
|
212
|
+
if (isReadonly && !areAllStatementsReadOnly(sql, connector.id)) {
|
|
2556
213
|
errorMessage = `Read-only mode is enabled. Only the following SQL operations are allowed: ${allowedKeywords[connector.id]?.join(", ") || "none"}`;
|
|
2557
214
|
success = false;
|
|
2558
215
|
return createToolErrorResponse(errorMessage, "READONLY_VIOLATION");
|
|
@@ -2561,7 +218,7 @@ function createExecuteSqlToolHandler(sourceId) {
|
|
|
2561
218
|
readonly: toolConfig?.readonly,
|
|
2562
219
|
maxRows: toolConfig?.max_rows
|
|
2563
220
|
};
|
|
2564
|
-
result = await connector.executeSQL(
|
|
221
|
+
result = await connector.executeSQL(sql, executeOptions);
|
|
2565
222
|
const responseData = {
|
|
2566
223
|
rows: result.rows,
|
|
2567
224
|
count: result.rowCount,
|
|
@@ -2577,7 +234,7 @@ function createExecuteSqlToolHandler(sourceId) {
|
|
|
2577
234
|
{
|
|
2578
235
|
sourceId: effectiveSourceId,
|
|
2579
236
|
toolName: effectiveSourceId === "default" ? "execute_sql" : `execute_sql_${effectiveSourceId}`,
|
|
2580
|
-
sql
|
|
237
|
+
sql
|
|
2581
238
|
},
|
|
2582
239
|
startTime,
|
|
2583
240
|
extra,
|
|
@@ -3705,7 +1362,7 @@ See documentation for more details on configuring database connections.
|
|
|
3705
1362
|
const sources = sourceConfigsData.sources;
|
|
3706
1363
|
console.error(`Configuration source: ${sourceConfigsData.source}`);
|
|
3707
1364
|
await connectorManager.connectWithSources(sources);
|
|
3708
|
-
const { initializeToolRegistry: initializeToolRegistry2 } = await import("./registry-
|
|
1365
|
+
const { initializeToolRegistry: initializeToolRegistry2 } = await import("./registry-XSMMLRC4.js");
|
|
3709
1366
|
initializeToolRegistry2({
|
|
3710
1367
|
sources: sourceConfigsData.sources,
|
|
3711
1368
|
tools: sourceConfigsData.tools
|
|
@@ -3812,11 +1469,18 @@ See documentation for more details on configuring database connections.
|
|
|
3812
1469
|
const transport = new StdioServerTransport();
|
|
3813
1470
|
await server.connect(transport);
|
|
3814
1471
|
console.error("MCP server running on stdio");
|
|
3815
|
-
|
|
1472
|
+
let isShuttingDown = false;
|
|
1473
|
+
const shutdown = async () => {
|
|
1474
|
+
if (isShuttingDown) return;
|
|
1475
|
+
isShuttingDown = true;
|
|
3816
1476
|
console.error("Shutting down...");
|
|
3817
1477
|
await transport.close();
|
|
1478
|
+
await connectorManager.disconnect();
|
|
3818
1479
|
process.exit(0);
|
|
3819
|
-
}
|
|
1480
|
+
};
|
|
1481
|
+
process.on("SIGINT", shutdown);
|
|
1482
|
+
process.on("SIGTERM", shutdown);
|
|
1483
|
+
process.stdin.on("end", shutdown);
|
|
3820
1484
|
}
|
|
3821
1485
|
} catch (err) {
|
|
3822
1486
|
console.error("Fatal error:", err);
|
|
@@ -3824,8 +1488,46 @@ See documentation for more details on configuring database connections.
|
|
|
3824
1488
|
}
|
|
3825
1489
|
}
|
|
3826
1490
|
|
|
1491
|
+
// src/utils/module-loader.ts
|
|
1492
|
+
var MISSING_MODULE_RE = /Cannot find (?:package|module) '([^']+)'/;
|
|
1493
|
+
function isDriverNotInstalled(err, driver) {
|
|
1494
|
+
if (!(err instanceof Error) || !("code" in err) || err.code !== "ERR_MODULE_NOT_FOUND") {
|
|
1495
|
+
return false;
|
|
1496
|
+
}
|
|
1497
|
+
const match = err.message.match(MISSING_MODULE_RE);
|
|
1498
|
+
if (!match) {
|
|
1499
|
+
return false;
|
|
1500
|
+
}
|
|
1501
|
+
const missingSpecifier = match[1];
|
|
1502
|
+
return missingSpecifier === driver || missingSpecifier.startsWith(`${driver}/`);
|
|
1503
|
+
}
|
|
1504
|
+
async function loadConnectors(connectorModules2) {
|
|
1505
|
+
await Promise.all(
|
|
1506
|
+
connectorModules2.map(async ({ load, name, driver }) => {
|
|
1507
|
+
try {
|
|
1508
|
+
await load();
|
|
1509
|
+
} catch (err) {
|
|
1510
|
+
if (isDriverNotInstalled(err, driver)) {
|
|
1511
|
+
console.error(
|
|
1512
|
+
`Skipping ${name} connector: driver package "${driver}" not installed.`
|
|
1513
|
+
);
|
|
1514
|
+
} else {
|
|
1515
|
+
throw err;
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
})
|
|
1519
|
+
);
|
|
1520
|
+
}
|
|
1521
|
+
|
|
3827
1522
|
// src/index.ts
|
|
3828
|
-
|
|
1523
|
+
var connectorModules = [
|
|
1524
|
+
{ load: () => import("./postgres-B7YSSZMH.js"), name: "PostgreSQL", driver: "pg" },
|
|
1525
|
+
{ load: () => import("./sqlserver-FDBRUELV.js"), name: "SQL Server", driver: "mssql" },
|
|
1526
|
+
{ load: () => import("./sqlite-FSCLCRIH.js"), name: "SQLite", driver: "better-sqlite3" },
|
|
1527
|
+
{ load: () => import("./mysql-I35IQ2GH.js"), name: "MySQL", driver: "mysql2" },
|
|
1528
|
+
{ load: () => import("./mariadb-VGTS4WXE.js"), name: "MariaDB", driver: "mariadb" }
|
|
1529
|
+
];
|
|
1530
|
+
loadConnectors(connectorModules).then(() => main()).catch((error) => {
|
|
3829
1531
|
console.error("Fatal error:", error);
|
|
3830
1532
|
process.exit(1);
|
|
3831
1533
|
});
|