@klapeks/micro-db-utils 0.0.18 → 0.0.20

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.d.ts CHANGED
@@ -4,3 +4,4 @@ export * from './sql';
4
4
  export * from './connections';
5
5
  export * from './migrations';
6
6
  export * from './selectors';
7
+ export * from './patch.typeorm';
package/dist/index.js CHANGED
@@ -20,3 +20,4 @@ __exportStar(require("./sql"), exports);
20
20
  __exportStar(require("./connections"), exports);
21
21
  __exportStar(require("./migrations"), exports);
22
22
  __exportStar(require("./selectors"), exports);
23
+ __exportStar(require("./patch.typeorm"), exports);
package/dist/micro.sql.js CHANGED
@@ -57,7 +57,12 @@ var MicroSQL;
57
57
  _b.label = 3;
58
58
  case 3:
59
59
  query = (_a);
60
- query = (0, sql_1.toRawSQL)(dbType, query);
60
+ return [4 /*yield*/, (0, sql_1.toRawSQL)(dbType, query, {
61
+ database: dataSource.options.database,
62
+ runAdditionalSQL: dataSource.query
63
+ })];
64
+ case 4:
65
+ query = _b.sent();
61
66
  return [2 /*return*/, dataSource.query(query.query, query.params)];
62
67
  }
63
68
  });
