@klapeks/micro-db-utils 0.0.16 → 0.0.18

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.
@@ -97,13 +97,13 @@ var AbstractSelectHandler = /** @class */ (function () {
97
97
  });
98
98
  };
99
99
  AbstractSelectHandler.prototype.getSumStatistic = function (sumField, strWhere) {
100
- var _a;
100
+ var _a, _b;
101
101
  return __awaiter(this, void 0, void 0, function () {
102
- var stat, time, response, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
103
- var _p, _q;
102
+ var stat, time, response, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
103
+ var _q, _r;
104
104
  var _this = this;
105
- return __generator(this, function (_r) {
106
- switch (_r.label) {
105
+ return __generator(this, function (_s) {
106
+ switch (_s.label) {
107
107
  case 0:
108
108
  stat = function (fromDate, time) { return __awaiter(_this, void 0, void 0, function () {
109
109
  var expr, isoDate, sum;
@@ -128,65 +128,65 @@ var AbstractSelectHandler = /** @class */ (function () {
128
128
  });
129
129
  }); };
130
130
  time = new Date().toLocaleTimeString('uk-UA');
131
- _p = {
131
+ _q = {
132
132
  serverTime: time
133
133
  };
134
- return [4 /*yield*/, this.getTotal()];
134
+ return [4 /*yield*/, this.runSQL_One("\n SELECT COUNT(1) AS count\n FROM ".concat(this.getTableName(), " \n ").concat(strWhere ? ("WHERE " + strWhere) : '', "\n "))];
135
135
  case 1:
136
- response = (_p.count = _r.sent(),
137
- _p);
138
- _b = response;
139
- _q = {
136
+ response = (_q.count = (_a = (_s.sent())) === null || _a === void 0 ? void 0 : _a.count,
137
+ _q);
138
+ _c = response;
139
+ _r = {
140
140
  from: new Date(0)
141
141
  };
142
- return [4 /*yield*/, this.runSQL_One("\n SELECT SUM(".concat(sumField, ") as sum\n FROM ").concat(this.getTableName(), "\n ").concat(strWhere ? ("WHERE " + strWhere) : '', "\n "))];
142
+ return [4 /*yield*/, this.runSQL_One("\n SELECT SUM(".concat(sumField, ") AS sum\n FROM ").concat(this.getTableName(), "\n ").concat(strWhere ? ("WHERE " + strWhere) : '', "\n "))];
143
143
  case 2:
144
- _b.total = (_q.sum = (_a = (_r.sent())) === null || _a === void 0 ? void 0 : _a.sum,
145
- _q);
146
- _c = response;
144
+ _c.total = (_r.sum = (_b = (_s.sent())) === null || _b === void 0 ? void 0 : _b.sum,
145
+ _r);
146
+ _d = response;
147
147
  return [4 /*yield*/, stat(new Date())];
148
148
  case 3:
149
- _c.thisDay = _r.sent();
150
- _d = response;
149
+ _d.thisDay = _s.sent();
150
+ _e = response;
151
151
  return [4 /*yield*/, stat(function (d) { return d.setDate(d.getDate() - (d.getDay() || 7) + 1); })];
152
152
  case 4:
153
- _d.thisWeek = _r.sent();
154
- _e = response;
153
+ _e.thisWeek = _s.sent();
154
+ _f = response;
155
155
  return [4 /*yield*/, stat(function (d) { return d.setDate(1); })];
156
156
  case 5:
157
- _e.thisMonth = _r.sent();
158
- _f = response;
157
+ _f.thisMonth = _s.sent();
158
+ _g = response;
159
159
  return [4 /*yield*/, stat(function (d) { d.setMonth(0); d.setDate(1); })];
160
160
  case 6:
161
- _f.thisYear = _r.sent();
162
- _g = response;
161
+ _g.thisYear = _s.sent();
162
+ _h = response;
163
163
  return [4 /*yield*/, stat(function (d) { return d.setDate(d.getDate() - 1); }, time)];
164
164
  case 7:
165
- _g.past24hours = _r.sent();
166
- _h = response;
165
+ _h.past24hours = _s.sent();
166
+ _j = response;
167
167
  return [4 /*yield*/, stat(function (d) { return d.setDate(d.getDate() - 2); })];
168
168
  case 8:
169
- _h.past3days = _r.sent();
170
- _j = response;
169
+ _j.past3days = _s.sent();
170
+ _k = response;
171
171
  return [4 /*yield*/, stat(function (d) { return d.setDate(d.getDate() - 6); })];
172
172
  case 9:
173
- _j.past7days = _r.sent();
174
- _k = response;
173
+ _k.past7days = _s.sent();
174
+ _l = response;
175
175
  return [4 /*yield*/, stat(function (d) { return d.setDate(d.getDate() - 13); })];
176
176
  case 10:
177
- _k.past14days = _r.sent();
178
- _l = response;
177
+ _l.past14days = _s.sent();
178
+ _m = response;
179
179
  return [4 /*yield*/, stat(function (d) { return d.setDate(d.getDate() - 29); })];
180
180
  case 11:
181
- _l.past30days = _r.sent();
182
- _m = response;
181
+ _m.past30days = _s.sent();
182
+ _o = response;
183
183
  return [4 /*yield*/, stat(function (d) { return d.setMonth(d.getMonth() - 6); })];
184
184
  case 12:
185
- _m.past6months = _r.sent();
186
- _o = response;
185
+ _o.past6months = _s.sent();
186
+ _p = response;
187
187
  return [4 /*yield*/, stat(function (d) { return d.setMonth(d.getMonth() - 12); })];
188
188
  case 13:
189
- _o.past12months = _r.sent();
189
+ _p.past12months = _s.sent();
190
190
  return [2 /*return*/, response];
191
191
  }
192
192
  });
@@ -1,6 +1,6 @@
1
- import { DatabaseOptions } from "@klapeks/utils";
1
+ import { DatabaseOptions, getRawDatabaseColumnTypeOfTypeORM } from "@klapeks/utils";
2
2
  import { ColumnType } from "typeorm";
3
- export declare function getRawDatabaseColumnTypeOfTypeORM(dbtype: DatabaseOptions['type'], type: ColumnType): ColumnType;
3
+ export { getRawDatabaseColumnTypeOfTypeORM };
4
4
  export interface MicroColumnTypeObject {
5
5
  type: ColumnType;
6
6
  primary?: boolean;
@@ -1,40 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MicroColumnTypeObject = exports.getRawDatabaseColumnTypeOfTypeORM = void 0;
4
- var utils_1 = require("../utils");
5
- // https://vscode.dev/github.com/typeorm/typeorm/blob/master/src/driver/mysql/MysqlDriver.ts#L750
6
- // https://vscode.dev/github.com/typeorm/typeorm/blob/master/src/driver/sqlserver/SqlServerDriver.ts#L678
7
- function getRawDatabaseColumnTypeOfTypeORM(dbtype, type) {
8
- if (type === Number) {
9
- if (dbtype == 'sqlite')
10
- return 'integer';
11
- if (dbtype == 'postgres')
12
- return 'integer';
13
- return 'int';
14
- }
15
- if (type === String) {
16
- if (dbtype === 'postgres')
17
- return 'character varying';
18
- if (dbtype === 'mssql')
19
- return 'nvarchar';
20
- return 'varchar';
21
- }
22
- if (type === Boolean) {
23
- if (dbtype === 'mssql')
24
- return 'bit';
25
- if (dbtype === 'mysql')
26
- return 'tinyint';
27
- return 'boolean';
28
- }
29
- if (type === Date)
30
- return utils_1.MULTISQL_COLUMNS_TYPES.datetime;
31
- return type;
32
- }
33
- exports.getRawDatabaseColumnTypeOfTypeORM = getRawDatabaseColumnTypeOfTypeORM;
4
+ var utils_1 = require("@klapeks/utils");
5
+ Object.defineProperty(exports, "getRawDatabaseColumnTypeOfTypeORM", { enumerable: true, get: function () { return utils_1.getRawDatabaseColumnTypeOfTypeORM; } });
34
6
  var MicroColumnTypeObject;
35
7
  (function (MicroColumnTypeObject) {
36
8
  function toSQLQuery(dbType, options, queryType) {
37
- var columnType = getRawDatabaseColumnTypeOfTypeORM(dbType, options.type);
9
+ var columnType = (0, utils_1.getRawDatabaseColumnTypeOfTypeORM)(dbType, options.type);
38
10
  var columnLength = options.length || ((columnType === 'varchar'
39
11
  || columnType === 'nvarchar') ? 255 : undefined);
40
12
  var str = columnType + (columnLength ? "(".concat(columnLength, ")") : '');
@@ -49,6 +21,7 @@ var MicroColumnTypeObject;
49
21
  str += ' IDENTITY';
50
22
  else if (dbType === 'mysql')
51
23
  str += ' AUTO_INCREMENT';
24
+ else if (dbType === 'sqlite') { /** after primary key */ }
52
25
  else
53
26
  throw "options.generated is not supported yet for " + dbType;
54
27
  }
@@ -85,6 +58,9 @@ var MicroColumnTypeObject;
85
58
  if (options.primary) {
86
59
  str += ' PRIMARY KEY';
87
60
  }
61
+ if (dbType === 'sqlite' && options.generated) {
62
+ str += ' AUTOINCREMENT';
63
+ }
88
64
  }
89
65
  return str;
90
66
  }
@@ -8,14 +8,17 @@ export interface SQLCommandContext {
8
8
  export interface ISQLCommandAdapter {
9
9
  toMySQL(ctx?: SQLCommandContext): SQLCommandData | string;
10
10
  toMSSQL(ctx?: SQLCommandContext): SQLCommandData | string;
11
+ toSQLite(ctx?: SQLCommandContext): SQLCommandData | string;
11
12
  }
12
13
  export declare abstract class AbstractSQLCommand implements ISQLCommandAdapter {
13
14
  abstract toMySQL(ctx?: SQLCommandContext): SQLCommandData | string;
14
15
  abstract toMSSQL(ctx?: SQLCommandContext): SQLCommandData | string;
16
+ abstract toSQLite(ctx?: SQLCommandContext): SQLCommandData | string;
15
17
  }
16
18
  export declare const rawSQL: (sqls: {
17
19
  defaultQuery: string;
18
20
  mysqlQuery?: string;
19
21
  mssqlQuery?: string;
22
+ sqliteQuery?: string;
20
23
  }) => ISQLCommandAdapter;
21
24
  export declare function toRawSQL(dbType: DatabaseOptions['type'], query: ISQLCommandAdapter | SQLCommandData | string): SQLCommandData;
@@ -11,6 +11,7 @@ var rawSQL = function (sqls) {
11
11
  return {
12
12
  toMySQL: function () { return sqls.mysqlQuery || sqls.defaultQuery; },
13
13
  toMSSQL: function () { return sqls.mssqlQuery || sqls.defaultQuery; },
14
+ toSQLite: function () { return sqls.sqliteQuery || sqls.defaultQuery; },
14
15
  };
15
16
  };
16
17
  exports.rawSQL = rawSQL;
@@ -22,6 +23,8 @@ function toRawSQL(dbType, query) {
22
23
  query = query.toMySQL({});
23
24
  else if (dbType === 'mssql')
24
25
  query = query.toMSSQL({});
26
+ else if (dbType === 'sqlite')
27
+ query = query.toSQLite({});
25
28
  else
26
29
  throw "Unknown database type: " + dbType;
27
30
  }
@@ -5,6 +5,6 @@ export declare class SQLAlterCommand {
5
5
  constructor(table: string);
6
6
  array(cb: (t: SQLAlterCommand) => ISQLCommandAdapter[]): ISQLCommandAdapter[];
7
7
  renameColumn(old_name: string, new_name: string): ISQLCommandAdapter;
8
- changeColumnType(column: string, type: MicroColumnTypeObject): ISQLCommandAdapter;
9
8
  addColumn(column: string, type: MicroColumnTypeObject): ISQLCommandAdapter;
9
+ changeColumnType(column: string, type: MicroColumnTypeObject): ISQLCommandAdapter;
10
10
  }
@@ -13,25 +13,29 @@ var SQLAlterCommand = /** @class */ (function () {
13
13
  var _this = this;
14
14
  return {
15
15
  toMySQL: function () { return "ALTER TABLE `".concat(_this.table, "` RENAME COLUMN `").concat(old_name, "` TO `").concat(new_name, "`;"); },
16
- toMSSQL: function () { return "EXEC sp_rename '".concat(_this.table, ".").concat(old_name, "', '").concat(new_name, "', 'COLUMN';"); }
16
+ toMSSQL: function () { return "EXEC sp_rename '".concat(_this.table, ".").concat(old_name, "', '").concat(new_name, "', 'COLUMN';"); },
17
+ toSQLite: function () { return "ALTER TABLE \"".concat(_this.table, "\" RENAME COLUMN \"").concat(old_name, "\" TO \"").concat(new_name, "\";"); },
17
18
  };
18
19
  };
19
- SQLAlterCommand.prototype.changeColumnType = function (column, type) {
20
+ SQLAlterCommand.prototype.addColumn = function (column, type) {
20
21
  var _this = this;
21
22
  return {
22
- toMySQL: function () { return "ALTER TABLE `".concat(_this.table, "` MODIFY COLUMN `").concat(column, "` ")
23
+ toMySQL: function () { return "ALTER TABLE `".concat(_this.table, "` ADD COLUMN `").concat(column, "` ")
23
24
  + column_type_parser_1.MicroColumnTypeObject.toSQLQuery('mysql', type, 'alter-column') + ';'; },
24
- toMSSQL: function () { return "ALTER TABLE [".concat(_this.table, "] ALTER COLUMN [").concat(column, "] ")
25
- + column_type_parser_1.MicroColumnTypeObject.toSQLQuery('mssql', type, 'alter-column') + ';'; }
25
+ toMSSQL: function () { return "ALTER TABLE [".concat(_this.table, "] ADD [").concat(column, "] ")
26
+ + column_type_parser_1.MicroColumnTypeObject.toSQLQuery('mssql', type, 'alter-column') + ';'; },
27
+ toSQLite: function () { return "ALTER TABLE \"".concat(_this.table, "\" ADD COLUMN \"").concat(column, "\" ")
28
+ + column_type_parser_1.MicroColumnTypeObject.toSQLQuery("sqlite", type, "alter-column") + ";"; }
26
29
  };
27
30
  };
28
- SQLAlterCommand.prototype.addColumn = function (column, type) {
31
+ SQLAlterCommand.prototype.changeColumnType = function (column, type) {
29
32
  var _this = this;
30
33
  return {
31
- toMySQL: function () { return "ALTER TABLE `".concat(_this.table, "` ADD COLUMN `").concat(column, "` ")
34
+ toMySQL: function () { return "ALTER TABLE `".concat(_this.table, "` MODIFY COLUMN `").concat(column, "` ")
32
35
  + column_type_parser_1.MicroColumnTypeObject.toSQLQuery('mysql', type, 'alter-column') + ';'; },
33
- toMSSQL: function () { return "ALTER TABLE [".concat(_this.table, "] ADD [").concat(column, "] ")
34
- + column_type_parser_1.MicroColumnTypeObject.toSQLQuery('mssql', type, 'alter-column') + ';'; }
36
+ toMSSQL: function () { return "ALTER TABLE [".concat(_this.table, "] ALTER COLUMN [").concat(column, "] ")
37
+ + column_type_parser_1.MicroColumnTypeObject.toSQLQuery('mssql', type, 'alter-column') + ';'; },
38
+ toSQLite: function () { throw "Not implemented yet: changeColumnType for sqlite :("; },
35
39
  };
36
40
  };
37
41
  return SQLAlterCommand;
@@ -2,6 +2,7 @@ import { ISQLCommandAdapter } from "./abstract.sql.command";
2
2
  export declare class SQLEditDataCommands {
3
3
  private readonly table;
4
4
  constructor(table: string);
5
+ insert(data: any): ISQLCommandAdapter;
5
6
  update(data: any, where: any): ISQLCommandAdapter;
6
7
  upsert(data: any, idKeys: string[]): ISQLCommandAdapter;
7
8
  }
@@ -26,15 +26,35 @@ var SQLEditDataCommands = /** @class */ (function () {
26
26
  function SQLEditDataCommands(table) {
27
27
  this.table = table;
28
28
  }
29
+ SQLEditDataCommands.prototype.insert = function (data) {
30
+ var _this = this;
31
+ if (!data)
32
+ throw "No data param";
33
+ var dataKeys = Object.keys(data);
34
+ return {
35
+ toMySQL: function () { return ({
36
+ query: "\n INSERT INTO `".concat(_this.table, "` \n (").concat(dataKeys.map(function (key) { return "`".concat(key, "`"); }).join(', '), ") \n VALUES (").concat(dataKeys.map(function () { return '?'; }).join(', '), ");\n "),
37
+ params: Object.values(data),
38
+ }); },
39
+ toMSSQL: function () { return ({
40
+ query: "\n INSERT INTO [".concat(_this.table, "]\n (").concat(dataKeys.map(function (key) { return "[".concat(key, "]"); }).join(', '), ")\n VALUES (").concat(dataKeys.map(function (key) { return '@' + key; }).join(', '), ");\n "),
41
+ params: data,
42
+ }); },
43
+ toSQLite: function () { return ({
44
+ query: "\n INSERT INTO \"".concat(_this.table, "\" \n (").concat(dataKeys.map(function (key) { return "\"".concat(key, "\""); }).join(', '), ") \n VALUES (").concat(dataKeys.map(function () { return '?'; }).join(', '), ");\n "),
45
+ params: Object.values(data),
46
+ }); },
47
+ };
48
+ };
29
49
  SQLEditDataCommands.prototype.update = function (data, where) {
30
50
  var _this = this;
31
51
  return {
32
52
  toMySQL: function () { return ({
33
- query: "\n UPDATE `".concat(_this.table, "`\n SET ").concat(Object.keys(data).map(function (key) { return "`".concat(key, "` = ?"); }).join(','), "\n WHERE ").concat(Object.keys(where).map(function (key) { return (0, raw_where_utils_1.converWhereQuery)('mysql', key, data[key], '?'); }).join(' AND '), ";\n "),
53
+ query: "\n UPDATE `".concat(_this.table, "`\n SET ").concat(Object.keys(data).map(function (key) { return "`".concat(key, "` = ?"); }).join(', '), "\n WHERE ").concat(Object.keys(where).map(function (key) { return (0, raw_where_utils_1.converWhereQuery)('mysql', key, data[key], '?'); }).join(' AND '), ";\n "),
34
54
  params: __spreadArray(__spreadArray([], Object.values(data), true), Object.values(where), true)
35
55
  }); },
36
56
  toMSSQL: function () { return ({
37
- query: "\n UPDATE [".concat(_this.table, "] \n SET ").concat(Object.keys(data).map(function (key) { return "[".concat(key, "] = @").concat(key); }).join(','), "\n WHERE ").concat(Object.keys(where).map(function (key) { return (0, raw_where_utils_1.converWhereQuery)('mssql', key, data[key], 'where_' + key); }).join(' AND '), ";\n "),
57
+ query: "\n UPDATE [".concat(_this.table, "] \n SET ").concat(Object.keys(data).map(function (key) { return "[".concat(key, "] = @").concat(key); }).join(', '), "\n WHERE ").concat(Object.keys(where).map(function (key) { return (0, raw_where_utils_1.converWhereQuery)('mssql', key, data[key], 'where_' + key); }).join(' AND '), ";\n "),
38
58
  params: (function () {
39
59
  var params = __assign({}, data);
40
60
  for (var _i = 0, _a = Object.keys(where); _i < _a.length; _i++) {
@@ -44,6 +64,10 @@ var SQLEditDataCommands = /** @class */ (function () {
44
64
  return params;
45
65
  })()
46
66
  }); },
67
+ toSQLite: function () { return ({
68
+ query: "\n UPDATE \"".concat(_this.table, "\" \n SET ").concat(Object.keys(data).map(function (key) { return "\"".concat(key, "\" = ?"); }).join(', '), "\n WHERE ").concat(Object.keys(where).map(function (key) { return (0, raw_where_utils_1.converWhereQuery)('sqlite', key, where[key], '?'); }).join(' AND '), ";"),
69
+ params: __spreadArray(__spreadArray([], Object.values(data), true), Object.values(where), true)
70
+ }); },
47
71
  };
48
72
  };
49
73
  SQLEditDataCommands.prototype.upsert = function (data, idKeys) {
@@ -73,6 +97,12 @@ var SQLEditDataCommands = /** @class */ (function () {
73
97
  query: "\n UPDATE [".concat(_this.table, "] \n SET ").concat(Object.keys(toUpdObj).map(function (key) { return "[".concat(key, "] = @").concat(key); }).join(','), "\n WHERE ").concat(idKeys.map(function (key) { return (0, raw_where_utils_1.converWhereQuery)('mssql', key, data[key], key); }).join(' AND '), ";\n\n IF @@ROWCOUNT = 0 INSERT INTO [").concat(_this.table, "]\n (").concat(dataKeys.map(function (a) { return "[".concat(a, "]"); }).join(', '), ")\n VALUES (").concat(dataKeys.map(function (key) { return '@' + key; }).join(', '), ");\n "),
74
98
  params: data
75
99
  }); },
100
+ toSQLite: function () { return ({
101
+ query: "\n INSERT INTO \"".concat(_this.table, "\" \n (").concat(dataKeys.map(function (key) { return "\"".concat(key, "\""); }).join(', '), ") \n VALUES (").concat(dataKeys.map(function () { return '?'; }).join(', '), ") \n ON CONFLICT (").concat(idKeys.map(function (key) { return "\"".concat(key, "\""); }).join(', '), ") \n DO UPDATE SET ").concat(Object.keys(toUpdObj).map(function (key) {
102
+ return "\"".concat(key, "\" = excluded.\"").concat(key, "\"");
103
+ }).join(', '), ";"),
104
+ params: Object.values(data)
105
+ }); },
76
106
  };
77
107
  };
78
108
  return SQLEditDataCommands;
@@ -10,6 +10,7 @@ var SQLSelectCommands = /** @class */ (function () {
10
10
  return {
11
11
  toMySQL: function () { return "SELECT * FROM `".concat(_this.table, "`;"); },
12
12
  toMSSQL: function () { return "SELECT * FROM [".concat(_this.table, "];"); },
13
+ toSQLite: function () { return "SELECT * FROM \"".concat(_this.table, "\";"); },
13
14
  };
14
15
  };
15
16
  return SQLSelectCommands;
@@ -9,8 +9,8 @@ var SQLTablesCommands = /** @class */ (function () {
9
9
  return {
10
10
  toMySQL: function () { return "RENAME TABLE `".concat(old_name, "` TO `").concat(new_name, "`;"); },
11
11
  toMSSQL: function () { return "EXEC sp_rename '".concat(old_name, "', '").concat(new_name, "';"); },
12
+ toSQLite: function () { return "ALTER TABLE \"".concat(old_name, "\" RENAME TO \"").concat(new_name, "\";"); },
12
13
  // PG: ALTER TABLE "old_name" RENAME TO "new_name";
13
- // SQLITE: ALTER TABLE "old_name" RENAME TO "new_name";
14
14
  };
15
15
  };
16
16
  SQLTablesCommands.tableInfo = function (database, table) {
@@ -27,6 +27,12 @@ var SQLTablesCommands = /** @class */ (function () {
27
27
  "AND TABLE_SCHEMA = 'dbo'",
28
28
  "AND TABLE_NAME = '".concat(table, "'"),
29
29
  ].join(' '); },
30
+ toSQLite: function () { return [
31
+ "SELECT * FROM sqlite_master",
32
+ "WHERE type = 'table'",
33
+ "AND name = '".concat(table, "'"),
34
+ "LIMIT 1;"
35
+ ].join(' '); },
30
36
  };
31
37
  };
32
38
  SQLTablesCommands.createTable = function (options) {
@@ -42,6 +48,8 @@ var SQLTablesCommands = /** @class */ (function () {
42
48
  str += "`".concat(columnName, "` ");
43
49
  else if (dbtype === 'mssql')
44
50
  str += "[".concat(columnName, "] ");
51
+ else if (dbtype === 'sqlite')
52
+ str += "\"".concat(columnName, "\" ");
45
53
  else if (dbtype === 'postgres')
46
54
  str += "\"".concat(columnName, "\" ");
47
55
  else
@@ -54,12 +62,14 @@ var SQLTablesCommands = /** @class */ (function () {
54
62
  return {
55
63
  toMySQL: function () { return _createQuery('mysql'); },
56
64
  toMSSQL: function () { return _createQuery('mssql'); },
65
+ toSQLite: function () { return _createQuery('sqlite'); },
57
66
  };
58
67
  };
59
68
  SQLTablesCommands.getTablesSizes = function (database) {
60
69
  return {
61
70
  toMySQL: function () { return "\n SELECT \n TABLE_NAME as 'table_name', \n (DATA_LENGTH / 1024) as 'data_kb', \n (INDEX_LENGTH / 1024) as 'index_kb'\n FROM information_schema.TABLES\n WHERE table_schema = '".concat(database, "'\n ORDER BY (data_kb + index_kb) DESC;\n "); },
62
71
  toMSSQL: function () { return "\n SELECT * FROM (\n SELECT\n t.name AS table_name,\n SUM(ps.in_row_data_page_count + ps.lob_used_page_count\n + ps.row_overflow_used_page_count\n ) * 8 AS data_kb,\n SUM(ps.used_page_count - ps.in_row_data_page_count\n - ps.lob_used_page_count - ps.row_overflow_used_page_count\n ) * 8 AS index_kb\n FROM sys.tables t\n JOIN sys.dm_db_partition_stats ps\n ON t.object_id = ps.object_id\n GROUP BY t.name\n ) t ORDER BY (data_kb + index_kb) DESC;\n "; },
72
+ toSQLite: function () { return "\n SELECT name AS table_name, \n (SUM(pgsize) / 1024.0) AS data_kb \n FROM dbstat WHERE name NOT LIKE 'sqlite_%' \n GROUP BY name ORDER BY data_kb DESC;\n "; },
63
73
  // postgress
64
74
  // SELECT
65
75
  // relname AS table_name,
@@ -8,4 +8,5 @@ export declare function createSQLConnection(options: DatabaseOptions): AbstractS
8
8
  export * from './abstract.connection';
9
9
  export * from './mysql.connection';
10
10
  export * from './mssql.connection';
11
+ export * from './sqlite.connection';
11
12
  export { MySQLConnection as RawMySQLConnection };
@@ -18,6 +18,7 @@ exports.RawMySQLConnection = exports.createSQLConnection = exports.isDatabaseTyp
18
18
  var mysql_connection_1 = require("./mysql.connection");
19
19
  Object.defineProperty(exports, "RawMySQLConnection", { enumerable: true, get: function () { return mysql_connection_1.MySQLConnection; } });
20
20
  var mssql_connection_1 = require("./mssql.connection");
21
+ var sqlite_connection_1 = require("./sqlite.connection");
21
22
  function isDatabaseTypeIs(options, type) {
22
23
  return options.type === type;
23
24
  }
@@ -27,9 +28,12 @@ function createSQLConnection(options) {
27
28
  return new mysql_connection_1.MySQLConnection(options);
28
29
  if (isDatabaseTypeIs(options, 'mssql'))
29
30
  return new mssql_connection_1.MSSQLConnection(options);
31
+ if (isDatabaseTypeIs(options, 'sqlite'))
32
+ return new sqlite_connection_1.SQLiteConnection(options);
30
33
  throw "Connection for database type " + options.type + ' is not implemented :(';
31
34
  }
32
35
  exports.createSQLConnection = createSQLConnection;
33
36
  __exportStar(require("./abstract.connection"), exports);
34
37
  __exportStar(require("./mysql.connection"), exports);
35
38
  __exportStar(require("./mssql.connection"), exports);
39
+ __exportStar(require("./sqlite.connection"), exports);
@@ -0,0 +1,13 @@
1
+ import { DatabaseOptions } from '@klapeks/utils';
2
+ import { AbstractSQLConnection } from './abstract.connection';
3
+ import type { Database as SQLite3Database } from 'sqlite3';
4
+ export declare class SQLiteConnection extends AbstractSQLConnection {
5
+ private _db;
6
+ constructor(options: DatabaseOptions & {
7
+ type: "sqlite";
8
+ });
9
+ initConnection(): Promise<void>;
10
+ getConnection(): Promise<SQLite3Database>;
11
+ destroyConnection(): Promise<void>;
12
+ sendSQL<T = any>(query: string, params?: any): Promise<T[]>;
13
+ }
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
18
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19
+ return new (P || (P = Promise))(function (resolve, reject) {
20
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
23
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
24
+ });
25
+ };
26
+ var __generator = (this && this.__generator) || function (thisArg, body) {
27
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29
+ function verb(n) { return function (v) { return step([n, v]); }; }
30
+ function step(op) {
31
+ if (f) throw new TypeError("Generator is already executing.");
32
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
33
+ 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;
34
+ if (y = 0, t) op = [op[0] & 2, t.value];
35
+ switch (op[0]) {
36
+ case 0: case 1: t = op; break;
37
+ case 4: _.label++; return { value: op[1], done: false };
38
+ case 5: _.label++; y = op[1]; op = [0]; continue;
39
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
40
+ default:
41
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45
+ if (t[2]) _.ops.pop();
46
+ _.trys.pop(); continue;
47
+ }
48
+ op = body.call(thisArg, _);
49
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51
+ }
52
+ };
53
+ Object.defineProperty(exports, "__esModule", { value: true });
54
+ exports.SQLiteConnection = void 0;
55
+ var utils_1 = require("@klapeks/utils");
56
+ var abstract_connection_1 = require("./abstract.connection");
57
+ var quiet_require_1 = require("../../utils/quiet.require");
58
+ var sqlite3 = (0, quiet_require_1.quietRequire)('sqlite3');
59
+ var logger = new utils_1.Logger('SQLite');
60
+ var SQLiteConnection = /** @class */ (function (_super) {
61
+ __extends(SQLiteConnection, _super);
62
+ function SQLiteConnection(options) {
63
+ return _super.call(this, options, 'toSQLite') || this;
64
+ }
65
+ SQLiteConnection.prototype.initConnection = function () {
66
+ return __awaiter(this, void 0, void 0, function () {
67
+ return __generator(this, function (_a) {
68
+ switch (_a.label) {
69
+ case 0: return [4 /*yield*/, this.getConnection()];
70
+ case 1:
71
+ _a.sent();
72
+ return [2 /*return*/];
73
+ }
74
+ });
75
+ });
76
+ };
77
+ SQLiteConnection.prototype.getConnection = function () {
78
+ return __awaiter(this, void 0, void 0, function () {
79
+ return __generator(this, function (_a) {
80
+ if (!sqlite3)
81
+ throw "sqlite3 module is not installed";
82
+ if (this._db)
83
+ return [2 /*return*/, this._db];
84
+ this._db = new sqlite3.Database(this.rawOptions.database);
85
+ this._db.exec("\n PRAGMA journal_mode = WAL;\n PRAGMA busy_timeout = 15000;\n ");
86
+ return [2 /*return*/, this._db];
87
+ });
88
+ });
89
+ };
90
+ SQLiteConnection.prototype.destroyConnection = function () {
91
+ return __awaiter(this, void 0, void 0, function () {
92
+ var _this = this;
93
+ return __generator(this, function (_a) {
94
+ return [2 /*return*/, new Promise(function (resolve, reject) {
95
+ if (!_this._db)
96
+ return resolve();
97
+ try {
98
+ _this._db.close(function (err) {
99
+ logger.log('Database disconnected');
100
+ if (err)
101
+ reject(err);
102
+ else
103
+ resolve();
104
+ });
105
+ }
106
+ catch (err) {
107
+ reject(err);
108
+ }
109
+ finally {
110
+ _this._db = undefined;
111
+ }
112
+ })];
113
+ });
114
+ });
115
+ };
116
+ SQLiteConnection.prototype.sendSQL = function (query, params) {
117
+ return __awaiter(this, void 0, void 0, function () {
118
+ var connection;
119
+ var _this = this;
120
+ return __generator(this, function (_a) {
121
+ switch (_a.label) {
122
+ case 0: return [4 /*yield*/, this.getConnection()];
123
+ case 1:
124
+ connection = _a.sent();
125
+ return [2 /*return*/, new Promise(function (resolve, reject) {
126
+ _this.debugQuery(query, params);
127
+ var upperSQL = query.trim().toUpperCase();
128
+ if (upperSQL.startsWith('BEGIN')
129
+ || upperSQL.startsWith('COMMIT')
130
+ || upperSQL.startsWith('ROLLBACK')) {
131
+ return connection.exec(query, function (err) {
132
+ if (err)
133
+ return reject(err);
134
+ resolve([]);
135
+ });
136
+ }
137
+ if (!params)
138
+ params = [];
139
+ if (upperSQL.startsWith('SELECT')) {
140
+ return connection.all(query, params, function (err1, rows) {
141
+ if (err1)
142
+ return reject(err1);
143
+ resolve((rows || []));
144
+ });
145
+ }
146
+ return connection.run(query, params, function (err1) {
147
+ if (err1)
148
+ return reject(err1);
149
+ resolve(this);
150
+ });
151
+ })];
152
+ }
153
+ });
154
+ });
155
+ };
156
+ return SQLiteConnection;
157
+ }(abstract_connection_1.AbstractSQLConnection));
158
+ exports.SQLiteConnection = SQLiteConnection;
@@ -7,6 +7,8 @@ function sqlQuoteKey(dbType, str) {
7
7
  return "`".concat(str, "`");
8
8
  if (dbType === 'mssql')
9
9
  return "[".concat(str, "]");
10
+ if (dbType === 'sqlite')
11
+ return "\"".concat(str, "\"");
10
12
  return str;
11
13
  }
12
14
  function converWhereQuery(dbType, key, value, keyAlias) {
@@ -24,7 +26,7 @@ function converWhereQuery(dbType, key, value, keyAlias) {
24
26
  if (value === null) {
25
27
  return sqlQuoteKey(dbType, key) + ' IS NULL';
26
28
  }
27
- if (keyAlias === '?' || dbType === 'mysql') {
29
+ if (keyAlias === '?' || dbType === 'mysql' || dbType === 'sqlite') {
28
30
  return sqlQuoteKey(dbType, key) + " = ?";
29
31
  }
30
32
  if (dbType === 'mssql') {
@@ -11,7 +11,11 @@ export declare function createRelation(target: string, type: "one-to-many" | "on
11
11
  };
12
12
  export declare const MULTISQL_COLUMNS_TYPES: {
13
13
  dbtype: "sqlite" | "mysql" | "postgres" | "mssql";
14
+ int32: "int" | "integer";
15
+ string: "character varying" | "nvarchar" | "varchar" | "text";
16
+ boolean: "boolean" | "tinyint" | "integer" | "bit";
14
17
  enum: "simple-enum" | "enum";
18
+ bigint: "bigint" | "integer";
15
19
  datetime: "datetime" | "datetime2" | "timestamp";
16
20
  float32: "float" | "double";
17
21
  float64: "float" | "double";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@klapeks/micro-db-utils",
3
3
  "description": "klapeks utils for db and other storages",
4
- "version": "0.0.16",
4
+ "version": "0.0.18",
5
5
  "type": "commonjs",
6
6
  "author": "Klapeks",
7
7
  "license": "ISC",
@@ -22,15 +22,17 @@
22
22
  "@aws-sdk/client-s3": "^3.842.0",
23
23
  "@aws-sdk/s3-request-presigner": "^3.844.0",
24
24
  "@klapeks/api-creation-tools": "^0.0.7",
25
- "@klapeks/utils": "^0.1.8",
25
+ "@klapeks/utils": "^0.1.9",
26
26
  "@types/mssql": "^12.3.0",
27
27
  "@types/node": "^18.11.18",
28
+ "@types/pg": "^8.23.1",
28
29
  "axios": "^1.7.7",
29
30
  "ioredis": "^5.6.1",
30
31
  "kafkajs": "^2.2.4",
31
32
  "mongoose": "^8.16.1",
32
33
  "mssql": "^11.0.1",
33
34
  "mysql2": "^3.11.3",
35
+ "pg": "^8.23.0",
34
36
  "redis": "^4.7.0",
35
37
  "sqlite3": "^5.1.7",
36
38
  "typeorm": "^0.3.21",