-
Notifications
You must be signed in to change notification settings - Fork 1
/
sql-engine.js
677 lines (652 loc) · 26.7 KB
/
sql-engine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
import StashKu, {
GetRequest,
PostRequest,
PutRequest,
PatchRequest,
DeleteRequest,
OptionsRequest,
BaseEngine,
Filter,
Response,
RESTError,
ModelGenerator,
ModelUtility
} from '@appku/stashku';
import rhino from 'rhino';
import { SQLServerTypes, PostgresTypes } from './sql-types.js';
import QuerySegment from './query-segment.js';
import SQLTranslator from './sql-translator.js';
import fs from 'fs';
import path from 'path';
const __dirname = (
process.platform === 'win32' ?
path.dirname(decodeURI(new URL(import.meta.url).pathname)).substring(1) :
path.dirname(decodeURI(new URL(import.meta.url).pathname))
);
const SUPPORTED_DRIVERS = ['sql-server'];
const OPTIONS_QUERY = fs.readFileSync(__dirname + '/templates/options.sql', 'utf8');
const RESOURCES_QUERY = fs.readFileSync(__dirname + '/templates/resources.sql', 'utf8');
/**
* @typedef SQLStorageAuthenticationConfiguration
* @property {String} type
* @property {String} user
* @property {String} password
* @property {String} domain
*/
/**
* @typedef SQLStoragePoolConfiguration
* @property {Number} min
* @property {Number} max
*/
/**
* @typedef SQLStorageLogConfiguration
* @property {Boolean} queries
* @property {Boolean} sensitive
*/
/**
* @typedef SQLStorageBatchConfiguration
* @property {Boolean} [enabled=false]
* @property {Number} [size=100]
*/
/**
* @typedef SQLBulkColumnOptions
* @property {Boolean} [nullable=false] - Indicates whether the column accepts NULL values.
* @property {Number} length - For VarChar, NVarChar, VarBinary. Use length as Infinity for VarChar(max), NVarChar(max) and VarBinary(max).
* @property {Number} precision - For Numeric, Decimal.
* @property {Number} scale - For Numeric, Decimal, Time, DateTime2, DateTimeOffset.
*/
/**
* @typedef SQLStorageConfigurationModel
* @property {Boolean} [views=false]
*/
/**
* @typedef SQLStorageConfiguration
* @property {String} driver
* @property {String} host
* @property {Number} port
* @property {String} database
* @property {SQLStorageAuthenticationConfiguration} auth
* @property {SQLStorageBatchConfiguration} batch
* @property {SQLStoragePoolConfiguration} pool
* @property {SQLStorageLogConfiguration} log
* @property {Boolean} encrypt
* @property {SQLStorageConfigurationModel} [model]
*/
/**
* Helper function to process input values to a boolean.
* @param {String} input - Input value to check for `true` or `false`.
* @returns {Boolean}
*/
const toBool = (input) => !!(input === 1 || input === true || (typeof input === 'string' && input.match(/^[ty1]/i)));
/**
* This StashKu engine provides an interface to SQL databases and support for all StashKu RESTful actions and
* operations.
*/
class SQLEngine extends BaseEngine {
/**
* Creates a new `SQLEngine` instance.
*/
constructor() {
super('sql');
/**
* @type {SQLStorageConfiguration}
*/
this.config = super.config;
/**
* The driver instance for the configured database.
*/
this.driver = null;
}
/**
* @inheritdoc
*/
async destroy() {
if (this.driver) {
return new Promise((res, rej) => {
this.driver.destroy(() => {
res();
});
});
}
}
/**
* @inheritdoc
* @param {*} config - The configuration object for the storage engine.
*/
configure(config, log) {
super.configure(config, log);
this.config = Object.assign({
driver: process.env.STASHKU_SQL_DRIVER || 'sql-server',
host: process.env.STASHKU_SQL_HOST || 'localhost',
database: process.env.STASHKU_SQL_DATABASE || 'master',
port: process.env.STASHKU_SQL_PORT || 1433,
encrypt: toBool(process.env.STASHKU_SQL_ENCRYPT),
trust: toBool(process.env.STASHKU_SQL_TRUST),
auth: {}
}, config);
this.config.batch = Object.assign({
enabled: toBool(process.env.STASHKU_SQL_BATCH_ENABLED),
size: process.env.STASHKU_SQL_BATCH_SIZE || 100
}, config ? config.batch : null);
this.config.log = Object.assign({
queries: toBool(process.env.STASHKU_SQL_LOG_QUERIES),
sensitive: toBool(process.env.STASHKU_SQL_LOG_SENSITIVE)
}, config ? config.log : null);
this.driver = null; //clear out the driver instance to allow re-initialization
//initialize the database driver
let driverConfig = {
server: this.config.host,
authentication: {
type: 'default',
options: {}
},
options: {
database: this.config.database,
port: parseInt(this.config.port),
encrypt: !!this.config.encrypt,
trustServerCertificate: !!this.config.trust,
useColumnNames: true,
enableArithAbort: true
}
};
if (this.config) {
//we only want these properties set if they are present
if (process.env.STASHKU_SQL_AUTH_TYPE || this.config.auth.type) {
this.config.auth.type =
driverConfig.authentication.type =
this.config.auth.type || process.env.STASHKU_SQL_AUTH_TYPE;
}
if (process.env.STASHKU_SQL_AUTH_USER || this.config.auth.user) {
this.config.auth.user =
driverConfig.authentication.options.userName =
this.config.auth.user || process.env.STASHKU_SQL_AUTH_USER;
}
if (process.env.STASHKU_SQL_AUTH_PASSWORD || this.config.auth.password) {
this.config.auth.password =
driverConfig.authentication.options.password =
this.config.auth.password || process.env.STASHKU_SQL_AUTH_PASSWORD;
}
if (process.env.STASHKU_SQL_AUTH_DOMAIN || this.config.auth.domain) {
this.config.auth.domain =
driverConfig.authentication.options.domain =
this.config.auth.domain || process.env.STASHKU_SQL_AUTH_DOMAIN;
}
//merge other options
if (this.config.options) {
driverConfig.options = Object.assign(driverConfig.options, this.config.options);
}
}
this.driver = new rhino(driverConfig);
}
/**
* @inheritdoc
* @returns {Promise.<Array.<String>>}
*/
async resources() {
let names = await this.raw(RESOURCES_QUERY);
return names.map(v => `${SQLTranslator.identifier(v.schema)}.${SQLTranslator.identifier(v.name)}`);
}
/**
* Makes a raw SQL query to the configured database.
* @param {String} query - The SQL query to run on the database.
* @param {Object|Map} [params] - The URI parameters to include in the request.
* @returns {Promise.<Array>}
*/
async raw(query, params) {
if (query) {
if (this.log && this.config.log && this.config.log.queries) {
this.log.debug('Executing SQL query.', query, this.config.log.sensitive ? params : '{ Params Hidden }');
}
if (this.config.driver === 'sql-server') {
let result = await this.driver.query(query, params);
if (Array.isArray(result)) {
return result.map(v => v.rows);
}
return result.rows;
}
}
throw new RESTError(500, 'The "query" parameter argument is missing or not defined.');
}
/**
* Bulk-loads rows into the database using specified column definitions.
* @param {String} tableName - The name of the table to bulk-load into.
* @param {Map.<String, SQLBulkColumnOptions>} columns - An map of column definitions with the key as the column name.
* @param {Array} rows - An array of rows to bulk-load.
* @param {{checkConstraints:Boolean, fireTriggers:Boolean, keepNulls:Boolean, tableLock:Boolean}} [options] - Optional bulk-load options for the underlying driver.
* @returns {Promise.<Number>}
*/
async bulk(tableName, columns, rows, options) {
if (!tableName) {
throw new RESTError(500, 'The "tableName" argument is required.');
}
if (columns && columns.size && rows) {
if (this.log && this.config.log && this.config.log.queries) {
this.log.debug('Executing SQL bulk-load.', columns);
}
if (this.config.driver === 'sql-server') {
let bk = await this.driver.bulk(tableName, Object.assign({
checkConstraints: false,
fireTriggers: false,
keepNulls: false,
tableLock: false
}, options));
for (let [k, v] of columns) {
let opts = Object.assign({
nullable: true
}, v);
await bk.column(k, rhino.Types[v.type], opts);
}
for (let i = 0, ilen = rows.length; i < ilen; i++) {
await bk.add(rows[i]);
}
let rowCount = await bk.execute();
return rowCount;
}
}
throw new RESTError(500, 'Invalid bulk operation. No columns or rows were specified.');
}
/**
* @inheritdoc
* @param {GetRequest} request - The GET request to send to the storage engine.
* @returns {Promise.<Response>} Returns the data objects from storage matching request criteria.
*/
async get(request) {
//validate
await super.get(request);
let meta = request.metadata;
let headers = meta.headers ?? new Map();
if (meta.bulk || headers.get('bulk')) {
throw new RESTError(400, 'A "get" request does not support bulk operations (only "post" requests do).');
} else if (meta.batch) {
throw new RESTError(400, 'A "get" request does not support batch operations (only "put" and "post" requests do).');
}
//build the query
let qs = new QuerySegment();
try {
let totalSegment = null;
let baseSegment = new QuerySegment('SELECT');
if (meta.distinct) {
baseSegment.line(1, 'DISTINCT');
}
if (meta.properties && meta.properties.length && meta.properties[0] !== '*') {
baseSegment.line(1, SQLTranslator.columns(...meta.properties));
} else {
baseSegment.line(1, '*');
}
baseSegment.line(1, `FROM ${SQLTranslator.identifier(meta.from)}`);
if (meta.where && Filter.isEmpty(meta.where) === false) {
baseSegment.line(1, 'WHERE ', SQLTranslator.where(meta.where));
}
//if paging is enabled we need to build a primary totalling query to get the non-paged total.
if (meta.skip || meta.take) {
totalSegment = new QuerySegment('WITH base AS (');
totalSegment.line(1, baseSegment);
totalSegment.line(0, ')');
totalSegment.line(0, 'SELECT COUNT(*) AS __Query_Total FROM base;\n\n');
totalSegment.params.clear(); //remove parameters (they already exist on the base)
}
//continue building the base query segment
if (meta.sorts && meta.sorts.length) {
baseSegment.line(1, 'ORDER BY ', SQLTranslator.sorts(...meta.sorts));
} else if (meta.skip || meta.take) {
baseSegment.line(1, 'ORDER BY 1');
}
if (meta.skip) {
baseSegment.line(1, `OFFSET ${SQLTranslator.integer(meta.skip)} ROWS`);
}
if (meta.take) {
if (!meta.skip) {
baseSegment.line(1, 'OFFSET 0 ROWS'); //always include offset
}
baseSegment.line(1, `FETCH NEXT ${SQLTranslator.integer(meta.take)} ROWS ONLY`);
}
//handle count-only requests
if (meta.count) {
baseSegment.prepend('SELECT COUNT(*) AS __Query_Returns FROM (\n');
baseSegment.line(0, ') as query');
}
//combine queries
qs.concat(totalSegment, baseSegment);
} catch (err) {
throw new RESTError(500, `Failed to generate query.\nError: ${err}`);
}
//make the query
let results = await this.raw(qs.segment, qs.params);
//respond
if (meta.count) {
if (meta.skip || meta.take) {
return new Response(null, results[0][0].__Query_Total, 0, results[1][0].__Query_Returns);
} else {
return new Response(null, results[0].__Query_Returns, 0, results[0].__Query_Returns);
}
} else {
if (meta.skip || meta.take) {
return new Response(results[1], results[0][0].__Query_Total, 0, results[1].length);
} else {
return new Response(results, results.length, 0, results.length);
}
}
}
/**
* @inheritdoc
* @param {PostRequest} request - The POST request to send to the storage engine.
* @returns {Promise.<Response>} Returns the data objects from storage matching request criteria.
*/
async post(request) {
//validate
await super.post(request);
let meta = request.metadata;
let headers = meta.headers ?? new Map();
let res = new Response();
let batch = !!(meta.batch || this.config.batch.enabled || headers.get('batch'));
let batchSize = (this.config?.batch?.size || headers.get('batch')?.size || 100);
//build the query
if (meta.bulk || headers.get('bulk')) {
let columns = new Map(Object.entries(meta.bulk ?? headers.get('bulk')));
//validate columns
for (let [c, v] of columns) {
if (!v.type) {
throw new RESTError(400, `The "request" bulk metadata is missing the required 'type' for column "${c}".`);
} else if (typeof SQLServerTypes[v.type] === 'undefined') {
throw new RESTError(400, `The "request" bulk metadata contains an invalid or unsupported column type "${v.type}".`);
}
}
if (batch) {
for (let x = 0; x < meta.objects.length; x += batchSize) {
let rows = meta.objects.slice(x, x + batchSize);
if (rows.length) {
res.total += await this.bulk(meta.to, columns, rows);
}
}
} else {
res.total = await this.bulk(meta.to, columns, meta.objects);
}
res.affected = res.total;
} else {
let chunk = '';
let counter = 0;
if (batch) {
chunk = `ALTER TABLE ${SQLTranslator.identifier(meta.to)} NOCHECK CONSTRAINT ALL;`;
}
for (let o of meta.objects) {
let qs = new QuerySegment('INSERT INTO ');
try {
qs.concat(SQLTranslator.identifier(meta.to), '(');
qs.line(2, SQLTranslator.columns(...Object.keys(o)));
qs.line(1, ') ', meta.count ? '' : 'OUTPUT INSERTED.*');
qs.line(1, 'VALUES (');
qs.line(2, SQLTranslator.values(o));
qs.line(1, ')');
} catch (err) {
throw new RESTError(500, `Failed to generate query.\nError: ${err}`);
}
if (batch) { //batching enabled, build up a batch query.
chunk += SQLTranslator.raw(qs) + ';\n';
counter++;
if (counter >= batchSize) {
//batch exec
let results = await this.raw(chunk);
res.data.push(...results.flat());
res.total += results.length;
//reset chunk
chunk = '';
counter = 0;
}
} else {
//non-batch exec
let results = await this.raw(qs.segment, qs.params);
if (!meta.count) {
res.data.push(results[0]);
}
res.total++;
}
}
//handle batch left-overs
if (batch && counter > 0) {
let results = await this.raw(chunk);
res.data.push(...results.flat());
res.total += results.length;
}
res.affected = res.total;
res.returned = res.total;
}
//respond
return res;
}
/**
* @inheritdoc
* @param {PutRequest} request - The PUT request to send to the storage engine.
* @returns {Promise.<Response>} Returns the data objects from storage matching request criteria.
*/
async put(request) {
//validate
await super.put(request);
if (request.metadata.bulk) {
throw new RESTError(400, 'A "put" request does not support bulk operations (only "post" requests do).');
}
let meta = request.metadata;
let headers = meta.headers ?? new Map();
let res = new Response();
//build the query
let batch = !!(meta.batch || this.config.batch.enabled || headers.get('batch'));
let batchSize = (this.config?.batch?.size || headers.get('batch')?.size || 100);
let chunk = '';
let counter = 0;
for (let o of meta.objects) {
let qs = new QuerySegment('UPDATE ');
let f = new Filter();
for (let k of meta.pk) {
f.and(k, Filter.OP.EQUALS, o[k]);
}
try {
qs.concat(SQLTranslator.identifier(meta.to), ' SET ');
qs.line(1, SQLTranslator.columnValues(o, null, meta.pk));
if (!meta.count) {
qs.line(1, 'OUTPUT INSERTED.*');
}
qs.line(1, 'WHERE ', SQLTranslator.where(f));
} catch (err) {
throw new RESTError(500, `Failed to generate query.\nError: ${err}`);
}
if (batch) { //batching enabled, build up a batch query.
chunk += SQLTranslator.raw(qs) + ';\n';
counter++;
if (counter >= batchSize) {
//batch exec
let results = await this.raw(chunk);
res.data.push(...results.flat());
res.total += results.length;
//reset chunk
chunk = '';
counter = 0;
}
} else {
//non-batch exec
let results = await this.raw(qs.segment, qs.params);
res.data.push(results[0]);
res.total++;
}
}
//handle batch left-overs
if (batch && counter > 0) {
let results = await this.raw(chunk);
res.data.push(...results.flat());
res.total += results.length;
}
//respond
res.affected = res.total;
res.returned = res.total;
return res;
}
/**
* @inheritdoc
* @param {PatchRequest} request - The PUT request to send to the storage engine.
* @returns {Promise.<Response>} Returns the data objects from storage matching request criteria.
*/
async patch(request) {
//validate
await super.patch(request);
if (request.metadata.bulk) {
throw new RESTError(400, 'A "patch" request does not support bulk operations (only "post" requests do).');
} else if (request.metadata.batch) {
throw new RESTError(400, 'A "patch" request does not support batch operations (only "put" and "post" requests do).');
}
let meta = request.metadata;
let res = new Response();
//build the query
let emptyFilter = Filter.isEmpty(meta.where);
if (meta.all === true || emptyFilter === false) { //must have either a filter, or the "all" flag set.
let qs = new QuerySegment('UPDATE ');
try {
qs.concat(SQLTranslator.identifier(meta.to), ' SET ');
qs.line(1, SQLTranslator.columnValues(meta.template));
if (!meta.count) {
qs.line(1, 'OUTPUT INSERTED.*');
}
if (meta.where && Filter.isEmpty(meta.where) === false) {
qs.line(1, 'WHERE ', SQLTranslator.where(meta.where));
}
} catch (err) {
throw new RESTError(500, `Failed to generate query.\nError: ${err}`);
}
let results = await this.raw(qs.segment, qs.params);
res.data.push(...results);
res.total = results.length;
}
//respond
res.affected = res.total;
res.returned = res.total;
return res;
}
/**
* @inheritdoc
* @param {DeleteRequest} request - The PUT request to send to the storage engine.
* @returns {Promise.<Response>} Returns the data objects from storage matching request criteria.
*/
async delete(request) {
//validate
await super.delete(request);
if (request.metadata.bulk) {
throw new RESTError(400, 'A "delete" request does not support bulk operations (only "post" requests do).');
} else if (request.metadata.batch) {
throw new RESTError(400, 'A "delete" request does not support batch operations (only "put" and "post" requests do).');
}
let meta = request.metadata;
let res = new Response();
//build the query
let emptyFilter = Filter.isEmpty(meta.where);
if (meta.all === true || emptyFilter === false) { //must have either a filter, or the "all" flag set.
let qs = new QuerySegment('DELETE FROM ');
try {
qs.concat(SQLTranslator.identifier(meta.from));
if (!meta.count) {
qs.line(1, 'OUTPUT DELETED.*');
}
if (meta.where && Filter.isEmpty(meta.where) === false) {
qs.line(1, 'WHERE ', SQLTranslator.where(meta.where));
}
} catch (err) {
throw new RESTError(500, `Failed to generate query.\nError: ${err}`);
}
let results = await this.raw(qs.segment, qs.params);
res.data.push(...results);
res.total = results.length;
}
//respond
res.affected = res.total;
res.returned = res.total;
return res;
}
/**
* @inheritdoc
* @override
* @throws 404 Error when the requested resource is has not been stored in memory.
* @param {OptionsRequest} request - The OPTIONS request to send to the storage engine.
* @returns {Promise.<Response>} Returns a response with a single data object- the dynamically created model configuration.
*/
async options(request) {
//validate
await super.options(request);
//get information
let meta = request.metadata;
let data = [];
let resources = [];
if (meta.from === '*') {
resources.push(...(await this.resources()));
} else {
resources.push(meta.from);
}
let includeViews = (process.env.STASHKU_SQL_MODEL_VIEWS === 'true');
let includeTables = this.config?.model?.tables ?? true;
if (this.config?.model?.views === true) {
includeViews = true;
}
if (typeof this.config?.model?.tables === 'undefined' && process.env.STASHKU_SQL_MODEL_TABLES === 'false') {
includeTables = false;
}
for (let resource of resources) {
let properties = new Map();
let columns = await this.raw(OPTIONS_QUERY, {
resource: resource,
views: includeViews,
tables: includeTables
});
if (columns && columns.length) {
for (let col of columns) {
if (properties.has(col.property) === false) {
let def = {
target: col.property,
type: SQLTranslator.toJSTypeName(col.dataType)
};
if (col.keyed) {
def.pk = true;
}
if (col.numberPrecision) {
def.precision = col.numberPrecision;
}
if (col.numberRadix) {
def.radix = col.numberRadix;
}
if (col.charLength) {
def.charLength = col.charLength;
}
if (col.keyed || col.hasDefault) {
//omit if null to let SQL handle the default
def.omit = {
post: null,
put: null
};
}
if (!def.pk && !col.nullable && !col.hasDefault) {
switch (def.type) {
case 'Number': def.default = 0; break;
case 'String': def.default = ''; break;
case 'Boolean': def.default = false; break;
case 'Array': def.default = []; break;
case 'Date': def.default = new Date(); break;
case 'Map': def.default = new Map(); break;
case 'Set': def.default = new Set(); break;
case 'Buffer': def.default = Buffer.alloc(0); break;
case 'ArrayBuffer': def.default = new ArrayBuffer(0); break;
}
}
properties.set(ModelGenerator.formatPropName(col.property), def);
}
}
} else if (meta.from !== '*') {
throw new RESTError(404, `The requested resource "${resource}" was not found.`);
} else {
continue;
}
//generate model type and return
let mt = ModelGenerator.generateModelType(resource, properties, { resource: resource });
data.push(mt);
}
return new Response(data, data.length, 0, data.length);
}
}
export {
SQLEngine as default,
SQLServerTypes,
PostgresTypes
};