db-crud-api 0.3.23 → 0.3.25

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.
@@ -0,0 +1,404 @@
1
+ 'use strict';
2
+
3
+ import sql from 'mysql2/promise';
4
+ import log from './log.js'
5
+
6
+ // Regex
7
+ const _match_LIMIT_n = /\bLIMIT\b +\d+/ig
8
+ const _match_TOP_n = /\bTOP\b +\d+/ig
9
+ const _match_TOP = /\bTOP\b/ig
10
+
11
+ const pools = {};
12
+
13
+ // Common
14
+ function stringifyValue(fieldName, value, tSchema) {
15
+
16
+ // null or undefined
17
+ if (value == undefined)
18
+ return 'null';
19
+
20
+ // detect field type
21
+ let _fieldType = undefined;
22
+ if (tSchema.table.fields && tSchema.table.fields[fieldName] && tSchema.table.fields[fieldName].type) {
23
+ _fieldType = tSchema.table.fields[fieldName].type;
24
+ }
25
+
26
+ // if datetime
27
+ if (_fieldType == 'datetime') {
28
+ // my-sql not accepts 'Z' at end of ISO string
29
+ if (value instanceof Date)
30
+ return `\'${value.toISOString().slice(0, -1)}\'`;
31
+ if (typeof value == 'string') {
32
+ const valueDate = new Date(Date.parse(value));
33
+ return `\'${valueDate.toISOString().slice(0, -1)}\'`;
34
+ }
35
+ return value;
36
+ }
37
+
38
+ // if boolean
39
+ if (_fieldType == 'boolean' && typeof value == 'boolean')
40
+ return `\'${value}\'`;
41
+
42
+ // if string or uuid
43
+ if (_fieldType == 'string' || _fieldType == 'uuid') {
44
+ if (value.trimStart().charAt(0) !== '\'' && value.trimStart().charAt(0) !== '\"') {
45
+ return `\'${value}\'`;
46
+ }
47
+ }
48
+
49
+ // field not in schema
50
+ if (_fieldType == undefined) {
51
+ if (value instanceof Date)
52
+ return `\'${value.toISOString().slice(0, -1)}\'`;
53
+ if (typeof value == 'boolean')
54
+ return `\'${value}\'`;
55
+ if (typeof value == 'string' && value.trimStart().charAt(0) !== '\'' && value.trimStart().charAt(0) !== '\"')
56
+ return `\'${value}\'`;
57
+ }
58
+
59
+ return value;
60
+ }
61
+
62
+
63
+
64
+ // Create config object for pool
65
+ export function prepareConnection(tSchema) {
66
+ return {
67
+ id: `${tSchema.server.realName}-${tSchema.database.realName}-${tSchema.server.user}`,
68
+ host: ((tSchema.server.instance && tSchema.server.instance != 'DEFAULT') ? (tSchema.server.realName + '\\' + tSchema.server.instance) : tSchema.server.realName) ?? 'localhost',
69
+ port: tSchema.server.port,
70
+ user: tSchema.server.user,
71
+ password: tSchema.server.password,
72
+ database: tSchema.database.realName,
73
+ ssl: {
74
+ rejectUnauthorized: false
75
+ },
76
+ multipleStatements: true,
77
+ connectionLimit: tSchema.server.connectionLimit
78
+ };
79
+ };
80
+
81
+ // Close connection
82
+ export async function closeConnection(connection) {
83
+ let pool = pools[connection.id];
84
+ if (pool) {
85
+ pool.releaseConnection();
86
+ connection.end();
87
+ pools[connection.id] = undefined; // remove pool from pools
88
+ }
89
+ }
90
+
91
+ // Close all connections
92
+ export async function closeAllConnections() {
93
+ for (let poolId in pools) {
94
+ if (!pools.hasOwnProperty(poolId)) continue;
95
+ let pool = pools[poolId];
96
+ if (pool) {
97
+ pool.end();
98
+ pool = undefined; // remove pool from pools
99
+ }
100
+ }
101
+ }
102
+
103
+ // Test connection
104
+ export async function testConnection(connection) {
105
+ try {
106
+ const _connection = await sql.createConnection(connection);
107
+ await _connection.end();
108
+ return true;
109
+ }
110
+ catch (error)
111
+ {
112
+ throw (error);
113
+ }
114
+ }
115
+
116
+ // Query
117
+ export async function query(connection, dbOpes) {
118
+
119
+ // Prepare pool
120
+ let pool = pools[connection.id]; // Try to get an existing pool
121
+ if (!pool) {
122
+ pool = new sql.createPool(connection); // Create new pool
123
+ pools[connection.id] = pool; // add new pool to pools
124
+ }
125
+
126
+ // Prepare sql statement
127
+ let sqlString = '';
128
+ let appLog = true;
129
+ // if exists, input params will be added to request
130
+ if (Array.isArray(dbOpes)) {
131
+ dbOpes.forEach((dbOpe, index) => {
132
+ sqlString += ToSql(dbOpe, pool);
133
+ if (dbOpe?.hasOwnProperty('appLog') && dbOpe.appLog === false) appLog = false;
134
+ });
135
+ }
136
+ else {
137
+ sqlString += ToSql(dbOpes, pool);
138
+ if (dbOpes?.hasOwnProperty('appLog') && dbOpes.appLog === false) appLog = false;
139
+ }
140
+
141
+ sqlString = normalizeSpecialName(sqlString);
142
+
143
+ // Log
144
+ if (appLog) {
145
+ log(JSON.stringify(dbOpes), 60);
146
+ log(sqlString, 50);
147
+ }
148
+
149
+ // Run query
150
+ let sqlresult = undefined;
151
+ let sqlconn = undefined;
152
+ try {
153
+ sqlconn = await pool.getConnection();
154
+ sqlresult = await sqlconn.query(sqlString);
155
+ }
156
+ catch (err) { throw (err); } // using original error
157
+ finally { if (sqlconn) sqlconn.release(); }
158
+
159
+ // Log
160
+ if (appLog) {
161
+ log(`Query result: ${(sqlresult && sqlresult.length > 0) ? sqlresult[0].length : 0} rows.`, 50);
162
+ }
163
+
164
+ // normalize return object
165
+ if (sqlresult == undefined) return;
166
+ if (sqlresult.length === 0) return;
167
+ if (sqlresult[0].length === 0) return;
168
+
169
+ return sqlresult[0];
170
+ }
171
+
172
+ // Normalize special name to replace square brackets with backticks, considering quoted strings
173
+ function normalizeSpecialName(sql) {
174
+ let result = "";
175
+ let inSingleQuote = false;
176
+ let inDoubleQuote = false;
177
+
178
+ for (let i = 0; i < sql.length; i++) {
179
+ const char = sql[i];
180
+
181
+ // Gestione delle virgolette singole '
182
+ if (char === "'" && !inDoubleQuote) {
183
+ inSingleQuote = !inSingleQuote;
184
+ }
185
+ // Gestione delle virgolette doppie "
186
+ else if (char === '"' && !inSingleQuote) {
187
+ inDoubleQuote = !inDoubleQuote;
188
+ }
189
+
190
+ // Se non siamo all'interno di una stringa, sostituiamo le quadre
191
+ if (!inSingleQuote && !inDoubleQuote) {
192
+ if (char === '[' || char === ']') {
193
+ result += '`';
194
+ continue;
195
+ }
196
+ }
197
+
198
+ result += char;
199
+ }
200
+
201
+ return result;
202
+ }
203
+
204
+ // Compose fully qualified table name
205
+ function fullyQualifiedTableName(tSchema) {
206
+ return (tSchema.database.realName + '.' + tSchema.table.realName);
207
+ }
208
+
209
+ function containLIMIT(s) {
210
+ const _return = s?.match(_match_LIMIT_n);
211
+ if (_return) return _return[0];
212
+ else return undefined;
213
+ };
214
+
215
+ function containTOP(s) {
216
+ const _return = s?.match(_match_TOP_n);
217
+ if (_return) return _return[0];
218
+ else return undefined;
219
+ };
220
+
221
+ function replaceTOPToLIMIT(s) {
222
+ const _replace = containTOP(s);
223
+ if (_replace) { return s.replace(_match_TOP_n, _replace.replace(_match_TOP, 'LIMIT')); }
224
+ else return s;
225
+ }
226
+
227
+ // Parse oprations object to sql string
228
+ function ToSql(dbOpe, sqlRequest) {
229
+ if (dbOpe.get) return getToSql(dbOpe, sqlRequest);
230
+ if (dbOpe.patch) return patchToSql(dbOpe, sqlRequest);
231
+ if (dbOpe.put) return putToSql(dbOpe, sqlRequest);
232
+ if (dbOpe.delete) return deleteToSql(dbOpe, sqlRequest);
233
+ if (dbOpe.execute) return executeToSql(dbOpe, sqlRequest);
234
+ if (dbOpe.begin) return beginToSql(dbOpe, sqlRequest);
235
+ if (dbOpe.commit) return commitToSql(dbOpe, sqlRequest);
236
+ if (dbOpe.passthrough) return passthroughToSql(dbOpe, sqlRequest);
237
+ }
238
+
239
+ // Parse operation object to sql string without any trasformation.
240
+ function passthroughToSql(dbOpe, sqlRequest) {
241
+
242
+ let result = "";
243
+
244
+ if (dbOpe.passthrough.command) {
245
+ result += dbOpe.passthrough.command;
246
+ }
247
+ else { throw new Error('command is missing.'); }
248
+
249
+ if (dbOpe.passthrough.params) addParams(dbOpe.passthrough.params, sqlRequest);
250
+
251
+ return result;
252
+ }
253
+
254
+ // Parse get operation object to sql string
255
+ function getToSql(dbOpe, sqlRequest) {
256
+ let _first = true;
257
+
258
+ let result = 'select'
259
+
260
+ // omit 'limit' or 'top'
261
+ if (dbOpe.get.options && dbOpe.get.options.length > 0) {
262
+ if (Array.isArray(dbOpe.get.options)) {
263
+ for (const s of dbOpe.get.options) { if (!containLIMIT(s) && !containTOP(s)) result += ' ' + s; }
264
+ }
265
+ else if (!containLIMIT(dbOpe.get.options) && !containTOP(dbOpe.get.options)) result += ' ' + dbOpe.get.options;
266
+ }
267
+
268
+ if (dbOpe.get.fields && dbOpe.get.fields.length > 0) {
269
+ if (Array.isArray(dbOpe.get.fields)) result += ' ' + dbOpe.get.fields.join(',')
270
+ else result += ' ' + dbOpe.get.fields;
271
+ }
272
+ else { throw new Error('fields is missing.'); }
273
+
274
+ result += ' from ' + fullyQualifiedTableName(dbOpe.get.schema);
275
+
276
+ if (dbOpe.get.filters && dbOpe.get.filters.length > 0) {
277
+ if (Array.isArray(dbOpe.get.filters)) result += ' where ' + dbOpe.get.filters.join(' ');
278
+ else result += ' where ' + dbOpe.get.filters;
279
+ }
280
+
281
+ if (dbOpe.get.groups && dbOpe.get.groups.length > 0) {
282
+ if (Array.isArray(dbOpe.get.groups)) result += ' group by ' + dbOpe.get.groups.join(', ');
283
+ else result += ' group by ' + dbOpe.get.groups;
284
+ }
285
+
286
+ if (dbOpe.get.groupsFilters && dbOpe.get.groupsFilters.length > 0) {
287
+ if (Array.isArray(dbOpe.get.groupsFilters)) result += ' having ' + dbOpe.get.groupsFilters.join(' ');
288
+ else result += ' having ' + dbOpe.get.groupsFilters;
289
+ }
290
+
291
+ if (dbOpe.get.orderBy && dbOpe.get.orderBy.length > 0) {
292
+ if (Array.isArray(dbOpe.get.orderBy)) result += ' order by ' + dbOpe.get.orderBy.join(', ');
293
+ else result += ' order by ' + dbOpe.get.orderBy;
294
+ }
295
+
296
+ // search if 'limit' or 'top'
297
+ if (dbOpe.get.options && dbOpe.get.options.length > 0) {
298
+ if (Array.isArray(dbOpe.get.options)) {
299
+ for (const s of dbOpe.get.options) { if (containLIMIT(s) || containTOP(s)) result += ' ' + replaceTOPToLIMIT(s); }
300
+ }
301
+ else if (containLIMIT(dbOpe.get.options) || containTOP(dbOpe.get.options)) result += ' ' + replaceTOPToLIMIT(dbOpe.get.options);
302
+ }
303
+
304
+ if (dbOpe.get.params) addParams(dbOpe.get.params, sqlRequest);
305
+
306
+ result += ';'
307
+
308
+ return result;
309
+ }
310
+
311
+ // Parse patch operation object to sql string
312
+ function patchToSql(dbOpe, sqlRequest) {
313
+ let result = 'update ' + fullyQualifiedTableName(dbOpe.patch.schema);
314
+
315
+ if (dbOpe.patch.sets) { result += ' set ' + Object.entries(dbOpe.patch.sets).map(e => { return e[0] + '=' + stringifyValue(e[0], e[1], dbOpe.patch.schema) }).join(', '); }
316
+ else { throw new Error('sets is missing.'); }
317
+
318
+ if (dbOpe.patch.filters && dbOpe.patch.filters.length > 0) {
319
+ if (Array.isArray(dbOpe.patch.filters)) result += ' where ' + dbOpe.patch.filters.join(' ');
320
+ else result += ' where ' + dbOpe.patch.filters;
321
+ }
322
+
323
+ if (dbOpe.patch.params) addParams(dbOpe.patch.params, sqlRequest);
324
+
325
+ result += ';'
326
+
327
+ return result;
328
+ }
329
+
330
+ // Parse put (add) operation object to sql string
331
+ function putToSql(dbOpe, sqlRequest) {
332
+ let result = 'insert into ' + fullyQualifiedTableName(dbOpe.put.schema);
333
+
334
+ if ((dbOpe.put.sets) && (Object.keys(dbOpe.put.sets).length > 0)) {
335
+ let result_f = ' ('; let result_v = ' values (';
336
+ let _first = true;
337
+ for (const [key, value] of Object.entries(dbOpe.put.sets)) {
338
+ if (!_first) { result_f += ', '; result_v += ', '; } else { _first = false }
339
+ if (key || value) { result_f += key; result_v += stringifyValue(key, value, dbOpe.put.schema); }
340
+ }
341
+ result_f += ')'; result_v += ')';
342
+ result += result_f + result_v;
343
+ }
344
+ else { throw new Error('sets is missing.'); }
345
+
346
+ if (dbOpe.put.params) addParams(dbOpe.put.params, sqlRequest);
347
+
348
+ result += ';'
349
+
350
+ return result;
351
+ }
352
+
353
+ // Parse delete operation object to sql string
354
+ function deleteToSql(dbOpe, sqlRequest) {
355
+ let result = 'delete from ' + fullyQualifiedTableName(dbOpe.delete.schema);
356
+
357
+ if (dbOpe.delete.filters && dbOpe.delete.filters.length > 0) {
358
+ if (Array.isArray(dbOpe.delete.filters)) result += ' where ' + dbOpe.delete.filters.join(' ');
359
+ else result += ' where ' + dbOpe.delete.filters;
360
+ }
361
+
362
+ if (dbOpe.delete.params) addParams(dbOpe.delete.params, sqlRequest);
363
+
364
+ result += ';'
365
+
366
+ return result;
367
+ }
368
+
369
+ // Parse execute operation object to sql string
370
+ function executeToSql(dbOpe, sqlRequest) {
371
+ let result = "CALL ";
372
+
373
+ if (dbOpe.execute.schema.procedure) {
374
+ result += dbOpe.execute.schema.procedure.command;
375
+ if (dbOpe.execute.arguments) { result += ('(' + dbOpe.execute.arguments) + ')'; }
376
+ }
377
+ else { throw new Error('missing procedure/function name.'); }
378
+
379
+ if (dbOpe.execute.params) addParams(dbOpe.execute.params, sqlRequest);
380
+
381
+ result += ';'
382
+
383
+ return result;
384
+ }
385
+
386
+ // Parse begin operation object to sql string
387
+ function beginToSql(dbOpe, sqlRequest) {
388
+ return "START TRANSACTION; ";
389
+ }
390
+
391
+ // Parse commit operation object to sql string
392
+ function commitToSql(dbOpe, sqlRequest) {
393
+ return " COMMIT;";
394
+ }
395
+
396
+ // Add input parameters to pool.request
397
+ function addParams(params, sqlRequest) {
398
+ if (params) {
399
+ for (const [key, value] of Object.entries(params)) {
400
+ sqlRequest.input(key, value)
401
+ }
402
+ }
403
+ return;
404
+ }
package/lib/schema.js CHANGED
@@ -1,14 +1,14 @@
1
- export default {
2
- servers: {
3
- },
4
- config: {
5
- log: {
6
- level: 0,
7
- callback: undefined,
8
- maxAsyncInstance: 50
9
- },
10
- session: {
11
- tablePath: 'sessions'
12
- }
13
- }
1
+ export default {
2
+ servers: {
3
+ },
4
+ config: {
5
+ log: {
6
+ level: 0,
7
+ callback: undefined,
8
+ maxAsyncInstance: 50
9
+ },
10
+ session: {
11
+ tablePath: 'sessions'
12
+ }
13
+ }
14
14
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "db-crud-api",
3
- "version": "0.3.23",
3
+ "version": "0.3.25",
4
4
  "type": "module",
5
5
  "description": "CRUD api for database tables",
6
6
  "main": "index.js",