@@ -104,29 +104,34 @@ var SuperMigrations = /** @class */ (function () {
104
104
  case 1: return [4 /*yield*/, _e.sent()];
105
105
  case 2:
106
106
  isTableExistsInfo = _e.sent();
107
- if (!!isTableExistsInfo) return [3 /*break*/, 5];
108
- firstSQL = (function () {
109
- var _a;
110
- var sql = (_a = todoMigrations === null || todoMigrations === void 0 ? void 0 : todoMigrations[0]) === null || _a === void 0 ? void 0 : _a.sql;
111
- if (!sql)
112
- return null;
113
- if (Array.isArray(sql))
114
- sql = sql[0];
115
- return sqlInstance.toRawSQL(sql);
116
- })();
117
- if (!!((_b = (_a = firstSQL === null || firstSQL === void 0 ? void 0 : firstSQL.query) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes('create table'))) return [3 /*break*/, 5];
107
+ if (!!isTableExistsInfo) return [3 /*break*/, 6];
108
+ return [4 /*yield*/, (function () { return __awaiter(_this, void 0, void 0, function () {
109
+ var sql;
110
+ var _a;
111
+ return __generator(this, function (_b) {
112
+ sql = (_a = todoMigrations === null || todoMigrations === void 0 ? void 0 : todoMigrations[0]) === null || _a === void 0 ? void 0 : _a.sql;
113
+ if (!sql)
114
+ return [2 /*return*/, null];
115
+ if (Array.isArray(sql))
116
+ sql = sql[0];
117
+ return [2 /*return*/, sqlInstance.toRawSQL(sql)];
118
+ });
119
+ }); })()];
120
+ case 3:
121
+ firstSQL = _e.sent();
122
+ if (!!((_b = (_a = firstSQL === null || firstSQL === void 0 ? void 0 : firstSQL.query) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes('create table'))) return [3 /*break*/, 6];
118
123
  logger.log("Table ".concat(table, " not found. Migrations ").concat(todoMigrations === null || todoMigrations === void 0 ? void 0 : todoMigrations.length, " will be skipped"));
119
124
  lastMigrationDate = todoMigrations.length ? (_c = todoMigrations === null || todoMigrations === void 0 ? void 0 : todoMigrations[todoMigrations.length - 1]) === null || _c === void 0 ? void 0 : _c.date : undefined;
120
- if (!((todoMigrations === null || todoMigrations === void 0 ? void 0 : todoMigrations.length) && lastMigrationDate)) return [3 /*break*/, 4];
125
+ if (!((todoMigrations === null || todoMigrations === void 0 ? void 0 : todoMigrations.length) && lastMigrationDate)) return [3 /*break*/, 5];
121
126
  return [4 /*yield*/, sqlInstance.runSQL(micro_sql_1.MicroSQL.editData(this.migrationTableName).upsert({
122
127
  table: table,
123
128
  lastMigrationTime: (0, iso_date_time_1.toISODate)(lastMigrationDate)
124
129
  }, ['table']))];
125
- case 3:
130
+ case 4:
126
131
  _e.sent();
127
- _e.label = 4;
128
- case 4: return [2 /*return*/];
129
- case 5:
132
+ _e.label = 5;
133
+ case 5: return [2 /*return*/];
134
+ case 6:
130
135
  _local_runSQL = function (sql, params) { return __awaiter(_this, void 0, void 0, function () {
131
136
  return __generator(this, function (_a) {
132
137
  switch (_a.label) {
@@ -155,61 +160,71 @@ var SuperMigrations = /** @class */ (function () {
155
160
  lastRealMigration = lastRealMigrationDateTime
156
161
  ? new Date(lastRealMigrationDateTime) : null;
157
162
  _i = 0, todoMigrations_1 = todoMigrations;
158
- _e.label = 6;
159
- case 6:
160
- if (!(_i < todoMigrations_1.length)) return [3 /*break*/, 17];
163
+ _e.label = 7;
164
+ case 7:
165
+ if (!(_i < todoMigrations_1.length)) return [3 /*break*/, 20];
161
166
  migration = todoMigrations_1[_i];
162
167
  if (migration.table != table)
163
- return [3 /*break*/, 16];
168
+ return [3 /*break*/, 19];
164
169
  logger;
165
170
  if (lastRealMigration && lastRealMigration.getTime() >= migration.date.getTime()) {
166
- return [3 /*break*/, 16];
171
+ return [3 /*break*/, 19];
167
172
  }
168
173
  runnedMigrationsAmount = onMigrationComplete();
169
174
  migrationName = '"' + table + ' ' + (0, iso_date_time_1.toISODate)(migration.date) + '"';
170
- if (!Array.isArray(migration.sql)) return [3 /*break*/, 11];
171
- sqls = migration.sql.filter(Boolean).map(function (sql) {
172
- var sql2 = sqlInstance.toRawSQL(sql);
173
- sql2.query = utils_1.utils.replaceAll(sql2.query.trim(), "%{table_name}", table);
174
- return sql2;
175
- });
175
+ if (!Array.isArray(migration.sql)) return [3 /*break*/, 13];
176
+ return [4 /*yield*/, Promise.all(migration.sql.filter(Boolean).map(function (sql) { return __awaiter(_this, void 0, void 0, function () {
177
+ var sql2;
178
+ return __generator(this, function (_a) {
179
+ switch (_a.label) {
180
+ case 0: return [4 /*yield*/, sqlInstance.toRawSQL(sql)];
181
+ case 1:
182
+ sql2 = _a.sent();
183
+ sql2.query = utils_1.utils.replaceAll(sql2.query.trim(), "%{table_name}", table);
184
+ return [2 /*return*/, sql2];
185
+ }
186
+ });
187
+ }); }))];
188
+ case 8:
189
+ sqls = _e.sent();
176
190
  logger.log(runnedMigrationsAmount, "| Migrations will be runned:", migrationName, '|\n' + utils_1.terminalColors.cyan, sqls.map(function (s) { return s.query; }));
177
191
  _d = 0, sqls_1 = sqls;
178
- _e.label = 7;
179
- case 7:
180
- if (!(_d < sqls_1.length)) return [3 /*break*/, 10];
192
+ _e.label = 9;
193
+ case 9:
194
+ if (!(_d < sqls_1.length)) return [3 /*break*/, 12];
181
195
  sql = sqls_1[_d];
182
196
  return [4 /*yield*/, _local_runSQL(sql.query, sql.params)];
183
- case 8:
197
+ case 10:
184
198
  _e.sent();
185
- _e.label = 9;
186
- case 9:
187
- _d++;
188
- return [3 /*break*/, 7];
189
- case 10: return [3 /*break*/, 13];
199
+ _e.label = 11;
190
200
  case 11:
191
- sql = sqlInstance.toRawSQL(migration.sql);
201
+ _d++;
202
+ return [3 /*break*/, 9];
203
+ case 12: return [3 /*break*/, 16];
204
+ case 13: return [4 /*yield*/, sqlInstance.toRawSQL(migration.sql)];
205
+ case 14:
206
+ sql = _e.sent();
192
207
  sql.query = utils_1.utils.replaceAll(sql.query.trim(), "%{table_name}", table);
193
208
  logger.log(runnedMigrationsAmount, "| Migration will be runned:", migrationName, '|\n' + utils_1.terminalColors.cyan, sql.query);
194
209
  return [4 /*yield*/, _local_runSQL(sql.query, sql.params)];
195
- case 12:
210
+ case 15:
196
211
  _e.sent();
197
- _e.label = 13;
198
- case 13: return [4 /*yield*/, sqlInstance.runSQL(micro_sql_1.MicroSQL.editData(this.migrationTableName).upsert({
212
+ _e.label = 16;
213
+ case 16: return [4 /*yield*/, sqlInstance.runSQL(micro_sql_1.MicroSQL.editData(this.migrationTableName).upsert({
199
214
  table: table,
200
215
  lastMigrationTime: (0, iso_date_time_1.toISODate)(migration.date)
201
216
  }, ['table']))];
202
- case 14:
217
+ case 17:
203
218
  _e.sent();
204
219
  logger.log(runnedMigrationsAmount, "| Migration", migrationName, "successfully done");
205
220
  return [4 /*yield*/, utils_1.utils.sleep(100)];
206
- case 15:
221
+ case 18:
207
222
  _e.sent();
208
- _e.label = 16;
209
- case 16:
223
+ _e.label = 19;
224
+ case 19:
210
225
  _i++;
211
- return [3 /*break*/, 6];
212
- case 17: return [2 /*return*/];
226
+ return [3 /*break*/, 7];
227
+ case 20: return [2 /*return*/];
213
228
  }
214
229
  });
215
230
  });
@@ -0,0 +1 @@
1
+ export declare function patchTypeorm(): void;
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.patchTypeorm = void 0;
51
+ var typeorm_1 = require("typeorm");
52
+ var _alreadyPatched = false;
53
+ function patchTypeorm() {
54
+ if (_alreadyPatched)
55
+ return;
56
+ { // repository changes
57
+ var originalUpdate_1 = typeorm_1.Repository.prototype.update;
58
+ typeorm_1.Repository.prototype.update = function () {
59
+ var args = [];
60
+ for (var _i = 0; _i < arguments.length; _i++) {
61
+ args[_i] = arguments[_i];
62
+ }
63
+ var _wasDel = false;
64
+ for (var _a = 0, _b = Object.keys(args[0]); _a < _b.length; _a++) {
65
+ var key = _b[_a];
66
+ if (typeof args[1] === 'object' && key in args[1]) {
67
+ if (args[0][key] === args[1][key]) {
68
+ if (!_wasDel) {
69
+ args[1] = __assign({}, args[1]);
70
+ _wasDel = true;
71
+ }
72
+ delete args[1][key];
73
+ }
74
+ }
75
+ }
76
+ return originalUpdate_1.apply(this, args);
77
+ };
78
+ var originalUpsert_1 = typeorm_1.Repository.prototype.upsert;
79
+ typeorm_1.Repository.prototype.upsert = function () {
80
+ var args = [];
81
+ for (var _i = 0; _i < arguments.length; _i++) {
82
+ args[_i] = arguments[_i];
83
+ }
84
+ return __awaiter(this, void 0, void 0, function () {
85
+ return __generator(this, function (_a) {
86
+ if (this.manager.connection.options.type === "mssql") {
87
+ return [2 /*return*/, this.save(args[0])];
88
+ }
89
+ return [2 /*return*/, originalUpsert_1.apply(this, args)];
90
+ });
91
+ });
92
+ };
93
+ }
94
+ { // query builder changes changes
95
+ var whereFix_1 = function (dbtype, args) {
96
+ if (args[0] && typeof args[0] === 'string') {
97
+ if (dbtype == 'mssql') {
98
+ args[0] = args[0].replace(/\btrue\b/g, "1");
99
+ args[0] = args[0].replace(/\bfalse\b/g, "0");
100
+ }
101
+ }
102
+ return args;
103
+ };
104
+ var originalWhere_1 = typeorm_1.SelectQueryBuilder.prototype.where;
105
+ typeorm_1.SelectQueryBuilder.prototype.where = function () {
106
+ var _a;
107
+ var args = [];
108
+ for (var _i = 0; _i < arguments.length; _i++) {
109
+ args[_i] = arguments[_i];
110
+ }
111
+ var dbType = this.connection.options.type
112
+ || ((_a = this.dataSource) === null || _a === void 0 ? void 0 : _a.options.type);
113
+ return originalWhere_1.apply(this, whereFix_1(dbType, args));
114
+ };
115
+ var originalAndWhere_1 = typeorm_1.SelectQueryBuilder.prototype.andWhere;
116
+ typeorm_1.SelectQueryBuilder.prototype.andWhere = function () {
117
+ var _a;
118
+ var args = [];
119
+ for (var _i = 0; _i < arguments.length; _i++) {
120
+ args[_i] = arguments[_i];
121
+ }
122
+ var dbType = this.connection.options.type
123
+ || ((_a = this.dataSource) === null || _a === void 0 ? void 0 : _a.options.type);
124
+ return originalAndWhere_1.apply(this, whereFix_1(dbType, args));
125
+ };
126
+ }
127
+ _alreadyPatched = true;
128
+ }
129
+ exports.patchTypeorm = patchTypeorm;
@@ -4,16 +4,18 @@ export interface SQLCommandData {
4
4
  params?: any[];
5
5
  }
6
6
  export interface SQLCommandContext {
7
+ database: string;
8
+ runAdditionalSQL: (sql: string, params?: any[]) => any;
7
9
  }
8
10
  export interface ISQLCommandAdapter {
9
- toMySQL(ctx?: SQLCommandContext): SQLCommandData | string;
10
- toMSSQL(ctx?: SQLCommandContext): SQLCommandData | string;
11
- toSQLite(ctx?: SQLCommandContext): SQLCommandData | string;
11
+ toMySQL(ctx?: SQLCommandContext): SQLCommandData | string | Promise<string>;
12
+ toMSSQL(ctx?: SQLCommandContext): SQLCommandData | string | Promise<string>;
13
+ toSQLite(ctx?: SQLCommandContext): SQLCommandData | string | Promise<string>;
12
14
  }
13
15
  export declare abstract class AbstractSQLCommand implements ISQLCommandAdapter {
14
- abstract toMySQL(ctx?: SQLCommandContext): SQLCommandData | string;
15
- abstract toMSSQL(ctx?: SQLCommandContext): SQLCommandData | string;
16
- abstract toSQLite(ctx?: SQLCommandContext): SQLCommandData | string;
16
+ abstract toMySQL(ctx?: SQLCommandContext): SQLCommandData | string | Promise<string>;
17
+ abstract toMSSQL(ctx?: SQLCommandContext): SQLCommandData | string | Promise<string>;
18
+ abstract toSQLite(ctx?: SQLCommandContext): SQLCommandData | string | Promise<string>;
17
19
  }
18
20
  export declare const rawSQL: (sqls: {
19
21
  defaultQuery: string;
@@ -21,4 +23,4 @@ export declare const rawSQL: (sqls: {
21
23
  mssqlQuery?: string;
22
24
  sqliteQuery?: string;
23
25
  }) => ISQLCommandAdapter;
24
- export declare function toRawSQL(dbType: DatabaseOptions['type'], query: ISQLCommandAdapter | SQLCommandData | string): SQLCommandData;
26
+ export declare function toRawSQL(dbType: DatabaseOptions['type'], query: ISQLCommandAdapter | SQLCommandData | string, ctx?: SQLCommandContext): Promise<SQLCommandData>;
@@ -1,4 +1,40 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
2
38
  Object.defineProperty(exports, "__esModule", { value: true });
3
39
  exports.toRawSQL = exports.rawSQL = exports.AbstractSQLCommand = void 0;
4
40
  var AbstractSQLCommand = /** @class */ (function () {
@@ -15,19 +51,35 @@ var rawSQL = function (sqls) {
15
51
  };
16
52
  };
17
53
  exports.rawSQL = rawSQL;
18
- function toRawSQL(dbType, query) {
19
- if (typeof query === 'string')
20
- return { query: query };
21
- if (typeof query === 'object' && !('query' in query)) {
22
- if (dbType === 'mysql')
23
- query = query.toMySQL({});
24
- else if (dbType === 'mssql')
25
- query = query.toMSSQL({});
26
- else if (dbType === 'sqlite')
27
- query = query.toSQLite({});
28
- else
29
- throw "Unknown database type: " + dbType;
30
- }
31
- return typeof query === 'string' ? { query: query } : query;
54
+ function toRawSQL(dbType, query, ctx) {
55
+ return __awaiter(this, void 0, void 0, function () {
56
+ return __generator(this, function (_a) {
57
+ switch (_a.label) {
58
+ case 0:
59
+ if (typeof query === 'string')
60
+ return [2 /*return*/, { query: query }];
61
+ if (!(typeof query === 'object' && !('query' in query))) return [3 /*break*/, 7];
62
+ if (!(dbType === 'mysql')) return [3 /*break*/, 2];
63
+ return [4 /*yield*/, query.toMySQL(ctx)];
64
+ case 1:
65
+ query = _a.sent();
66
+ return [3 /*break*/, 7];
67
+ case 2:
68
+ if (!(dbType === 'mssql')) return [3 /*break*/, 4];
69
+ return [4 /*yield*/, query.toMSSQL(ctx)];
70
+ case 3:
71
+ query = _a.sent();
72
+ return [3 /*break*/, 7];
73
+ case 4:
74
+ if (!(dbType === 'sqlite')) return [3 /*break*/, 6];
75
+ return [4 /*yield*/, query.toSQLite(ctx)];
76
+ case 5:
77
+ query = _a.sent();
78
+ return [3 /*break*/, 7];
79
+ case 6: throw "Unknown database type: " + dbType;
80
+ case 7: return [2 /*return*/, typeof query === 'string' ? { query: query } : query];
81
+ }
82
+ });
83
+ });
32
84
  }
33
85
  exports.toRawSQL = toRawSQL;
@@ -1,6 +1,43 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
2
38
  Object.defineProperty(exports, "__esModule", { value: true });
3
39
  exports.SQLAlterCommand = void 0;
40
+ var utils_1 = require("@klapeks/utils");
4
41
  var column_type_parser_1 = require("../column.type.parser");
5
42
  var SQLAlterCommand = /** @class */ (function () {
6
43
  function SQLAlterCommand(table) {
@@ -35,7 +72,70 @@ var SQLAlterCommand = /** @class */ (function () {
35
72
  + column_type_parser_1.MicroColumnTypeObject.toSQLQuery('mysql', type, 'alter-column') + ';'; },
36
73
  toMSSQL: function () { return "ALTER TABLE [".concat(_this.table, "] ALTER COLUMN [").concat(column, "] ")
37
74
  + column_type_parser_1.MicroColumnTypeObject.toSQLQuery('mssql', type, 'alter-column') + ';'; },
38
- toSQLite: function () { throw "Not implemented yet: changeColumnType for sqlite :("; },
75
+ toSQLite: function (ctx) { return __awaiter(_this, void 0, void 0, function () {
76
+ var tableCreateOld, indexesToRecreate, tableCreateArray, _wasChanges, tableColumnNames, _loop_1, i, RECHANGE_TABLE_NAME;
77
+ var _a, _b;
78
+ return __generator(this, function (_c) {
79
+ switch (_c.label) {
80
+ case 0:
81
+ if (!(ctx === null || ctx === void 0 ? void 0 : ctx.runAdditionalSQL))
82
+ throw "No runAdditionalSQL in context";
83
+ return [4 /*yield*/, ctx.runAdditionalSQL("\n SELECT sql FROM sqlite_master WHERE type = \"table\" AND name = \"".concat(this.table, "\";\n "))];
84
+ case 1:
85
+ tableCreateOld = (_b = (_a = (_c.sent())) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.sql;
86
+ if (!tableCreateOld)
87
+ throw "Table ".concat(this.table, " not exists");
88
+ return [4 /*yield*/, ctx.runAdditionalSQL("\n SELECT sql FROM sqlite_master WHERE type = \"index\"\n AND tbl_name = \"".concat(this.table, "\" AND sql IS NOT NULL;\n "))];
89
+ case 2:
90
+ indexesToRecreate = (_c.sent()).map(function (s) { return s.sql || s; }).filter(Boolean).join("; ") + ';';
91
+ tableCreateArray = tableCreateOld.split('\n');
92
+ _wasChanges = false;
93
+ tableColumnNames = [];
94
+ _loop_1 = function (i) {
95
+ if (tableCreateArray[i].trim()[0] == '"') {
96
+ var str = tableCreateArray[i].trim().substring(1);
97
+ tableColumnNames.push(str.substring(0, str.indexOf('"')));
98
+ }
99
+ if (!tableCreateArray[i].includes('"' + column + '"'))
100
+ return "continue";
101
+ var arr = tableCreateArray[i].split('\t');
102
+ var indexName = arr.findIndex(function (a) { return a == '"' + column + '"'; });
103
+ if (indexName < 0)
104
+ return "continue";
105
+ arr[indexName + 1] = (function () {
106
+ var str = column_type_parser_1.MicroColumnTypeObject.toSQLQuery('sqlite', type);
107
+ if (str.startsWith('text('))
108
+ str = str.replace("text(", "varchar(");
109
+ if (arr[indexName + 1].toLowerCase().includes(' unique'))
110
+ str += ' UNIQUE';
111
+ if (arr[indexName + 1].endsWith(','))
112
+ str += ',';
113
+ return str;
114
+ })();
115
+ // console.log("CHANGES ARR:", arr);
116
+ tableCreateArray[i] = arr.join('\t');
117
+ _wasChanges = true;
118
+ };
119
+ for (i = 0; i < tableCreateArray.length; i++) {
120
+ _loop_1(i);
121
+ }
122
+ if (!_wasChanges)
123
+ return [2 /*return*/, "SELECT 1"];
124
+ RECHANGE_TABLE_NAME = this.table + "___rechange_" + utils_1.utils.randomInclude(99);
125
+ tableCreateArray[0] = "CREATE TABLE \"".concat(RECHANGE_TABLE_NAME, "\" (");
126
+ // console.log("Table create:", tableCreateNew);
127
+ // console.log("INDEXES:", indexesToRecreate);
128
+ // console.log("Colums:", tableColumnNames);
129
+ // const hasColumnIndex = tableColumns.findIndex(
130
+ // (row) => row.name === column
131
+ // );
132
+ // if (hasColumnIndex < 0) return "SELECT 1";
133
+ // // ctx?.runAdditionalSQL
134
+ // // throw "Not implemented yet: changeColumnType for sqlite"
135
+ return [2 /*return*/, "\n BEGIN;\n ".concat(tableCreateArray.join('\n'), ";\n INSERT INTO ").concat(RECHANGE_TABLE_NAME, " (").concat(tableColumnNames.join(', '), ") \n SELECT ").concat(tableColumnNames.join(', '), " FROM ").concat(this.table, ";\n DROP TABLE ").concat(this.table, ";\n ALTER TABLE ").concat(RECHANGE_TABLE_NAME, " RENAME TO ").concat(this.table, ";\n ").concat(indexesToRecreate, "\n COMMIT;\n ")];
136
+ }
137
+ });
138
+ }); },
39
139
  };
40
140
  };
41
141
  return SQLAlterCommand;
@@ -8,7 +8,7 @@ export declare abstract class AbstractSQLConnection {
8
8
  abstract initConnection(): Promise<void>;
9
9
  abstract destroyConnection(): Promise<void>;
10
10
  protected abstract sendSQL<T = any>(query: string, params?: any[]): Promise<T[]>;
11
- toRawSQL(sql: ISQLCommandAdapter | SQLCommandData | string): SQLCommandData;
11
+ toRawSQL(sql: ISQLCommandAdapter | SQLCommandData | string): Promise<SQLCommandData>;
12
12
  runSQL<T = any>(query: SQLCommandData): Promise<T[]>;
13
13
  runSQL<T = any>(query: ISQLCommandAdapter): Promise<T[]>;
14
14
  runSQL<T = any>(query: AbstractSQLCommand): Promise<T[]>;
@@ -43,6 +43,7 @@ var AbstractSQLConnection = /** @class */ (function () {
43
43
  function AbstractSQLConnection(rawOptions, abstractCommandFunctionName) {
44
44
  this.rawOptions = rawOptions;
45
45
  this.abstractCommandFunctionName = abstractCommandFunctionName;
46
+ this.sendSQL = this.sendSQL.bind(this);
46
47
  }
47
48
  Object.defineProperty(AbstractSQLConnection.prototype, "databaseName", {
48
49
  get: function () {
@@ -52,7 +53,17 @@ var AbstractSQLConnection = /** @class */ (function () {
52
53
  configurable: true
53
54
  });
54
55
  AbstractSQLConnection.prototype.toRawSQL = function (sql) {
55
- return (0, commands_1.toRawSQL)(this.rawOptions.type, sql);
56
+ return __awaiter(this, void 0, void 0, function () {
57
+ return __generator(this, function (_a) {
58
+ switch (_a.label) {
59
+ case 0: return [4 /*yield*/, (0, commands_1.toRawSQL)(this.rawOptions.type, sql, {
60
+ database: this.databaseName,
61
+ runAdditionalSQL: this.sendSQL
62
+ })];
63
+ case 1: return [2 /*return*/, _a.sent()];
64
+ }
65
+ });
66
+ });
56
67
  };
57
68
  AbstractSQLConnection.prototype.runSQL = function (query, params) {
58
69
  var _a;
@@ -71,7 +82,8 @@ var AbstractSQLConnection = /** @class */ (function () {
71
82
  abstrKey = this.abstractCommandFunctionName;
72
83
  if (!(abstrKey in query)) return [3 /*break*/, 2];
73
84
  return [4 /*yield*/, ((_a = query === null || query === void 0 ? void 0 : query[abstrKey]) === null || _a === void 0 ? void 0 : _a.call(query, {
74
- database: this.databaseName
85
+ database: this.databaseName,
86
+ runAdditionalSQL: this.sendSQL
75
87
  }))];
76
88
  case 1:
77
89
  query = _b.sent();
@@ -136,7 +136,7 @@ var SQLiteConnection = /** @class */ (function (_super) {
136
136
  }
137
137
  if (!params)
138
138
  params = [];
139
- if (upperSQL.startsWith('SELECT')) {
139
+ if (upperSQL.startsWith('SELECT') || upperSQL.startsWith("PRAGMA")) {
140
140
  return connection.all(query, params, function (err1, rows) {
141
141
  if (err1)
142
142
  return reject(err1);
@@ -9,18 +9,7 @@ export declare function createRelation(target: string, type: "one-to-many" | "on
9
9
  cascade: boolean;
10
10
  inverseSide: string;
11
11
  };
12
- export declare const MULTISQL_COLUMNS_TYPES: {
13
- dbtype: "sqlite" | "mysql" | "postgres" | "mssql";
14
- int32: "int" | "integer";
15
- string: "character varying" | "nvarchar" | "varchar" | "text";
16
- boolean: "boolean" | "tinyint" | "integer" | "bit";
17
- enum: "simple-enum" | "enum";
18
- bigint: "bigint" | "integer";
19
- datetime: "datetime" | "datetime2" | "timestamp";
20
- float32: "float" | "double";
21
- float64: "float" | "double";
22
- json: "simple-json" | "json";
23
- };
12
+ export declare const MULTISQL_COLUMNS_TYPES: import("@klapeks/utils").IDatabaseColumnTypesList;
24
13
  export declare const FloatingColumn: MicroColumnTypeObject;
25
14
  export declare const NullableFloatingColumn: MicroColumnTypeObject;
26
15
  export declare const Float64Column: MicroColumnTypeObject;
@@ -18,7 +18,7 @@ function createRelation(target, type, inverseSide, cascade) {
18
18
  return { target: target, type: type, cascade: cascade, inverseSide: inverseSide };
19
19
  }
20
20
  exports.createRelation = createRelation;
21
- exports.MULTISQL_COLUMNS_TYPES = (0, utils_1.getDatabaseColumnTypes)();
21
+ exports.MULTISQL_COLUMNS_TYPES = (0, utils_1.getEnvDatabaseColumnTypes)();
22
22
  exports.FloatingColumn = {
23
23
  type: exports.MULTISQL_COLUMNS_TYPES.float32, default: 0
24
24
  // type: "decimal", precision: 10, scale: 6, default: 0
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@klapeks/micro-db-utils",
3
3
  "description": "klapeks utils for db and other storages",
4
- "version": "0.0.18",
4
+ "version": "0.0.20",
5
5
  "type": "commonjs",
6
6
  "author": "Klapeks",
7
7
  "license": "ISC",
8
8
  "scripts": {
9
9
  "patch": "npm version patch -f --no-git-tag-version",
10
10
  "build": "npm run patch && tsc --skipLibCheck",
11
+ "build:no-patch": "tsc --skipLibCheck",
11
12
  "prepublishOnly": "tsc --skipLibCheck"
12
13
  },
13
14
  "keywords": [
@@ -22,7 +23,7 @@
22
23
  "@aws-sdk/client-s3": "^3.842.0",
23
24
  "@aws-sdk/s3-request-presigner": "^3.844.0",
24
25
  "@klapeks/api-creation-tools": "^0.0.7",
25
- "@klapeks/utils": "^0.1.9",
26
+ "@klapeks/utils": "^0.2.1",
26
27
  "@types/mssql": "^12.3.0",
27
28
  "@types/node": "^18.11.18",
28
29
  "@types/pg": "^8.23.1",