dbgate-tools 4.6.0 → 4.7.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.
@@ -21,6 +21,7 @@ export declare class DatabaseAnalyser {
21
21
  getDeletedObjectsForField(snapshot: any, objectTypeField: any): any;
22
22
  getDeletedObjects(snapshot: any): any[];
23
23
  getModifications(): Promise<any[]>;
24
+ safeQuery(sql: any): Promise<import("dbgate-types").QueryResult>;
24
25
  static createEmptyStructure(): DatabaseInfo;
25
26
  static byTableFilter(table: any): (x: any) => boolean;
26
27
  static extractPrimaryKeys(table: any, pkColumns: any): {
@@ -19,6 +19,21 @@ const pick_1 = __importDefault(require("lodash/pick"));
19
19
  const compact_1 = __importDefault(require("lodash/compact"));
20
20
  const STRUCTURE_FIELDS = ['tables', 'collections', 'views', 'matviews', 'functions', 'procedures', 'triggers'];
21
21
  const fp_pick = arg => array => (0, pick_1.default)(array, arg);
22
+ function mergeTableRowCounts(info, rowCounts) {
23
+ return Object.assign(Object.assign({}, info), { tables: (info.tables || []).map(table => {
24
+ var _a, _b;
25
+ return (Object.assign(Object.assign({}, table), { tableRowCount: (_b = (_a = rowCounts.find(x => x.objectId == table.objectId)) === null || _a === void 0 ? void 0 : _a.tableRowCount) !== null && _b !== void 0 ? _b : table.tableRowCount }));
26
+ }) });
27
+ }
28
+ function areDifferentRowCounts(db1, db2) {
29
+ for (const t1 of db1.tables || []) {
30
+ const t2 = (db2.tables || []).find(x => x.objectId == t1.objectId);
31
+ if ((t1 === null || t1 === void 0 ? void 0 : t1.tableRowCount) !== (t2 === null || t2 === void 0 ? void 0 : t2.tableRowCount)) {
32
+ return true;
33
+ }
34
+ }
35
+ return false;
36
+ }
22
37
  class DatabaseAnalyser {
23
38
  constructor(pool, driver, version) {
24
39
  this.pool = pool;
@@ -78,14 +93,27 @@ class DatabaseAnalyser {
78
93
  incrementalAnalysis(structure) {
79
94
  return __awaiter(this, void 0, void 0, function* () {
80
95
  this.structure = structure;
81
- this.modifications = yield this.getModifications();
82
- if (this.modifications == null) {
96
+ const modifications = yield this.getModifications();
97
+ if (modifications == null) {
83
98
  // modifications not implemented, perform full analysis
84
99
  this.structure = null;
85
100
  return this.addEngineField(yield this._runAnalysis());
86
101
  }
87
- if (this.modifications.length == 0)
88
- return null;
102
+ const structureModifications = modifications.filter(x => x.action != 'setTableRowCounts');
103
+ const setTableRowCounts = modifications.find(x => x.action == 'setTableRowCounts');
104
+ let structureWithRowCounts = null;
105
+ if (setTableRowCounts) {
106
+ const newStructure = mergeTableRowCounts(structure, setTableRowCounts.rowCounts);
107
+ if (areDifferentRowCounts(structure, newStructure)) {
108
+ structureWithRowCounts = newStructure;
109
+ }
110
+ }
111
+ if (structureModifications.length == 0) {
112
+ return structureWithRowCounts ? this.addEngineField(structureWithRowCounts) : null;
113
+ }
114
+ this.modifications = structureModifications;
115
+ if (structureWithRowCounts)
116
+ this.structure = structureWithRowCounts;
89
117
  console.log('DB modifications detected:', this.modifications);
90
118
  return this.addEngineField(this.mergeAnalyseResult(yield this._runAnalysis()));
91
119
  });
@@ -228,9 +256,34 @@ class DatabaseAnalyser {
228
256
  res.push(action);
229
257
  }
230
258
  }
259
+ const rowCounts = (snapshot.tables || [])
260
+ .filter(x => x.tableRowCount != null)
261
+ .map(x => ({
262
+ objectId: x.objectId,
263
+ tableRowCount: x.tableRowCount,
264
+ }));
265
+ if (rowCounts.length > 0) {
266
+ res.push({
267
+ action: 'setTableRowCounts',
268
+ rowCounts,
269
+ });
270
+ }
231
271
  return [...(0, compact_1.default)(res), ...this.getDeletedObjects(snapshot)];
232
272
  });
233
273
  }
274
+ safeQuery(sql) {
275
+ return __awaiter(this, void 0, void 0, function* () {
276
+ try {
277
+ return yield this.driver.query(this.pool, sql);
278
+ }
279
+ catch (err) {
280
+ console.log('Error running analyser query', err.message);
281
+ return {
282
+ rows: [],
283
+ };
284
+ }
285
+ });
286
+ }
234
287
  static createEmptyStructure() {
235
288
  return {
236
289
  tables: [],
@@ -9,12 +9,14 @@ export declare class SqlDumper implements AlterProcessor {
9
9
  putRaw(text: any): void;
10
10
  escapeString(value: any): string;
11
11
  putStringValue(value: any): void;
12
+ putByteArrayValue(value: any): void;
12
13
  putValue(value: any): void;
13
14
  putCmd(format: any, ...args: any[]): void;
14
15
  putFormattedValue(c: any, value: any): void;
15
16
  putFormattedList(c: any, collection: any): void;
16
17
  put(format: string, ...args: any[]): void;
17
18
  autoIncrement(): void;
19
+ specialColumnOptions(column: any): void;
18
20
  columnDefinition(column: ColumnInfo, { includeDefault, includeNullable, includeCollate }?: {
19
21
  includeDefault?: boolean;
20
22
  includeNullable?: boolean;
package/lib/SqlDumper.js CHANGED
@@ -8,6 +8,8 @@ const lodash_1 = __importDefault(require("lodash"));
8
8
  const isString_1 = __importDefault(require("lodash/isString"));
9
9
  const isNumber_1 = __importDefault(require("lodash/isNumber"));
10
10
  const isDate_1 = __importDefault(require("lodash/isDate"));
11
+ const isArray_1 = __importDefault(require("lodash/isArray"));
12
+ const isPlainObject_1 = __importDefault(require("lodash/isPlainObject"));
11
13
  const v1_1 = __importDefault(require("uuid/v1"));
12
14
  class SqlDumper {
13
15
  constructor(driver) {
@@ -39,6 +41,9 @@ class SqlDumper {
39
41
  this.putRaw(this.escapeString(value));
40
42
  this.putRaw("'");
41
43
  }
44
+ putByteArrayValue(value) {
45
+ this.putRaw('NULL');
46
+ }
42
47
  putValue(value) {
43
48
  if (value === null)
44
49
  this.putRaw('NULL');
@@ -52,6 +57,10 @@ class SqlDumper {
52
57
  this.putRaw(value.toString());
53
58
  else if ((0, isDate_1.default)(value))
54
59
  this.putStringValue(new Date(value).toISOString());
60
+ else if ((value === null || value === void 0 ? void 0 : value.type) == 'Buffer' && (0, isArray_1.default)(value === null || value === void 0 ? void 0 : value.data))
61
+ this.putByteArrayValue(value === null || value === void 0 ? void 0 : value.data);
62
+ else if ((0, isPlainObject_1.default)(value) || (0, isArray_1.default)(value))
63
+ this.putStringValue(JSON.stringify(value));
55
64
  else
56
65
  this.putRaw('NULL');
57
66
  }
@@ -161,6 +170,7 @@ class SqlDumper {
161
170
  autoIncrement() {
162
171
  this.put(' ^auto_increment');
163
172
  }
173
+ specialColumnOptions(column) { }
164
174
  columnDefinition(column, { includeDefault = true, includeNullable = true, includeCollate = true } = {}) {
165
175
  var _a;
166
176
  if (column.computedExpression) {
@@ -174,9 +184,7 @@ class SqlDumper {
174
184
  this.autoIncrement();
175
185
  }
176
186
  this.putRaw(' ');
177
- if (column.isSparse) {
178
- this.put(' ^sparse ');
179
- }
187
+ this.specialColumnOptions(column);
180
188
  if (includeNullable) {
181
189
  this.put(column.notNull ? '^not ^null' : '^null');
182
190
  }
@@ -25,6 +25,7 @@ function createBulkInsertStreamBase(driver, stream, pool, name, options) {
25
25
  writable.buffer = [];
26
26
  writable.structure = null;
27
27
  writable.columnNames = null;
28
+ writable.requireFixedStructure = !driver.dialect.nosql;
28
29
  writable.addRow = (row) => __awaiter(this, void 0, void 0, function* () {
29
30
  if (writable.structure) {
30
31
  writable.buffer.push(row);
@@ -39,18 +40,18 @@ function createBulkInsertStreamBase(driver, stream, pool, name, options) {
39
40
  // console.log('ANALYSING', name, structure);
40
41
  if (structure && options.dropIfExists) {
41
42
  console.log(`Dropping table ${fullNameQuoted}`);
42
- yield driver.query(pool, `DROP TABLE ${fullNameQuoted}`);
43
+ yield driver.script(pool, `DROP TABLE ${fullNameQuoted}`);
43
44
  }
44
45
  if (options.createIfNotExists && (!structure || options.dropIfExists)) {
45
46
  console.log(`Creating table ${fullNameQuoted}`);
46
47
  const dmp = driver.createDumper();
47
48
  dmp.createTable((0, tableTransforms_1.prepareTableForImport)(Object.assign(Object.assign({}, writable.structure), name)));
48
49
  console.log(dmp.s);
49
- yield driver.query(pool, dmp.s);
50
+ yield driver.script(pool, dmp.s);
50
51
  structure = yield driver.analyseSingleTable(pool, name);
51
52
  }
52
53
  if (options.truncate) {
53
- yield driver.query(pool, `TRUNCATE TABLE ${fullNameQuoted}`);
54
+ yield driver.script(pool, `TRUNCATE TABLE ${fullNameQuoted}`);
54
55
  }
55
56
  writable.columnNames = (0, intersection_1.default)(structure.columns.map(x => x.columnName), writable.structure.columns.map(x => x.columnName));
56
57
  });
package/lib/diffTools.js CHANGED
@@ -134,6 +134,18 @@ function testEqualColumns(a, b, checkName, checkDefault, opts = {}) {
134
134
  // opts.DiffLogger.Trace('Column {0}, {1}: different is_sparse: {2}; {3}', a, b, a.IsSparse, b.IsSparse);
135
135
  return false;
136
136
  }
137
+ if ((a.isUnsigned || false) != (b.isUnsigned || false)) {
138
+ console.debug(`Column ${a.pureName}.${a.columnName}, ${b.pureName}.${b.columnName}: different unsigned: ${a.isUnsigned}, ${b.isUnsigned}`);
139
+ return false;
140
+ }
141
+ if ((a.isZerofill || false) != (b.isZerofill || false)) {
142
+ console.debug(`Column ${a.pureName}.${a.columnName}, ${b.pureName}.${b.columnName}: different zerofill: ${a.isZerofill}, ${b.isZerofill}`);
143
+ return false;
144
+ }
145
+ if ((a.columnComment || '') != (b.columnComment || '')) {
146
+ console.debug(`Column ${a.pureName}.${a.columnName}, ${b.pureName}.${b.columnName}: different comment: ${a.columnComment}, ${b.columnComment}`);
147
+ return false;
148
+ }
137
149
  if (!testEqualTypes(a, b, opts)) {
138
150
  return false;
139
151
  }
@@ -9,6 +9,10 @@ export declare const driverBase: {
9
9
  stringEscapeChar: string;
10
10
  fallbackDataType: string;
11
11
  quoteIdentifier(s: any): any;
12
+ columnProperties: {
13
+ isSparse: boolean;
14
+ isPersisted: boolean;
15
+ };
12
16
  };
13
17
  analyseFull(pool: any, version: any): Promise<any>;
14
18
  analyseSingleObject(pool: any, name: any, typeField?: string): Promise<any>;
package/lib/driverBase.js CHANGED
@@ -21,6 +21,10 @@ const dialect = {
21
21
  quoteIdentifier(s) {
22
22
  return s;
23
23
  },
24
+ columnProperties: {
25
+ isSparse: false,
26
+ isPersisted: false,
27
+ },
24
28
  };
25
29
  exports.driverBase = {
26
30
  analyserClass: null,
@@ -1,2 +1,6 @@
1
1
  export declare function arrayToHexString(byteArray: any): any;
2
2
  export declare function hexStringToArray(inputString: any): any[];
3
+ export declare function parseCellValue(value: any): any;
4
+ export declare function stringifyCellValue(value: any): any;
5
+ export declare function safeJsonParse(json: any, defaultValue?: any, logError?: boolean): any;
6
+ export declare function isJsonLikeLongString(value: any): RegExpMatchArray;
@@ -1,8 +1,14 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.hexStringToArray = exports.arrayToHexString = void 0;
6
+ exports.isJsonLikeLongString = exports.safeJsonParse = exports.stringifyCellValue = exports.parseCellValue = exports.hexStringToArray = exports.arrayToHexString = void 0;
7
+ const isString_1 = __importDefault(require("lodash/isString"));
8
+ const isArray_1 = __importDefault(require("lodash/isArray"));
9
+ const isPlainObject_1 = __importDefault(require("lodash/isPlainObject"));
4
10
  function arrayToHexString(byteArray) {
5
- return byteArray.reduce((output, elem) => output + ('0' + elem.toString(16)).slice(-2), '');
11
+ return byteArray.reduce((output, elem) => output + ('0' + elem.toString(16)).slice(-2), '').toUpperCase();
6
12
  }
7
13
  exports.arrayToHexString = arrayToHexString;
8
14
  function hexStringToArray(inputString) {
@@ -14,3 +20,52 @@ function hexStringToArray(inputString) {
14
20
  return res;
15
21
  }
16
22
  exports.hexStringToArray = hexStringToArray;
23
+ function parseCellValue(value) {
24
+ if (!(0, isString_1.default)(value))
25
+ return value;
26
+ if (value == '(NULL)')
27
+ return null;
28
+ const mHex = value.match(/^0x([0-9a-fA-F][0-9a-fA-F])+$/);
29
+ if (mHex) {
30
+ return {
31
+ type: 'Buffer',
32
+ data: hexStringToArray(value.substring(2)),
33
+ };
34
+ }
35
+ const mOid = value.match(/^ObjectId\("([0-9a-f]{24})"\)$/);
36
+ if (mOid) {
37
+ return { $oid: mOid[1] };
38
+ }
39
+ return value;
40
+ }
41
+ exports.parseCellValue = parseCellValue;
42
+ function stringifyCellValue(value) {
43
+ if (value === null)
44
+ return '(NULL)';
45
+ if (value === undefined)
46
+ return '(NoField)';
47
+ if ((value === null || value === void 0 ? void 0 : value.type) == 'Buffer' && (0, isArray_1.default)(value.data))
48
+ return '0x' + arrayToHexString(value.data);
49
+ if (value === null || value === void 0 ? void 0 : value.$oid)
50
+ return `ObjectId("${value === null || value === void 0 ? void 0 : value.$oid}")`;
51
+ if ((0, isPlainObject_1.default)(value) || (0, isArray_1.default)(value))
52
+ return JSON.stringify(value);
53
+ return value;
54
+ }
55
+ exports.stringifyCellValue = stringifyCellValue;
56
+ function safeJsonParse(json, defaultValue, logError = false) {
57
+ try {
58
+ return JSON.parse(json);
59
+ }
60
+ catch (err) {
61
+ if (logError) {
62
+ console.error(`Error parsing JSON value "${json}"`, err);
63
+ }
64
+ return defaultValue;
65
+ }
66
+ }
67
+ exports.safeJsonParse = safeJsonParse;
68
+ function isJsonLikeLongString(value) {
69
+ return (0, isString_1.default)(value) && value.length > 100 && value.match(/^\s*\{.*\}\s*$|^\s*\[.*\]\s*$/);
70
+ }
71
+ exports.isJsonLikeLongString = isJsonLikeLongString;
@@ -1,4 +1,6 @@
1
- import { DatabaseInfo, TableInfo } from 'dbgate-types';
1
+ import { DatabaseInfo, TableInfo, ApplicationDefinition } from 'dbgate-types';
2
2
  export declare function addTableDependencies(db: DatabaseInfo): DatabaseInfo;
3
3
  export declare function extendTableInfo(table: TableInfo): TableInfo;
4
4
  export declare function extendDatabaseInfo(db: DatabaseInfo): DatabaseInfo;
5
+ export declare function extendDatabaseInfoFromApps(db: DatabaseInfo, apps: ApplicationDefinition[]): DatabaseInfo;
6
+ export declare function isTableColumnUnique(table: TableInfo, column: string): boolean;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.extendDatabaseInfo = exports.extendTableInfo = exports.addTableDependencies = void 0;
6
+ exports.isTableColumnUnique = exports.extendDatabaseInfoFromApps = exports.extendDatabaseInfo = exports.extendTableInfo = exports.addTableDependencies = void 0;
7
7
  const flatten_1 = __importDefault(require("lodash/flatten"));
8
8
  function addTableDependencies(db) {
9
9
  const allForeignKeys = (0, flatten_1.default)(db.tables.map(x => x.foreignKeys || []));
@@ -22,3 +22,26 @@ function extendDatabaseInfo(db) {
22
22
  return fillDatabaseExtendedInfo(addTableDependencies(db));
23
23
  }
24
24
  exports.extendDatabaseInfo = extendDatabaseInfo;
25
+ function extendDatabaseInfoFromApps(db, apps) {
26
+ if (!db || !apps)
27
+ return db;
28
+ const dbExt = Object.assign(Object.assign({}, db), { tables: db.tables.map(table => (Object.assign(Object.assign({}, table), { foreignKeys: [
29
+ ...(table.foreignKeys || []),
30
+ ...(0, flatten_1.default)(apps.map(app => app.virtualReferences || []))
31
+ .filter(fk => fk.pureName == table.pureName && fk.schemaName == table.schemaName)
32
+ .map(fk => (Object.assign(Object.assign({}, fk), { constraintType: 'foreignKey', isVirtual: true }))),
33
+ ] }))) });
34
+ return addTableDependencies(dbExt);
35
+ }
36
+ exports.extendDatabaseInfoFromApps = extendDatabaseInfoFromApps;
37
+ function isTableColumnUnique(table, column) {
38
+ if (table.primaryKey && table.primaryKey.columns.length == 1 && table.primaryKey.columns[0].columnName == column) {
39
+ return true;
40
+ }
41
+ const uqs = [...(table.uniques || []), ...(table.indexes || []).filter(x => x.isUnique)];
42
+ if (uqs.find(uq => uq.columns.length == 1 && uq.columns[0].columnName == column)) {
43
+ return true;
44
+ }
45
+ return false;
46
+ }
47
+ exports.isTableColumnUnique = isTableColumnUnique;
@@ -8,6 +8,9 @@ const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
8
8
  function prepareTableForImport(table) {
9
9
  const res = (0, cloneDeep_1.default)(table);
10
10
  res.foreignKeys = [];
11
+ res.indexes = [];
12
+ res.uniques = [];
13
+ res.checks = [];
11
14
  if (res.primaryKey)
12
15
  res.primaryKey.constraintName = null;
13
16
  return res;
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.6.0",
2
+ "version": "4.7.0",
3
3
  "name": "dbgate-tools",
4
4
  "main": "lib/index.js",
5
5
  "typings": "lib/index.d.ts",
@@ -25,14 +25,14 @@
25
25
  ],
26
26
  "devDependencies": {
27
27
  "@types/node": "^13.7.0",
28
- "dbgate-types": "^4.6.0",
28
+ "dbgate-types": "^4.7.0",
29
29
  "jest": "^24.9.0",
30
30
  "ts-jest": "^25.2.1",
31
31
  "typescript": "^4.4.3"
32
32
  },
33
33
  "dependencies": {
34
34
  "lodash": "^4.17.21",
35
- "dbgate-query-splitter": "^4.6.0",
35
+ "dbgate-query-splitter": "^4.7.0",
36
36
  "uuid": "^3.4.0"
37
37
  }
38
38
  }