-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
635 lines (578 loc) · 16.5 KB
/
index.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
'use strict'
const R = require('ramda')
const moment = require('moment')
let cache = {}
const mssql = require('mssql')
const dateService = require('./date.service')
let pool
/** Utility functions **/
/**
* Return the Tedious key value given a SQL Server datatype
* E.g. 'nvarchar' => 'NVarChar'
* To get the whole Type for a parameter you need the object stored under this key.
* @param {string} type
* @return {string | undefined}
*/
const findDataType = (type) => Object.keys(sqlService.TYPES).find(k => {
if (type.toUpperCase() === k.toUpperCase()) {
return k
}
})
/**
* Given table and column names returns the cache key for looking up the datatype from the DB server
* It will remove square brackets from the table name if present.
* @param {string} table
* @param {string} column
* @return {string}
*/
const cacheKey = (table, column) => table.replace('[', '').replace(']', '') + '_' + column
/**
* Returns a function that extracts the keys from an object joins them together in a sql fragment
* @type {Function}
*/
const extractColumns = R.compose(
R.join(' , '),
R.keys
)
/**
* Prefix a string with '@'
* @param s
* @return {string}
*/
const paramName = (s) => '@' + s
/**
* Prefix a string with '@' and its index
* @param idx
* @param s
* @return {string}
*/
const paramNameWithIdx = R.curry((idx, s) => '@' + s + idx)
/**
* Return a function that takes the keys from an object joins them together into a list
* of sql parameter identifiers.
* @type {Function}
*/
const createParamIdentifiers = R.compose(
R.join(' , '),
R.map(paramName),
R.keys
)
/**
* Return a function that takes the keys from each object in an array and joins them
* together into a list of sql parameter identifiers with specific IDs.
* @type {Function}
*/
const createMultipleParamIdentifiers = (data) => data.map((d, idx) => R.compose(
R.join(' , '),
R.map(paramNameWithIdx(idx)),
R.keys
)(d))
/**
* Return a string for use in a SQL UPDATE statement
* E.g. 'foo' => 'foo=@foo'
* @param k
*/
const singleUpdate = (k) => R.join('', [k, '=', paramName(k)])
/**
* Return a function that generates a list of UPDATE fragments for an entire object's keys (except the `id` key)
* @type {Function}
*/
const generateSetStatements = R.compose(
R.join(' , '),
R.map(singleUpdate),
R.keys
)
/**
* Returns a bool indicating the supplied object is a Moment object
* @param v
* @return {boolean}
*/
const isMoment = (v) => moment.isMoment(v)
/**
* Given an object will convert all Moment values to Javascript Date
* Useful for converting Data during UPDATES and INSERTS
*/
const convertMomentToJsDate = (m) => {
if (!isMoment(m)) {
return m
}
const iso = dateService.formatIso8601(m)
return new Date(iso)
}
/**
* Convert Date to Moment object
* Useful for converting Data during UPDATES and INSERTS
*/
const convertDateToMoment = (d) => {
if (!(d instanceof Date)) {
return d
}
return moment(d)
}
/**
* Return a list of parameters given a table and an object whose keys are column names
* @param {string} tableName
* @param {object} data - keys should be col. names
* @return {Promise<Array>}
*/
async function generateParams (tableName, data) {
const pairs = R.toPairs(data)
const params = []
for (const p of pairs) {
const [column, value] = p
const cacheData = await sqlService.getCacheEntryForColumn(tableName, column)
if (!cacheData) {
throw new Error(`Column '${column}' not found in table '${tableName}'`)
}
const options = {}
// Construct the options array for params generated used `create()` or `update()`
if (cacheData.dataType === 'Decimal' || cacheData.dataType === 'Numeric') {
options.precision = cacheData.precision
options.scale = cacheData.scale
} else if (cacheData.maxLength) {
options.length = cacheData.maxLength
}
params.push({
name: column,
value,
type: R.prop(findDataType(cacheData.dataType), sqlService.TYPES),
options
})
}
return params
}
/** SQL Service **/
const sqlService = {
// SQL type-mapping adapter. Add new types as required.
TYPES: {
BigInt: mssql.BigInt,
Bit: mssql.Bit,
Char: mssql.Char,
DateTimeOffset: mssql.DateTimeOffset,
Decimal: mssql.Decimal,
Float: mssql.Float,
Int: mssql.Int,
Numeric: mssql.Numeric,
NVarChar: mssql.NVarChar,
Real: mssql.Real,
SmallInt: mssql.SmallInt,
UniqueIdentifier: mssql.UniqueIdentifier
}
}
function validateSqlConfig (config) {
const ex = (propertyName) => {
throw new Error(`${propertyName} is required`)
}
if (!config.Application.Username) {
ex('Application.Username')
}
if (!config.Application.Password) {
ex('Application.Password')
}
if (!config.Server) {
ex('Server')
}
if (!config.Database) {
ex('Server')
}
}
sqlService.initPool = async (sqlConfig) => {
if (!sqlConfig) {
throw new Error('sqlConfig is required')
}
if (pool) {
return
}
validateSqlConfig(sqlConfig)
const config = {
user: sqlConfig.Application.Username,
password: sqlConfig.Application.Password,
server: sqlConfig.Server,
database: sqlConfig.Database,
connectionTimeout: sqlConfig.connectionTimeout || 30000,
requestTimeout: sqlConfig.requestTimeout || 15000,
pool: {
max: sqlConfig.Pooling.MaxCount || 5,
min: sqlConfig.Pooling.MinCount || 0,
idleTimeoutMillis: sqlConfig.Pooling.IdleTimeout || 30000
},
options: {
encrypt: sqlConfig.Encrypt
}
}
pool = new mssql.ConnectionPool(config)
// TODO emit error
pool.on('error', () => {})
return pool.connect()
}
sqlService.drainPool = async () => {
await pool
if (!pool) {
return
}
return pool.close()
}
/**
* Utility service to transform the results before sending to the caller
* @type {Function}
*/
sqlService.transformResult = function (data) {
const recordSet = R.prop('recordset', data) // returns [o1, o2, ...]
if (!recordSet) {
return []
}
return R.map(R.pipe(
R.omit(['version']),
R.map(convertDateToMoment)
), recordSet)
}
function addParamsToRequestSimple (params, request) {
if (params) {
for (let index = 0; index < params.length; index++) {
const param = params[index]
// TODO support other options
request.input(param.name, param.type, param.value)
}
}
}
const retry = require('./retry-async')
const retryConfig = {
attempts: 3,
pauseTimeMs: 5000,
pauseMultiplier: 1.5
}
const connectionLimitReachedErrorCode = 10928
const dbLimitReached = (error) => {
// https://docs.microsoft.com/en-us/azure/sql-database/sql-database-develop-error-messages
return error.number === connectionLimitReachedErrorCode // || error.message.indexOf('request limit') !== -1
}
/**
* Query data from SQL Server via mssql
* @param {string} sql - The SELECT statement to execute
* @param {array} params - Array of parameters for SQL statement
* @return {Promise<*>}
*/
sqlService.query = async (sql, params = []) => {
await pool
const query = async () => {
const request = new mssql.Request(pool)
addParamsToRequestSimple(params, request)
const result = await request.query(sql)
return sqlService.transformResult(result)
}
return retry(query, retryConfig, dbLimitReached)
}
/**
* Add parameters to an SQL request
* @param {{name, value, type}[]} params - array of parameter objects
* @param {{}} request - mssql request
*/
function addParamsToRequest (params, request) {
if (params) {
for (let index = 0; index < params.length; index++) {
let param = params[index]
param.value = convertMomentToJsDate(param.value)
if (!param.type) {
throw new Error('parameter type invalid')
}
const options = {}
if (R.pathEq(['type', 'name'], 'Decimal', param) ||
R.pathEq(['type', 'name'], 'Numeric', param)) {
options.precision = param.precision || 28
options.scale = param.scale || 5
}
const opts = param.options ? param.options : options
if (opts.precision) {
request.input(param.name, param.type(opts.precision, opts.scale), param.value)
} else if (opts.length) {
request.input(param.name, param.type(opts.length), param.value)
} else {
request.input(param.name, param.type, param.value)
}
}
}
}
/**
* Modify data in SQL Server via mssql library.
* @param {string} sql - The INSERT/UPDATE/DELETE statement to execute
* @param {array} params - Array of parameters for SQL statement
* @return {Promise}
*/
sqlService.modify = async (sql, params = []) => {
await pool
const modify = async () => {
const request = new mssql.Request(pool)
addParamsToRequest(params, request)
return request.query(sql)
}
const returnValue = {}
const insertIds = []
let rawResponse
rawResponse = await retry(modify, retryConfig, dbLimitReached)
if (rawResponse && rawResponse.recordset) {
for (let obj of rawResponse.recordset) {
/* TODO remove this strict column name limitation and
extract column value regardless of name */
if (obj && obj.SCOPE_IDENTITY) {
insertIds.push(obj.SCOPE_IDENTITY)
}
}
}
if (insertIds.length === 1) {
returnValue.insertId = R.head(insertIds)
} else if (insertIds.length > 1) {
returnValue.insertIds = insertIds
}
return returnValue
}
/**
* Find a row by numeric ID
* Assumes all table have Int ID datatype
* @param {string} table
* @param {number} id
* @return {Promise<void>}
*/
sqlService.findOneById = async (table, id, schema = '[mtc_admin]') => {
const paramId = {
name: 'id',
type: sqlService.TYPES.Int,
value: id
}
const sql = `
SELECT *
FROM ${schema}.${table}
WHERE id = @id
`
const query = async () => {
return sqlService.query(sql, [paramId])
}
const rows = await retry(query, retryConfig, dbLimitReached)
return R.head(rows)
}
/**
* Return the Tedious datatype object required for a particular table and column
* It's okay if the table name has square brackets around it like '[pupil]'
* @param {string} table
* @param {string} column
* @return {TYPE}
*
*/
sqlService.getCacheEntryForColumn = async function (table, column) {
const key = cacheKey(table, column)
if (R.isEmpty(cache)) {
// This will cache all data-types once on the first sql request
await sqlService.updateDataTypeCache()
}
if (!cache.hasOwnProperty(key)) {
return undefined
}
const cacheData = cache[key]
return cacheData
}
/**
* Provide the INSERT statement for passing to modify and parameters given a key/value object
* @param {string} table
* @param {object} data
* @return {{sql: string, params}}
*/
sqlService.generateInsertStatement = async (table, data, schema = '[mtc_admin]') => {
const params = await generateParams(table, data)
const sql = `
INSERT INTO ${schema}.${table} ( ${extractColumns(data)} ) VALUES ( ${createParamIdentifiers(data)} );
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]`
return {
sql,
params,
outputParams: { SCOPE_IDENTITY: sqlService.TYPES.Int }
}
}
/**
* Provide the INSERT statements for passing to modify and parameters an array
* @param {string} table
* @param {array} data
* @return {{sql: string, params}}
*/
sqlService.generateMultipleInsertStatements = async (table, data, schema = '[mtc_admin]') => {
if (!Array.isArray(data)) throw new Error('Insert data is not an array')
const paramsWithTypes = await generateParams(table, R.head(data))
const headers = extractColumns(R.head(data))
const values = createMultipleParamIdentifiers(data).join('), (')
let params = []
data.forEach((datum, idx) => {
params.push(
R.map((key) => {
const sameParamWithType = paramsWithTypes.find(({ name }) => name === key)
return {
...sameParamWithType,
name: `${key}${idx}`,
value: (sameParamWithType.type.type === 'DATETIMEOFFSETN' ? moment(datum[key]) : datum[key])
}
}, R.keys(datum))
)
})
params = R.flatten(params)
const sql = `
INSERT INTO ${schema}.${table} ( ${headers} ) VALUES ( ${values} );
SELECT SCOPE_IDENTITY()`
return {
sql,
params
}
}
/**
* Utility function for internal sqlService use. Generate the SQL UPDATE statement and list of parameters
* given the table name and the object containing key/values to be updated.
* @param table
* @param data
* @return {Promise<{sql, params: Array}>}
*/
sqlService.generateUpdateStatement = async (table, data, schema = '[mtc_admin]') => {
const params = await generateParams(table, data)
const sql = R.join(' ', [
`UPDATE ${schema}.${table}`,
'SET',
generateSetStatements(R.omit(['id'], data)),
'WHERE id=@id'
])
return {
sql,
params
}
}
/**
* Create a new record
* @param {string} tableName
* @param {object} data
* @return {Promise} - returns the number of rows modified (e.g. 1)
*/
sqlService.create = async (tableName, data) => {
const preparedData = convertMomentToJsDate(data)
const {
sql,
params,
outputParams
} = await sqlService.generateInsertStatement(tableName, preparedData)
const create = async () => {
return sqlService.modify(sql, params, outputParams)
}
return retry(create, retryConfig, dbLimitReached)
}
/**
* Fetch the data-types for each column in the schema. Populates the cache.
* @return {Promise<void>}
*/
sqlService.updateDataTypeCache = async function () {
const sql =
`SELECT
TABLE_NAME,
COLUMN_NAME,
DATA_TYPE,
NUMERIC_PRECISION,
NUMERIC_SCALE,
CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = @schema
`
const paramSchema = {
name: 'schema',
value: 'mtc_admin',
type: sqlService.TYPES.NVarChar
}
// delete any existing cache
cache = {}
const rows = await sqlService.query(sql, [paramSchema])
rows.forEach((row) => {
const key = cacheKey(row.TABLE_NAME, row.COLUMN_NAME)
// add the datatype to the cache
cache[key] = {
dataType: findDataType(row.DATA_TYPE),
precision: row.NUMERIC_PRECISION,
scale: row.NUMERIC_SCALE,
maxLength: row.CHARACTER_MAXIMUM_LENGTH && row.CHARACTER_MAXIMUM_LENGTH > 0 ? row.CHARACTER_MAXIMUM_LENGTH : undefined
}
})
}
/**
* Call SQL Update on the table given an object whose keys are the columns to be updated and whose keys are the new
* values. You *MUST* pass the `id` field for the WHERE clause.
* Returns { rowsModified: n } the number of rows modified.
* @param tableName
* @param data
* @return {Promise<*>}
*/
sqlService.update = async function (tableName, data) {
if (!data.id) {
throw new Error('`id` is required')
}
// Convert any moment objects to JS Date objects as that's required by Tedious
const preparedData = convertMomentToJsDate(data)
const {
sql,
params
} = await sqlService.generateUpdateStatement(tableName, preparedData)
const update = async () => {
return sqlService.modify(sql, params)
}
return retry(update, retryConfig, dbLimitReached)
}
/**
* Helper function useful for constructing parameterised WHERE clauses
* @param {Array} ary
* @param {sqlService.TYPE} type
* @return {Promise<{params: Array, paramIdentifiers: Array}>}
*/
sqlService.buildParameterList = (ary, type) => {
const params = []
const paramIdentifiers = []
for (let i = 0; i < ary.length; i++) {
params.push({
name: `p${i}`,
type,
value: ary[i]
})
paramIdentifiers.push(`@p${i}`)
}
return {
params,
paramIdentifiers
}
}
sqlService.modifyWithTransaction = async (sqlStatements, params) => {
const wrappedSQL = `
BEGIN TRY
BEGIN TRANSACTION
${sqlStatements}
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF (@@TRANCOUNT > 0)
BEGIN
ROLLBACK TRANSACTION
PRINT 'Error detected, all changes reversed'
END
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT @ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Use RAISERROR inside the CATCH block to return
-- error information about the original error that
-- caused execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH
`
const modify = async () => sqlService.modify(wrappedSQL, params)
return retry(modify, retryConfig, dbLimitReached)
}
/**
* Initialise the sql service and set up the connection pool
* @param config
*/
sqlService.initialise = async (config) => {
await sqlService.initPool(config)
}
module.exports = sqlService