@berthojoris/mcp-mysql-server 1.43.2 → 1.44.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.
Files changed (56) hide show
  1. package/CHANGELOG.md +57 -6
  2. package/DOCUMENTATIONS.md +40 -38
  3. package/README.md +26 -7
  4. package/bin/mcp-mysql.js +168 -168
  5. package/dist/cache/queryCache.js +1 -1
  6. package/dist/config/config.js +2 -1
  7. package/dist/config/featureConfig.d.ts +5 -0
  8. package/dist/config/featureConfig.js +26 -12
  9. package/dist/db/connection.d.ts +8 -1
  10. package/dist/db/connection.js +19 -14
  11. package/dist/index.js +0 -10
  12. package/dist/mcp-server.js +45 -305
  13. package/dist/security/securityLayer.d.ts +33 -5
  14. package/dist/security/securityLayer.js +211 -58
  15. package/dist/tools/aiTools.js +1 -1
  16. package/dist/tools/dataExportTools.js +8 -0
  17. package/dist/tools/queryTools.d.ts +1 -1
  18. package/dist/tools/queryTools.js +6 -7
  19. package/dist/tools/toolArgumentValidation.js +22 -22
  20. package/dist/tools/toolRegistry.d.ts +1 -1
  21. package/dist/tools/toolRegistry.js +7 -1
  22. package/dist/tools/transactionTools.js +1 -1
  23. package/manifest.json +5 -5
  24. package/package.json +86 -78
  25. package/dist/auth/authService.d.ts +0 -29
  26. package/dist/auth/authService.js +0 -114
  27. package/dist/tools/backupRestoreTools.d.ts +0 -18
  28. package/dist/tools/backupRestoreTools.js +0 -70
  29. package/dist/tools/documentationGeneratorTools.d.ts +0 -145
  30. package/dist/tools/documentationGeneratorTools.js +0 -820
  31. package/dist/tools/forecastingTools.d.ts +0 -36
  32. package/dist/tools/forecastingTools.js +0 -256
  33. package/dist/tools/functionTools.d.ts +0 -87
  34. package/dist/tools/functionTools.js +0 -358
  35. package/dist/tools/indexRecommendationTools.d.ts +0 -50
  36. package/dist/tools/indexRecommendationTools.js +0 -451
  37. package/dist/tools/intelligentQueryTools.d.ts +0 -94
  38. package/dist/tools/intelligentQueryTools.js +0 -713
  39. package/dist/tools/performanceTools.d.ts +0 -76
  40. package/dist/tools/performanceTools.js +0 -505
  41. package/dist/tools/processTools.d.ts +0 -61
  42. package/dist/tools/processTools.js +0 -181
  43. package/dist/tools/queryVisualizationTools.d.ts +0 -22
  44. package/dist/tools/queryVisualizationTools.js +0 -155
  45. package/dist/tools/schemaDesignTools.d.ts +0 -67
  46. package/dist/tools/schemaDesignTools.js +0 -359
  47. package/dist/tools/schemaPatternTools.d.ts +0 -19
  48. package/dist/tools/schemaPatternTools.js +0 -253
  49. package/dist/tools/schemaVersioningTools.d.ts +0 -138
  50. package/dist/tools/schemaVersioningTools.js +0 -1008
  51. package/dist/tools/securityAuditTools.d.ts +0 -39
  52. package/dist/tools/securityAuditTools.js +0 -319
  53. package/dist/tools/smartDiscoveryTools.d.ts +0 -163
  54. package/dist/tools/smartDiscoveryTools.js +0 -750
  55. package/dist/tools/testDataTools.d.ts +0 -26
  56. package/dist/tools/testDataTools.js +0 -325
