mysqlsyncr 1.0.52 → 1.0.56

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/index.js ADDED
@@ -0,0 +1,284 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.compare = exports.DBStructureChecker = void 0;
8
+ Object.defineProperty(exports, "dumpAllDatabases", {
9
+ enumerable: true,
10
+ get: function get() {
11
+ return _dump.dumpAllDatabases;
12
+ }
13
+ });
14
+ Object.defineProperty(exports, "startApiServer", {
15
+ enumerable: true,
16
+ get: function get() {
17
+ return _socketServer.startApiServer;
18
+ }
19
+ });
20
+ var _mysql = _interopRequireDefault(require("mysql2"));
21
+ var _util = _interopRequireDefault(require("util"));
22
+ var _fs = _interopRequireDefault(require("fs"));
23
+ var _path = _interopRequireDefault(require("path"));
24
+ var _cli2 = require("./cli.js");
25
+ var _dump = require("./dump.js");
26
+ var _compare = require("./compare.js");
27
+ var _socketServer = require("./socketServer.js");
28
+ var _open = _interopRequireDefault(require("open"));
29
+ var _nodeUrl = require("node:url");
30
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
31
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
32
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
33
+ function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
34
+ function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
35
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
36
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
37
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
38
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
39
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } // Import the new socket server
40
+ var DBStructureChecker = exports.DBStructureChecker = /*#__PURE__*/function () {
41
+ function DBStructureChecker(config) {
42
+ var targetDatabase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
43
+ _classCallCheck(this, DBStructureChecker);
44
+ this.config = config;
45
+ this.targetDatabase = targetDatabase;
46
+ this.connection = _mysql["default"].createConnection(this.config);
47
+ this.dumpAllDatabases = _dump.dumpAllDatabases;
48
+ this.compareAllDatabases = _compare.compareAllDatabases;
49
+ this.getDatabases = function () {
50
+ _fs["default"].readFileSync(_path["default"].join(__dirname, 'databases.json'), 'utf8');
51
+ };
52
+ // this.connection.on('error', (err) => {
53
+ // this.emit('error', err);
54
+ // console.error('Database connection error:', err);
55
+ // });
56
+ this.connection.query = _util["default"].promisify(this.connection.query); // Promisify for async/await
57
+ }
58
+ return _createClass(DBStructureChecker, [{
59
+ key: "reconnect",
60
+ value: function () {
61
+ var _reconnect = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
62
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
63
+ while (1) switch (_context.prev = _context.next) {
64
+ case 0:
65
+ this.connection = _mysql["default"].createConnection(this.config);
66
+ this.connection.query = _util["default"].promisify(this.connection.query); // Promisify for async/await
67
+ _context.next = 4;
68
+ return this.connection.connect();
69
+ case 4:
70
+ case "end":
71
+ return _context.stop();
72
+ }
73
+ }, _callee, this);
74
+ }));
75
+ function reconnect() {
76
+ return _reconnect.apply(this, arguments);
77
+ }
78
+ return reconnect;
79
+ }()
80
+ }, {
81
+ key: "closeConnection",
82
+ value: function () {
83
+ var _closeConnection = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
84
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
85
+ while (1) switch (_context2.prev = _context2.next) {
86
+ case 0:
87
+ if (!(this.connection.state !== 'disconnected')) {
88
+ _context2.next = 3;
89
+ break;
90
+ }
91
+ _context2.next = 3;
92
+ return this.connection.end();
93
+ case 3:
94
+ case "end":
95
+ return _context2.stop();
96
+ }
97
+ }, _callee2, this);
98
+ }));
99
+ function closeConnection() {
100
+ return _closeConnection.apply(this, arguments);
101
+ }
102
+ return closeConnection;
103
+ }()
104
+ }]);
105
+ }();
106
+ var compare = exports.compare = /*#__PURE__*/function () {
107
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(config, output) {
108
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
109
+ while (1) switch (_context4.prev = _context4.next) {
110
+ case 0:
111
+ return _context4.abrupt("return", new Promise(function (resolve, reject) {
112
+ try {
113
+ var checker = new DBStructureChecker(config);
114
+ checker.connection.on('connect', /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
115
+ var diffs;
116
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
117
+ while (1) switch (_context3.prev = _context3.next) {
118
+ case 0:
119
+ _context3.next = 2;
120
+ return (0, _compare.compareAllDatabases)(checker.connection, output, false, 'compare', {
121
+ output: output
122
+ });
123
+ case 2:
124
+ diffs = _context3.sent;
125
+ resolve(diffs);
126
+ case 4:
127
+ case "end":
128
+ return _context3.stop();
129
+ }
130
+ }, _callee3);
131
+ })));
132
+ } catch (e) {
133
+ reject(e);
134
+ }
135
+ }));
136
+ case 1:
137
+ case "end":
138
+ return _context4.stop();
139
+ }
140
+ }, _callee4);
141
+ }));
142
+ return function compare(_x, _x2) {
143
+ return _ref.apply(this, arguments);
144
+ };
145
+ }();
146
+ // Only run this if this is the main module
147
+ var isMain = function () {
148
+ try {
149
+ return require.main === module;
150
+ } catch (e) {
151
+ return false;
152
+ }
153
+ }();
154
+ if (isMain) {
155
+ _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
156
+ var _cli, command, config, argv, PORT, checker;
157
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
158
+ while (1) switch (_context6.prev = _context6.next) {
159
+ case 0:
160
+ _cli = (0, _cli2.cli)(), command = _cli.command, config = _cli.config, argv = _cli.argv;
161
+ console.log("MySQLsyncr started via command line");
162
+ if (!(command === 'ui')) {
163
+ _context6.next = 12;
164
+ break;
165
+ }
166
+ PORT = argv.uiPort;
167
+ (0, _socketServer.startApiServer)(PORT, argv); // Start the Socket.IO server
168
+ console.log('Server started on port', PORT);
169
+ console.log('Open http://localhost:' + PORT + ' in your browser to use the UI');
170
+ if (!(argv.openUI && argv.openUI === true || argv.openUI === 'true')) {
171
+ _context6.next = 10;
172
+ break;
173
+ }
174
+ _context6.next = 10;
175
+ return (0, _open["default"])("http://localhost:".concat(PORT));
176
+ case 10:
177
+ _context6.next = 14;
178
+ break;
179
+ case 12:
180
+ // Handle other commands (dump, compare, update) as before
181
+ checker = new DBStructureChecker(config, argv.database);
182
+ checker.connection.on('connect', /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
183
+ var diffs, totalDiffs, _totalDiffs, previousDiffs, runCount, maxRuns, _diffs;
184
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
185
+ while (1) switch (_context5.prev = _context5.next) {
186
+ case 0:
187
+ console.log('Connected to the database');
188
+ checker.targetDatabase = argv.database;
189
+ checker.command = command;
190
+ checker.options = argv;
191
+ _context5.prev = 4;
192
+ if (!(command === 'dump')) {
193
+ _context5.next = 11;
194
+ break;
195
+ }
196
+ console.log('Dumping the database structure to files');
197
+ _context5.next = 9;
198
+ return (0, _dump.dumpAllDatabases)(checker.connection, command, argv);
199
+ case 9:
200
+ _context5.next = 42;
201
+ break;
202
+ case 11:
203
+ if (!(command === 'compare')) {
204
+ _context5.next = 21;
205
+ break;
206
+ }
207
+ console.log('Comparing the database structure with JSON dumps (dry run)');
208
+ _context5.next = 15;
209
+ return (0, _compare.compareAllDatabases)(checker.connection, argv.output, false, command, argv);
210
+ case 15:
211
+ diffs = _context5.sent;
212
+ // Dry run
213
+ totalDiffs = Object.values(diffs).reduce(function (acc, arr) {
214
+ return acc + arr.length;
215
+ }, 0);
216
+ console.log('Total differences count:', totalDiffs);
217
+ _fs["default"].writeFileSync(_path["default"].join(argv.output, 'diffs.json'), JSON.stringify(diffs, null, 4));
218
+ _context5.next = 42;
219
+ break;
220
+ case 21:
221
+ if (!(command === 'update')) {
222
+ _context5.next = 42;
223
+ break;
224
+ }
225
+ console.log('Updating the database structure based on JSON dumps');
226
+ _totalDiffs = Infinity; // Initialize with a large number
227
+ previousDiffs = _totalDiffs; // Store previous differences
228
+ runCount = 0; // Counter for the number of runs
229
+ maxRuns = 6;
230
+ case 27:
231
+ if (!(runCount < maxRuns && _totalDiffs > 0 && (_totalDiffs < previousDiffs || previousDiffs === Infinity))) {
232
+ _context5.next = 42;
233
+ break;
234
+ }
235
+ console.log('Running update command. Run count:', runCount);
236
+ _context5.next = 31;
237
+ return (0, _compare.compareAllDatabases)(checker.connection, argv.output, true, command, argv);
238
+ case 31:
239
+ _diffs = _context5.sent;
240
+ // Apply updates
241
+ previousDiffs = _totalDiffs; // Update previous differences
242
+ _totalDiffs = Object.values(_diffs).reduce(function (acc, arr) {
243
+ return acc + arr.length;
244
+ }, 0);
245
+ console.log('Total differences count:', _totalDiffs);
246
+ runCount++;
247
+ if (!(_totalDiffs > 0 && runCount < maxRuns)) {
248
+ _context5.next = 40;
249
+ break;
250
+ }
251
+ console.log('Total differences count is still greater than 0. Waiting 1 second before next run. Run count:', runCount);
252
+ _context5.next = 40;
253
+ return new Promise(function (resolve) {
254
+ return setTimeout(resolve, 1000);
255
+ });
256
+ case 40:
257
+ _context5.next = 27;
258
+ break;
259
+ case 42:
260
+ _context5.next = 47;
261
+ break;
262
+ case 44:
263
+ _context5.prev = 44;
264
+ _context5.t0 = _context5["catch"](4);
265
+ console.error(_context5.t0.message);
266
+ case 47:
267
+ _context5.prev = 47;
268
+ _context5.next = 50;
269
+ return checker.closeConnection();
270
+ case 50:
271
+ return _context5.finish(47);
272
+ case 51:
273
+ case "end":
274
+ return _context5.stop();
275
+ }
276
+ }, _callee5, null, [[4, 44, 47, 51]]);
277
+ })));
278
+ case 14:
279
+ case "end":
280
+ return _context6.stop();
281
+ }
282
+ }, _callee6);
283
+ }))();
284
+ }
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.setVerbose = exports.logger = exports.logDifferences = void 0;
7
+ var isVerbose = false; // Global variable to manage verbosity
8
+
9
+ var setVerbose = exports.setVerbose = function setVerbose(verbose) {
10
+ isVerbose = verbose; // Function to set the verbosity level
11
+ };
12
+ var logger = exports.logger = function logger() {
13
+ if (isVerbose) {
14
+ var _console;
15
+ (_console = console).log.apply(_console, arguments); // Log all arguments if verbose is enabled
16
+ }
17
+ };
18
+ var logDifferences = exports.logDifferences = function logDifferences(differences, database, dryRun) {
19
+ var formattedDifferences = differences.map(function (diff) {
20
+ switch (diff.type) {
21
+ case 'missing_procedure':
22
+ return {
23
+ Type: diff.type,
24
+ Name: diff.Name,
25
+ Details: "Procedure ".concat(diff.Name, " is missing"),
26
+ Action: 'Procedure is missing'
27
+ };
28
+ case 'mismatched_procedure':
29
+ return {
30
+ Type: diff.type,
31
+ Name: diff.Name,
32
+ Details: "Mismatched procedure ".concat(diff.Name),
33
+ Action: 'Mismatched procedure'
34
+ };
35
+ case 'missing_field':
36
+ return {
37
+ Type: diff.type,
38
+ Name: diff.tableName,
39
+ Details: "Field ".concat(diff.field.Field, " is missing"),
40
+ Action: 'Field is missing'
41
+ };
42
+ case 'missing_table':
43
+ return {
44
+ Type: diff.type,
45
+ Name: diff.tableName,
46
+ Details: "Table ".concat(diff.tableName, " is missing"),
47
+ Action: 'Table is missing'
48
+ };
49
+ case 'extra_field':
50
+ return {
51
+ Type: diff.type,
52
+ Name: diff.tableName,
53
+ Details: "Field ".concat(diff.field.Field, " is extra"),
54
+ Action: 'Field is extra'
55
+ };
56
+ case 'extra_table':
57
+ return {
58
+ Type: diff.type,
59
+ Name: diff.tableName,
60
+ Details: "Table ".concat(diff.tableName, " is extra"),
61
+ Action: 'Table is extra'
62
+ };
63
+ case 'missing_view':
64
+ return {
65
+ Type: diff.type,
66
+ Name: diff.viewName,
67
+ Details: "View ".concat(diff.viewName, " is missing"),
68
+ Action: 'View is missing'
69
+ };
70
+ case 'extra_index':
71
+ return {
72
+ Type: diff.type,
73
+ Name: diff.tableName,
74
+ Details: "Index ".concat(diff.index.Name, " is extra"),
75
+ Action: 'Index is extra'
76
+ };
77
+ case 'missing_index':
78
+ return {
79
+ Type: diff.type,
80
+ TableName: diff.tableName,
81
+ Name: diff.index.Name,
82
+ Details: "Index ".concat(diff.index.Name, " is missing"),
83
+ Action: 'Index is missing'
84
+ };
85
+ case 'mismatched_index':
86
+ return {
87
+ Type: diff.type,
88
+ TableName: diff.tableName,
89
+ Name: diff.index.Name,
90
+ From: diff.from,
91
+ Details: "Index ".concat(diff.index.Name, " is mismatched"),
92
+ Action: 'Index is mismatched'
93
+ };
94
+ case 'extra_trigger':
95
+ return {
96
+ Type: diff.type,
97
+ Name: diff.trigger.Name,
98
+ Details: "Trigger ".concat(diff.trigger.Name, " is extra"),
99
+ Action: 'Trigger is extra'
100
+ };
101
+ case 'mismatched_trigger':
102
+ return {
103
+ Type: diff.type,
104
+ Name: diff.trigger.Name,
105
+ Details: "Trigger ".concat(diff.trigger.Name, " is mismatched"),
106
+ Action: 'Trigger is mismatched'
107
+ };
108
+ case 'missing_trigger':
109
+ console.log('missing_trigger', diff);
110
+ return {
111
+ Type: diff.type,
112
+ Name: diff.trigger.Name,
113
+ Details: "Trigger ".concat(diff.trigger.Name, " is missing"),
114
+ Action: 'Trigger is missing'
115
+ };
116
+ default:
117
+ return {
118
+ Type: diff.type,
119
+ Details: "Unhandled difference type: ".concat(diff.type)
120
+ };
121
+ }
122
+ });
123
+
124
+ // Filter out any undefined or null entries
125
+ var filteredDifferences = formattedDifferences.filter(function (diff) {
126
+ return diff;
127
+ });
128
+
129
+ // Log the differences in a table format
130
+ if (filteredDifferences.length > 0) {
131
+ if (dryRun) {
132
+ logger("Dry Run: Differences for database ".concat(database, ":"));
133
+ } else {
134
+ logger("Differences applied for database ".concat(database, ":"));
135
+ }
136
+ console.table(filteredDifferences);
137
+ } else {
138
+ if (dryRun) {
139
+ logger("Dry Run: No differences found. Database: ".concat(database));
140
+ } else {
141
+ logger("No differences found. Database: ".concat(database));
142
+ }
143
+ }
144
+ };
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.normalizeSQLDefinition = void 0;
7
+ var normalizeSQLDefinition = exports.normalizeSQLDefinition = function normalizeSQLDefinition(definition) {
8
+ return definition.replace(/\s+/g, ' ') // Replace multiple whitespace with a single space
9
+ .replace(/'/g, "\\'") // Escape single quotes
10
+ .trim(); // Trim leading and trailing whitespace
11
+ };
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.parseCreateTableSQL = exports.parseConstraint = void 0;
7
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
8
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
9
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
10
+ var parseCreateTableSQL = exports.parseCreateTableSQL = function parseCreateTableSQL(createTableSQL) {
11
+ if (!createTableSQL) return null;
12
+ var name = createTableSQL.match(/CREATE TABLE\s+`([^`]+)`/)[1];
13
+ var columns = [];
14
+ var indexes = [];
15
+ var constraints = [];
16
+ var engine = null;
17
+ var charset = null;
18
+ var collate = null;
19
+
20
+ // Split the SQL statement into lines and filter out empty lines
21
+ var lines = createTableSQL.split('\n').map(function (line) {
22
+ return line.trim();
23
+ }).filter(function (line) {
24
+ return line.length > 0;
25
+ });
26
+
27
+ // Regular expression to match column definitions
28
+ var columnRegex = /`([^`]+)`\s+([^\s,]+)(\s+NOT NULL|\s+NULL)?(\s+DEFAULT\s+([^,\s]+))?(\s+AUTO_INCREMENT)?/;
29
+
30
+ // Regular expression to match index definitions
31
+ var indexRegex = /(PRIMARY|UNIQUE)?\s*KEY\s*`([^`]+)`\s*\(([^)]+)\)|PRIMARY KEY\s*\(([^)]+)\)/;
32
+
33
+ // Regular expression to match table options (ENGINE, CHARSET, COLLATE)
34
+ var optionsRegex = /ENGINE=(\w+)\s+DEFAULT\s+CHARSET=(\w+)(\s+COLLATE=(\w+))?/;
35
+
36
+ // Process each line
37
+ var _iterator = _createForOfIteratorHelper(lines),
38
+ _step;
39
+ try {
40
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
41
+ var line = _step.value;
42
+ if (line.includes('CREATE TABLE')) {
43
+ continue;
44
+ }
45
+ // Check if the line contains a column definition
46
+ var columnMatch = columnRegex.exec(line);
47
+ var indexMatch = indexRegex.exec(line);
48
+ var constraintMatch = parseConstraint(line);
49
+ if (columnMatch && !indexMatch && !constraintMatch) {
50
+ var columnType = parseColumnType(line);
51
+ var column = {
52
+ Field: columnMatch[1],
53
+ Type: columnType
54
+ };
55
+
56
+ // Set Null property based on NOT NULL presence
57
+ if (columnMatch[3] && columnMatch[3].includes('NOT NULL')) {
58
+ column.NotNull = true; // Set to false if NOT NULL is present
59
+ }
60
+
61
+ // Set Default property if it exists
62
+ if (columnMatch[5]) {
63
+ // console.log('columnMatch[5]', columnMatch[5], columnMatch[5].replace(/'/g, ''))
64
+ column.Default = columnMatch[5].replace(/'/g, '');
65
+ }
66
+
67
+ // Set AutoIncrement property if it exists
68
+ if (columnMatch[6]) {
69
+ column.AutoIncrement = true; // Set to true if AUTO_INCREMENT is present
70
+ }
71
+ columns.push(column);
72
+ } else if (indexMatch && !constraintMatch) {
73
+ var isPrimary = line.includes("PRIMARY KEY"); // Check for PRIMARY in both patterns
74
+ var isUnique = line.includes("UNIQUE KEY"); // Only set Unique if it matches
75
+
76
+ var keyName = isPrimary ? null : indexMatch[2]; // Set KeyName to null if it's a primary key
77
+ var columnNames = indexMatch[3] ? indexMatch[3].split(',').map(function (col) {
78
+ return col.trim().replace(/`/g, '');
79
+ }) // Remove backticks
80
+ : indexMatch[4].split(',').map(function (col) {
81
+ return col.trim().replace(/`/g, '');
82
+ }); // Remove backticks
83
+ var index = {
84
+ ColumnName: columnNames
85
+ };
86
+ if (isPrimary) index.Primary = true, index.Name = "PRIMARY";
87
+ if (isUnique) index.Unique = true;
88
+ if (keyName) index.Name = keyName;
89
+ indexes.push(index);
90
+ } else if (constraintMatch) {
91
+ constraints.push(constraintMatch);
92
+ }
93
+ }
94
+
95
+ // Handle table options
96
+ } catch (err) {
97
+ _iterator.e(err);
98
+ } finally {
99
+ _iterator.f();
100
+ }
101
+ var optionsMatch = optionsRegex.exec(createTableSQL);
102
+ if (optionsMatch) {
103
+ engine = optionsMatch[1];
104
+ charset = optionsMatch[2];
105
+ collate = optionsMatch[4] || null; // Collate may not be present
106
+ }
107
+ return {
108
+ name: name,
109
+ columns: columns,
110
+ indexes: indexes,
111
+ constraints: constraints,
112
+ engine: engine,
113
+ charset: charset,
114
+ collate: collate
115
+ };
116
+ };
117
+ var parseConstraint = exports.parseConstraint = function parseConstraint(sql) {
118
+ if (!sql) return null;
119
+ var regex = /FOREIGN KEY \((`[^`]+`)\) REFERENCES (`[^`]+`)\s?\((`[^`]+`)\)(?:\sON DELETE (NO|CASCADE|SET NULL|SET DEFAULT))?(?:\sON UPDATE (NO ACTION|CASCADE|SET NULL|SET DEFAULT))?/i;
120
+ var match = sql.match(regex);
121
+ if (!match) {
122
+ return null;
123
+ }
124
+ var onDelete = null;
125
+ var onUpdate = null;
126
+ if (sql.includes('ON DELETE CASCADE')) {
127
+ onDelete = 'CASCADE';
128
+ } else if (sql.includes('ON DELETE SET NULL')) {
129
+ onDelete = 'SET NULL';
130
+ } else if (sql.includes('ON DELETE SET DEFAULT')) {
131
+ onDelete = 'SET DEFAULT';
132
+ } else {
133
+ onDelete = 'NO ACTION';
134
+ }
135
+ if (sql.includes('ON UPDATE CASCADE')) {
136
+ onUpdate = 'CASCADE';
137
+ } else if (sql.includes('ON UPDATE SET NULL')) {
138
+ onUpdate = 'SET NULL';
139
+ } else if (sql.includes('ON UPDATE SET DEFAULT')) {
140
+ onUpdate = 'SET DEFAULT';
141
+ } else {
142
+ onUpdate = 'NO ACTION';
143
+ }
144
+ var columnName = match[1] || '';
145
+ columnName = columnName.replace(/`/g, '');
146
+ var table = match[2] || '';
147
+ table = table.replace(/`/g, '');
148
+ var column = match[3] || '';
149
+ column = column.replace(/`/g, '');
150
+ return {
151
+ Name: "AlertRule",
152
+ // Replace with actual constraint name if needed
153
+ Type: "FOREIGN KEY",
154
+ ColumnName: [columnName],
155
+ // Column in the current table
156
+ References: {
157
+ Table: table,
158
+ // Referenced table
159
+ Column: column // Referenced column
160
+ },
161
+ OnDelete: onDelete,
162
+ OnUpdate: onUpdate
163
+ };
164
+ };
165
+ var parseColumnType = function parseColumnType(line) {
166
+ // Match type pattern including parameters, handling both single and double parameter types
167
+ var typeRegex = /`[^`]+`\s+([a-zA-Z]+(?:\([0-9]+(?:,[0-9]+)?\))?)/i;
168
+ var match = line.match(typeRegex);
169
+ if (!match) return null;
170
+ return match[1]; // Returns the full type including parameters
171
+ };