@@ -1,1008 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.SchemaVersioningTools = void 0;
7
- const connection_1 = __importDefault(require("../db/connection"));
8
- const config_1 = require("../config/config");
9
- /**
10
- * Schema Versioning and Migrations Tools for MySQL MCP Server
11
- * Provides utilities for managing database schema versions and migrations
12
- */
13
- class SchemaVersioningTools {
14
- constructor(security) {
15
- this.migrationsTable = "_schema_migrations";
16
- this.db = connection_1.default.getInstance();
17
- this.security = security;
18
- }
19
- /**
20
- * Validate database access
21
- */
22
- validateDatabaseAccess(requestedDatabase) {
23
- const connectedDatabase = config_1.dbConfig.database;
24
- if (!connectedDatabase) {
25
- return {
26
- valid: false,
27
- database: "",
28
- error: "No database configured. Please specify a database in your connection settings.",
29
- };
30
- }
31
- if (requestedDatabase && requestedDatabase !== connectedDatabase) {
32
- return {
33
- valid: false,
34
- database: "",
35
- error: `Access denied: You are connected to '${connectedDatabase}' but requested '${requestedDatabase}'. Cross-database access is not permitted.`,
36
- };
37
- }
38
- return {
39
- valid: true,
40
- database: connectedDatabase,
41
- };
42
- }
43
- /**
44
- * Generate a migration version based on timestamp
45
- */
46
- generateVersion() {
47
- const now = new Date();
48
- return now
49
- .toISOString()
50
- .replace(/[-:T.Z]/g, "")
51
- .slice(0, 14);
52
- }
53
- /**
54
- * Escape string value for SQL
55
- */
56
- escapeValue(value) {
57
- if (value === null)
58
- return "NULL";
59
- if (typeof value === "number")
60
- return String(value);
61
- if (typeof value === "boolean")
62
- return value ? "1" : "0";
63
- if (value instanceof Date) {
64
- return `'${value.toISOString().slice(0, 19).replace("T", " ")}'`;
65
- }
66
- // Escape string
67
- const escaped = String(value)
68
- .replace(/\\/g, "\\\\")
69
- .replace(/'/g, "\\'")
70
- .replace(/"/g, '\\"')
71
- .replace(/\n/g, "\\n")
72
- .replace(/\r/g, "\\r")
73
- .replace(/\t/g, "\\t")
74
- .replace(/\0/g, "\\0");
75
- return `'${escaped}'`;
76
- }
77
- /**
78
- * Initialize the migrations tracking table if it doesn't exist
79
- */
80
- async initMigrationsTable(params) {
81
- try {
82
- const { database } = params;
83
- // Validate database access
84
- const dbValidation = this.validateDatabaseAccess(database);
85
- if (!dbValidation.valid) {
86
- return { status: "error", error: dbValidation.error };
87
- }
88
- const createTableQuery = `
89
- CREATE TABLE IF NOT EXISTS ${this.migrationsTable} (
90
- id INT AUTO_INCREMENT PRIMARY KEY,
91
- version VARCHAR(14) NOT NULL UNIQUE,
92
- name VARCHAR(255) NOT NULL,
93
- description TEXT,
94
- up_sql LONGTEXT NOT NULL,
95
- down_sql LONGTEXT,
96
- checksum VARCHAR(64),
97
- applied_at TIMESTAMP NULL DEFAULT NULL,
98
- applied_by VARCHAR(255),
99
- execution_time_ms INT,
100
- status ENUM('pending', 'applied', 'failed', 'rolled_back') DEFAULT 'pending',
101
- error_message TEXT,
102
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
103
- INDEX idx_version (version),
104
- INDEX idx_status (status),
105
- INDEX idx_applied_at (applied_at)
106
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
107
- `;
108
- await this.db.query(createTableQuery);
109
- return {
110
- status: "success",
111
- data: {
112
- message: `Migrations table '${this.migrationsTable}' initialized successfully`,
113
- table_name: this.migrationsTable,
114
- },
115
- };
116
- }
117
- catch (error) {
118
- return {
119
- status: "error",
120
- error: error.message,
121
- };
122
- }
123
- }
124
- /**
125
- * Create a new migration entry
126
- */
127
- async createMigration(params) {
128
- try {
129
- const { name, up_sql, down_sql, description, version, database } = params;
130
- // Validate database access
131
- const dbValidation = this.validateDatabaseAccess(database);
132
- if (!dbValidation.valid) {
133
- return { status: "error", error: dbValidation.error };
134
- }
135
- // Validate name
136
- if (!name || name.trim().length === 0) {
137
- return { status: "error", error: "Migration name is required" };
138
- }
139
- if (!up_sql || up_sql.trim().length === 0) {
140
- return { status: "error", error: "up_sql is required for migration" };
141
- }
142
- // Ensure migrations table exists
143
- await this.initMigrationsTable({ database });
144
- // Generate version if not provided
145
- const migrationVersion = version || this.generateVersion();
146
- // Generate checksum for the up_sql
147
- const checksum = this.generateChecksum(up_sql);
148
- // Check if version already exists
149
- const existingQuery = `SELECT id FROM ${this.migrationsTable} WHERE version = ?`;
150
- const existing = await this.db.query(existingQuery, [
151
- migrationVersion,
152
- ]);
153
- if (existing.length > 0) {
154
- return {
155
- status: "error",
156
- error: `Migration version '${migrationVersion}' already exists`,
157
- };
158
- }
159
- // Insert the migration
160
- const insertQuery = `
161
- INSERT INTO ${this.migrationsTable}
162
- (version, name, description, up_sql, down_sql, checksum, status)
163
- VALUES (?, ?, ?, ?, ?, ?, 'pending')
164
- `;
165
- await this.db.query(insertQuery, [
166
- migrationVersion,
167
- name.trim(),
168
- description || null,
169
- up_sql,
170
- down_sql || null,
171
- checksum,
172
- ]);
173
- return {
174
- status: "success",
175
- data: {
176
- message: `Migration '${name}' created successfully`,
177
- version: migrationVersion,
178
- name: name.trim(),
179
- checksum,
180
- status: "pending",
181
- },
182
- };
183
- }
184
- catch (error) {
185
- return {
186
- status: "error",
187
- error: error.message,
188
- };
189
- }
190
- }
191
- /**
192
- * Generate a simple checksum for SQL content
193
- */
194
- generateChecksum(sql) {
195
- let hash = 0;
196
- const str = sql.trim();
197
- for (let i = 0; i < str.length; i++) {
198
- const char = str.charCodeAt(i);
199
- hash = (hash << 5) - hash + char;
200
- hash = hash & hash; // Convert to 32bit integer
201
- }
202
- return Math.abs(hash).toString(16).padStart(8, "0");
203
- }
204
- /**
205
- * Apply pending migrations
206
- */
207
- async applyMigrations(params) {
208
- try {
209
- const { target_version, dry_run = false, database } = params;
210
- // Validate database access
211
- const dbValidation = this.validateDatabaseAccess(database);
212
- if (!dbValidation.valid) {
213
- return { status: "error", error: dbValidation.error };
214
- }
215
- // Ensure migrations table exists
216
- await this.initMigrationsTable({ database });
217
- let queryCount = 1;
218
- // Get pending migrations
219
- let pendingQuery = `
220
- SELECT id, version, name, up_sql, checksum
221
- FROM ${this.migrationsTable}
222
- WHERE status = 'pending'
223
- `;
224
- if (target_version) {
225
- pendingQuery += ` AND version <= ?`;
226
- }
227
- pendingQuery += ` ORDER BY version ASC`;
228
- const pendingMigrations = target_version
229
- ? await this.db.query(pendingQuery, [target_version])
230
- : await this.db.query(pendingQuery);
231
- queryCount++;
232
- if (pendingMigrations.length === 0) {
233
- return {
234
- status: "success",
235
- data: {
236
- message: "No pending migrations to apply",
237
- applied_count: 0,
238
- migrations: [],
239
- },
240
- };
241
- }
242
- if (dry_run) {
243
- return {
244
- status: "success",
245
- data: {
246
- message: `Dry run: ${pendingMigrations.length} migration(s) would be applied`,
247
- dry_run: true,
248
- migrations: pendingMigrations.map((m) => ({
249
- version: m.version,
250
- name: m.name,
251
- up_sql_preview: m.up_sql.substring(0, 200) +
252
- (m.up_sql.length > 200 ? "..." : ""),
253
- })),
254
- },
255
- };
256
- }
257
- const appliedMigrations = [];
258
- const failedMigrations = [];
259
- const currentUser = config_1.dbConfig.user || "unknown";
260
- for (const migration of pendingMigrations) {
261
- const startTime = Date.now();
262
- try {
263
- // Split SQL by semicolons and execute each statement
264
- const statements = this.splitSqlStatements(migration.up_sql);
265
- for (const statement of statements) {
266
- if (statement.trim()) {
267
- await this.db.query(statement);
268
- queryCount++;
269
- }
270
- }
271
- const executionTime = Date.now() - startTime;
272
- // Update migration status to applied
273
- const updateQuery = `
274
- UPDATE ${this.migrationsTable}
275
- SET status = 'applied',
276
- applied_at = NOW(),
277
- applied_by = ?,
278
- execution_time_ms = ?,
279
- error_message = NULL
280
- WHERE id = ?
281
- `;
282
- await this.db.query(updateQuery, [
283
- currentUser,
284
- executionTime,
285
- migration.id,
286
- ]);
287
- queryCount++;
288
- appliedMigrations.push({
289
- version: migration.version,
290
- name: migration.name,
291
- execution_time_ms: executionTime,
292
- });
293
- }
294
- catch (error) {
295
- const executionTime = Date.now() - startTime;
296
- // Update migration status to failed
297
- const updateQuery = `
298
- UPDATE ${this.migrationsTable}
299
- SET status = 'failed',
300
- execution_time_ms = ?,
301
- error_message = ?
302
- WHERE id = ?
303
- `;
304
- await this.db.query(updateQuery, [
305
- executionTime,
306
- error.message,
307
- migration.id,
308
- ]);
309
- queryCount++;
310
- failedMigrations.push({
311
- version: migration.version,
312
- name: migration.name,
313
- error: error.message,
314
- execution_time_ms: executionTime,
315
- });
316
- // Stop applying further migrations on failure
317
- break;
318
- }
319
- }
320
- return {
321
- status: failedMigrations.length > 0 ? "partial" : "success",
322
- data: {
323
- message: failedMigrations.length > 0
324
- ? `Applied ${appliedMigrations.length} migration(s), ${failedMigrations.length} failed`
325
- : `Successfully applied ${appliedMigrations.length} migration(s)`,
326
- applied_count: appliedMigrations.length,
327
- failed_count: failedMigrations.length,
328
- applied_migrations: appliedMigrations,
329
- failed_migrations: failedMigrations,
330
- },
331
- };
332
- }
333
- catch (error) {
334
- return {
335
- status: "error",
336
- error: error.message,
337
- };
338
- }
339
- }
340
- /**
341
- * Split SQL content into individual statements
342
- */
343
- splitSqlStatements(sql) {
344
- const statements = [];
345
- let currentStatement = "";
346
- let inString = false;
347
- let stringChar = "";
348
- let inComment = false;
349
- let inMultiLineComment = false;
350
- for (let i = 0; i < sql.length; i++) {
351
- const char = sql[i];
352
- const nextChar = sql[i + 1] || "";
353
- // Handle multi-line comments
354
- if (!inString && char === "/" && nextChar === "*") {
355
- inMultiLineComment = true;
356
- currentStatement += char;
357
- continue;
358
- }
359
- if (inMultiLineComment && char === "*" && nextChar === "/") {
360
- inMultiLineComment = false;
361
- currentStatement += char + nextChar;
362
- i++;
363
- continue;
364
- }
365
- if (inMultiLineComment) {
366
- currentStatement += char;
367
- continue;
368
- }
369
- // Handle single-line comments
370
- if (!inString && char === "-" && nextChar === "-") {
371
- inComment = true;
372
- currentStatement += char;
373
- continue;
374
- }
375
- if (inComment && char === "\n") {
376
- inComment = false;
377
- currentStatement += char;
378
- continue;
379
- }
380
- if (inComment) {
381
- currentStatement += char;
382
- continue;
383
- }
384
- // Handle strings
385
- if ((char === "'" || char === '"') && sql[i - 1] !== "\\") {
386
- if (!inString) {
387
- inString = true;
388
- stringChar = char;
389
- }
390
- else if (char === stringChar) {
391
- inString = false;
392
- }
393
- }
394
- // Handle statement separator
395
- if (char === ";" && !inString) {
396
- currentStatement += char;
397
- const trimmed = currentStatement.trim();
398
- if (trimmed && trimmed !== ";") {
399
- statements.push(trimmed);
400
- }
401
- currentStatement = "";
402
- continue;
403
- }
404
- currentStatement += char;
405
- }
406
- // Add any remaining statement
407
- const trimmed = currentStatement.trim();
408
- if (trimmed && trimmed !== ";") {
409
- statements.push(trimmed);
410
- }
411
- return statements;
412
- }
413
- /**
414
- * Rollback the last applied migration or to a specific version
415
- */
416
- async rollbackMigration(params) {
417
- try {
418
- const { target_version, steps = 1, dry_run = false, database } = params;
419
- // Validate database access
420
- const dbValidation = this.validateDatabaseAccess(database);
421
- if (!dbValidation.valid) {
422
- return { status: "error", error: dbValidation.error };
423
- }
424
- let queryCount = 0;
425
- // Get applied migrations to rollback
426
- let rollbackQuery;
427
- let queryParams = [];
428
- if (target_version) {
429
- rollbackQuery = `
430
- SELECT id, version, name, down_sql
431
- FROM ${this.migrationsTable}
432
- WHERE status = 'applied' AND version > ?
433
- ORDER BY version DESC
434
- `;
435
- queryParams = [target_version];
436
- }
437
- else {
438
- rollbackQuery = `
439
- SELECT id, version, name, down_sql
440
- FROM ${this.migrationsTable}
441
- WHERE status = 'applied'
442
- ORDER BY version DESC
443
- LIMIT ?
444
- `;
445
- queryParams = [steps];
446
- }
447
- const migrationsToRollback = await this.db.query(rollbackQuery, queryParams);
448
- queryCount++;
449
- if (migrationsToRollback.length === 0) {
450
- return {
451
- status: "success",
452
- data: {
453
- message: "No migrations to rollback",
454
- rolled_back_count: 0,
455
- migrations: [],
456
- },
457
- };
458
- }
459
- // Check if all migrations have down_sql
460
- const migrationsWithoutDown = migrationsToRollback.filter((m) => !m.down_sql);
461
- if (migrationsWithoutDown.length > 0 && !dry_run) {
462
- return {
463
- status: "error",
464
- error: `Cannot rollback: ${migrationsWithoutDown.length} migration(s) do not have down_sql defined: ${migrationsWithoutDown.map((m) => m.version).join(", ")}`,
465
- };
466
- }
467
- if (dry_run) {
468
- return {
469
- status: "success",
470
- data: {
471
- message: `Dry run: ${migrationsToRollback.length} migration(s) would be rolled back`,
472
- dry_run: true,
473
- migrations: migrationsToRollback.map((m) => ({
474
- version: m.version,
475
- name: m.name,
476
- has_down_sql: !!m.down_sql,
477
- down_sql_preview: m.down_sql
478
- ? m.down_sql.substring(0, 200) +
479
- (m.down_sql.length > 200 ? "..." : "")
480
- : null,
481
- })),
482
- },
483
- };
484
- }
485
- const rolledBackMigrations = [];
486
- const failedRollbacks = [];
487
- for (const migration of migrationsToRollback) {
488
- const startTime = Date.now();
489
- try {
490
- // Execute down_sql statements
491
- const statements = this.splitSqlStatements(migration.down_sql);
492
- for (const statement of statements) {
493
- if (statement.trim()) {
494
- await this.db.query(statement);
495
- queryCount++;
496
- }
497
- }
498
- const executionTime = Date.now() - startTime;
499
- // Update migration status to rolled_back
500
- const updateQuery = `
501
- UPDATE ${this.migrationsTable}
502
- SET status = 'rolled_back',
503
- applied_at = NULL,
504
- applied_by = NULL,
505
- execution_time_ms = ?,
506
- error_message = NULL
507
- WHERE id = ?
508
- `;
509
- await this.db.query(updateQuery, [executionTime, migration.id]);
510
- queryCount++;
511
- rolledBackMigrations.push({
512
- version: migration.version,
513
- name: migration.name,
514
- execution_time_ms: executionTime,
515
- });
516
- }
517
- catch (error) {
518
- const executionTime = Date.now() - startTime;
519
- failedRollbacks.push({
520
- version: migration.version,
521
- name: migration.name,
522
- error: error.message,
523
- execution_time_ms: executionTime,
524
- });
525
- // Stop rolling back on failure
526
- break;
527
- }
528
- }
529
- return {
530
- status: failedRollbacks.length > 0 ? "partial" : "success",
531
- data: {
532
- message: failedRollbacks.length > 0
533
- ? `Rolled back ${rolledBackMigrations.length} migration(s), ${failedRollbacks.length} failed`
534
- : `Successfully rolled back ${rolledBackMigrations.length} migration(s)`,
535
- rolled_back_count: rolledBackMigrations.length,
536
- failed_count: failedRollbacks.length,
537
- rolled_back_migrations: rolledBackMigrations,
538
- failed_rollbacks: failedRollbacks,
539
- },
540
- };
541
- }
542
- catch (error) {
543
- return {
544
- status: "error",
545
- error: error.message,
546
- };
547
- }
548
- }
549
- /**
550
- * Get migration history and status
551
- */
552
- async getMigrationStatus(params) {
553
- try {
554
- const { version, status, limit = 50, database } = params;
555
- // Validate database access
556
- const dbValidation = this.validateDatabaseAccess(database);
557
- if (!dbValidation.valid) {
558
- return { status: "error", error: dbValidation.error };
559
- }
560
- // Ensure migrations table exists
561
- await this.initMigrationsTable({ database });
562
- let queryCount = 1;
563
- // Build query
564
- let query = `
565
- SELECT
566
- id,
567
- version,
568
- name,
569
- description,
570
- checksum,
571
- status,
572
- applied_at,
573
- applied_by,
574
- execution_time_ms,
575
- error_message,
576
- created_at
577
- FROM ${this.migrationsTable}
578
- WHERE 1=1
579
- `;
580
- const queryParams = [];
581
- if (version) {
582
- query += ` AND version = ?`;
583
- queryParams.push(version);
584
- }
585
- if (status) {
586
- query += ` AND status = ?`;
587
- queryParams.push(status);
588
- }
589
- query += ` ORDER BY version DESC LIMIT ?`;
590
- queryParams.push(limit);
591
- const migrations = await this.db.query(query, queryParams);
592
- queryCount++;
593
- // Get summary statistics
594
- const summaryQuery = `
595
- SELECT
596
- status,
597
- COUNT(*) as count
598
- FROM ${this.migrationsTable}
599
- GROUP BY status
600
- `;
601
- const summary = await this.db.query(summaryQuery);
602
- queryCount++;
603
- const summaryMap = {};
604
- for (const row of summary) {
605
- summaryMap[row.status] = row.count;
606
- }
607
- // Get current schema version
608
- const currentVersionQuery = `
609
- SELECT version
610
- FROM ${this.migrationsTable}
611
- WHERE status = 'applied'
612
- ORDER BY version DESC
613
- LIMIT 1
614
- `;
615
- const currentVersionResult = await this.db.query(currentVersionQuery);
616
- queryCount++;
617
- const currentVersion = currentVersionResult.length > 0
618
- ? currentVersionResult[0].version
619
- : null;
620
- return {
621
- status: "success",
622
- data: {
623
- current_version: currentVersion,
624
- summary: {
625
- total: Object.values(summaryMap).reduce((a, b) => a + b, 0),
626
- pending: summaryMap.pending || 0,
627
- applied: summaryMap.applied || 0,
628
- failed: summaryMap.failed || 0,
629
- rolled_back: summaryMap.rolled_back || 0,
630
- },
631
- migrations: migrations.map((m) => ({
632
- ...m,
633
- applied_at: m.applied_at ? m.applied_at.toISOString() : null,
634
- created_at: m.created_at ? m.created_at.toISOString() : null,
635
- })),
636
- },
637
- };
638
- }
639
- catch (error) {
640
- return {
641
- status: "error",
642
- error: error.message,
643
- };
644
- }
645
- }
646
- /**
647
- * Get the current schema version
648
- */
649
- async getSchemaVersion(params) {
650
- try {
651
- const { database } = params;
652
- // Validate database access
653
- const dbValidation = this.validateDatabaseAccess(database);
654
- if (!dbValidation.valid) {
655
- return { status: "error", error: dbValidation.error };
656
- }
657
- // Check if migrations table exists
658
- const tableExistsQuery = `
659
- SELECT COUNT(*) as cnt
660
- FROM information_schema.tables
661
- WHERE table_schema = DATABASE()
662
- AND table_name = ?
663
- `;
664
- const tableExists = await this.db.query(tableExistsQuery, [
665
- this.migrationsTable,
666
- ]);
667
- if (tableExists[0].cnt === 0) {
668
- return {
669
- status: "success",
670
- data: {
671
- current_version: null,
672
- message: "No migrations have been tracked yet",
673
- migrations_table_exists: false,
674
- },
675
- };
676
- }
677
- // Get current version
678
- const versionQuery = `
679
- SELECT
680
- version,
681
- name,
682
- applied_at
683
- FROM ${this.migrationsTable}
684
- WHERE status = 'applied'
685
- ORDER BY version DESC
686
- LIMIT 1
687
- `;
688
- const versionResult = await this.db.query(versionQuery);
689
- if (versionResult.length === 0) {
690
- return {
691
- status: "success",
692
- data: {
693
- current_version: null,
694
- message: "No migrations have been applied yet",
695
- migrations_table_exists: true,
696
- },
697
- };
698
- }
699
- const current = versionResult[0];
700
- // Count pending migrations
701
- const pendingQuery = `
702
- SELECT COUNT(*) as cnt
703
- FROM ${this.migrationsTable}
704
- WHERE status = 'pending'
705
- `;
706
- const pendingResult = await this.db.query(pendingQuery);
707
- return {
708
- status: "success",
709
- data: {
710
- current_version: current.version,
711
- current_migration_name: current.name,
712
- applied_at: current.applied_at
713
- ? current.applied_at.toISOString()
714
- : null,
715
- pending_migrations: pendingResult[0].cnt,
716
- migrations_table_exists: true,
717
- },
718
- };
719
- }
720
- catch (error) {
721
- return {
722
- status: "error",
723
- error: error.message,
724
- };
725
- }
726
- }
727
- /**
728
- * Validate pending migrations (check for conflicts or issues)
729
- */
730
- async validateMigrations(params) {
731
- try {
732
- const { database } = params;
733
- // Validate database access
734
- const dbValidation = this.validateDatabaseAccess(database);
735
- if (!dbValidation.valid) {
736
- return { status: "error", error: dbValidation.error };
737
- }
738
- // Ensure migrations table exists
739
- await this.initMigrationsTable({ database });
740
- let queryCount = 1;
741
- // Get all migrations
742
- const migrationsQuery = `
743
- SELECT
744
- id,
745
- version,
746
- name,
747
- up_sql,
748
- down_sql,
749
- checksum,
750
- status
751
- FROM ${this.migrationsTable}
752
- ORDER BY version ASC
753
- `;
754
- const migrations = await this.db.query(migrationsQuery);
755
- queryCount++;
756
- const issues = [];
757
- const warnings = [];
758
- // Check for duplicate versions
759
- const versionCounts = new Map();
760
- for (const m of migrations) {
761
- versionCounts.set(m.version, (versionCounts.get(m.version) || 0) + 1);
762
- }
763
- for (const [version, count] of versionCounts) {
764
- if (count > 1) {
765
- issues.push({
766
- type: "duplicate_version",
767
- version,
768
- message: `Version '${version}' appears ${count} times`,
769
- });
770
- }
771
- }
772
- // Check for missing down_sql
773
- for (const m of migrations) {
774
- if (!m.down_sql) {
775
- warnings.push({
776
- type: "missing_down_sql",
777
- version: m.version,
778
- name: m.name,
779
- message: `Migration '${m.name}' (${m.version}) has no down_sql - rollback will not be possible`,
780
- });
781
- }
782
- }
783
- // Verify checksums for applied migrations
784
- for (const m of migrations) {
785
- if (m.status === "applied") {
786
- const expectedChecksum = this.generateChecksum(m.up_sql);
787
- if (m.checksum !== expectedChecksum) {
788
- issues.push({
789
- type: "checksum_mismatch",
790
- version: m.version,
791
- name: m.name,
792
- message: `Migration '${m.name}' (${m.version}) checksum mismatch - migration may have been modified after being applied`,
793
- stored_checksum: m.checksum,
794
- calculated_checksum: expectedChecksum,
795
- });
796
- }
797
- }
798
- }
799
- // Check for failed migrations that block pending ones
800
- const failedMigrations = migrations.filter((m) => m.status === "failed");
801
- if (failedMigrations.length > 0) {
802
- const pendingAfterFailed = migrations.filter((m) => m.status === "pending" && m.version > failedMigrations[0].version);
803
- if (pendingAfterFailed.length > 0) {
804
- warnings.push({
805
- type: "blocked_migrations",
806
- message: `${pendingAfterFailed.length} pending migration(s) are blocked by failed migration '${failedMigrations[0].name}' (${failedMigrations[0].version})`,
807
- failed_version: failedMigrations[0].version,
808
- blocked_versions: pendingAfterFailed.map((m) => m.version),
809
- });
810
- }
811
- }
812
- const isValid = issues.length === 0;
813
- return {
814
- status: "success",
815
- data: {
816
- valid: isValid,
817
- total_migrations: migrations.length,
818
- issues_count: issues.length,
819
- warnings_count: warnings.length,
820
- issues,
821
- warnings,
822
- summary: {
823
- pending: migrations.filter((m) => m.status === "pending").length,
824
- applied: migrations.filter((m) => m.status === "applied").length,
825
- failed: migrations.filter((m) => m.status === "failed").length,
826
- rolled_back: migrations.filter((m) => m.status === "rolled_back")
827
- .length,
828
- },
829
- },
830
- };
831
- }
832
- catch (error) {
833
- return {
834
- status: "error",
835
- error: error.message,
836
- };
837
- }
838
- }
839
- /**
840
- * Mark a failed migration as resolved (reset to pending status)
841
- */
842
- async resetFailedMigration(params) {
843
- try {
844
- const { version, database } = params;
845
- // Validate database access
846
- const dbValidation = this.validateDatabaseAccess(database);
847
- if (!dbValidation.valid) {
848
- return { status: "error", error: dbValidation.error };
849
- }
850
- // Check if migration exists and is failed
851
- const checkQuery = `
852
- SELECT id, name, status
853
- FROM ${this.migrationsTable}
854
- WHERE version = ?
855
- `;
856
- const migration = await this.db.query(checkQuery, [version]);
857
- if (migration.length === 0) {
858
- return {
859
- status: "error",
860
- error: `Migration version '${version}' not found`,
861
- };
862
- }
863
- if (migration[0].status !== "failed") {
864
- return {
865
- status: "error",
866
- error: `Migration '${version}' is not in failed status (current status: ${migration[0].status})`,
867
- };
868
- }
869
- // Reset to pending
870
- const updateQuery = `
871
- UPDATE ${this.migrationsTable}
872
- SET status = 'pending',
873
- error_message = NULL,
874
- execution_time_ms = NULL
875
- WHERE version = ?
876
- `;
877
- await this.db.query(updateQuery, [version]);
878
- return {
879
- status: "success",
880
- data: {
881
- message: `Migration '${migration[0].name}' (${version}) has been reset to pending status`,
882
- version,
883
- name: migration[0].name,
884
- previous_status: "failed",
885
- new_status: "pending",
886
- },
887
- };
888
- }
889
- catch (error) {
890
- return {
891
- status: "error",
892
- error: error.message,
893
- };
894
- }
895
- }
896
- /**
897
- * Generate a migration from table comparison
898
- */
899
- async generateMigrationFromDiff(params) {
900
- try {
901
- const { table1, table2, migration_name, database } = params;
902
- // Validate database access
903
- const dbValidation = this.validateDatabaseAccess(database);
904
- if (!dbValidation.valid) {
905
- return { status: "error", error: dbValidation.error };
906
- }
907
- // Validate table names
908
- const table1Validation = this.security.validateIdentifier(table1);
909
- if (!table1Validation.valid) {
910
- return {
911
- status: "error",
912
- error: `Invalid table1 name: ${table1Validation.error}`,
913
- };
914
- }
915
- const table2Validation = this.security.validateIdentifier(table2);
916
- if (!table2Validation.valid) {
917
- return {
918
- status: "error",
919
- error: `Invalid table2 name: ${table2Validation.error}`,
920
- };
921
- }
922
- const escapedTable1 = this.security.escapeIdentifier(table1);
923
- const escapedTable2 = this.security.escapeIdentifier(table2);
924
- // Get columns for both tables
925
- const cols1 = await this.db.query(`SHOW COLUMNS FROM ${escapedTable1}`);
926
- const cols2 = await this.db.query(`SHOW COLUMNS FROM ${escapedTable2}`);
927
- const columns1 = new Map(cols1.map((c) => [c.Field, c]));
928
- const columns2 = new Map(cols2.map((c) => [c.Field, c]));
929
- const upStatements = [];
930
- const downStatements = [];
931
- // Find columns only in table1 (to add to table2)
932
- for (const [name, col] of columns1) {
933
- if (!columns2.has(name)) {
934
- const nullable = col.Null === "YES" ? "NULL" : "NOT NULL";
935
- const defaultVal = col.Default !== null
936
- ? ` DEFAULT ${this.escapeValue(col.Default)}`
937
- : "";
938
- upStatements.push(`ALTER TABLE ${escapedTable2} ADD COLUMN \`${name}\` ${col.Type} ${nullable}${defaultVal};`);
939
- downStatements.push(`ALTER TABLE ${escapedTable2} DROP COLUMN \`${name}\`;`);
940
- }
941
- }
942
- // Find columns only in table2 (to remove from table2 to match table1)
943
- for (const [name, col] of columns2) {
944
- if (!columns1.has(name)) {
945
- upStatements.push(`ALTER TABLE ${escapedTable2} DROP COLUMN \`${name}\`;`);
946
- const nullable = col.Null === "YES" ? "NULL" : "NOT NULL";
947
- const defaultVal = col.Default !== null
948
- ? ` DEFAULT ${this.escapeValue(col.Default)}`
949
- : "";
950
- downStatements.push(`ALTER TABLE ${escapedTable2} ADD COLUMN \`${name}\` ${col.Type} ${nullable}${defaultVal};`);
951
- }
952
- }
953
- // Find columns with different types
954
- for (const [name, col1] of columns1) {
955
- const col2 = columns2.get(name);
956
- if (col2 && col1.Type !== col2.Type) {
957
- const nullable1 = col1.Null === "YES" ? "NULL" : "NOT NULL";
958
- const nullable2 = col2.Null === "YES" ? "NULL" : "NOT NULL";
959
- upStatements.push(`ALTER TABLE ${escapedTable2} MODIFY COLUMN \`${name}\` ${col1.Type} ${nullable1};`);
960
- downStatements.push(`ALTER TABLE ${escapedTable2} MODIFY COLUMN \`${name}\` ${col2.Type} ${nullable2};`);
961
- }
962
- }
963
- if (upStatements.length === 0) {
964
- return {
965
- status: "success",
966
- data: {
967
- message: "No differences found between tables - no migration needed",
968
- table1,
969
- table2,
970
- differences: 0,
971
- },
972
- };
973
- }
974
- const upSql = upStatements.join("\n");
975
- const downSql = downStatements.join("\n");
976
- // Create the migration
977
- const createResult = await this.createMigration({
978
- name: migration_name,
979
- up_sql: upSql,
980
- down_sql: downSql,
981
- description: `Auto-generated migration to transform ${table2} structure to match ${table1}`,
982
- database,
983
- });
984
- if (createResult.status === "error") {
985
- return createResult;
986
- }
987
- return {
988
- status: "success",
989
- data: {
990
- message: `Migration '${migration_name}' generated with ${upStatements.length} change(s)`,
991
- version: createResult.data?.version,
992
- changes_count: upStatements.length,
993
- up_sql: upSql,
994
- down_sql: downSql,
995
- source_table: table1,
996
- target_table: table2,
997
- },
998
- };
999
- }
1000
- catch (error) {
1001
- return {
1002
- status: "error",
1003
- error: error.message,
1004
- };
1005
- }
1006
- }
1007
- }
1008
- exports.SchemaVersioningTools = SchemaVersioningTools;