-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdb.js
More file actions
1597 lines (1520 loc) · 63.9 KB
/
db.js
File metadata and controls
1597 lines (1520 loc) · 63.9 KB
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import mysql from "mysql2";
import {isObject, isObjectEmpty, isString, isStringEmpty} from "@aicore/libcommonutils";
import crypto from "crypto";
import {isNumber} from "@aicore/libcommonutils/src/utils/common.js";
import {getColumNameForJsonField, isVariableNameLike, isNestedVariableNameLike} from "./sharedUtils.js";
import Query from './query.js';
import {
JSON_COLUMN, MAX_NUMBER_OF_DOCS_ALLOWED, PRIMARY_COLUMN, DATA_TYPES,
MAXIMUM_LENGTH_OF_MYSQL_TABLE_NAME_AND_COLUMN_NAME, MAXIMUM_LENGTH_OF_MYSQL_DATABASE_NAME
} from './constants.js';
// @INCLUDE_IN_API_DOCS
let CONNECTION = null;
let LOGGER = console; // Default fallback for backward compatibility
/* Defining a constant variable called SIZE_OF_PRIMARY_KEY and assigning it the value of 32. */
const SIZE_OF_PRIMARY_KEY = 32;
/**
* Gets the limit string for sql query pr the default limit 1000 string
* @param {Object} options
* @param {number} options.pageOffset specify which row to start retrieving documents from. Eg: to get 10 documents from
* the 100'th document, you should specify `pageOffset = 100` and `pageLimit = 10`
* @param {number} options.pageLimit specify number of documents to retrieve. Eg: to get 10 documents from
* the 100'th document, you should specify `pageOffset = 100` and `pageLimit = 10`
* @private
*/
function _getLimitString(options) {
if(!options.pageLimit && !options.pageOffset){
// default limit
return `LIMIT ${MAX_NUMBER_OF_DOCS_ALLOWED}`;
}
if(!isNumber(options.pageOffset) || !isNumber(options.pageLimit)){
throw new Error(`Expected required options options.pageOffset and options.pageLimit as numbers but got `
+ typeof options.pageOffset + " and " + typeof options.pageLimit);
}
if(options.pageLimit > 1000){
throw new Error("options.pageLimit Cannot exceed 1000");
}
return `LIMIT ${options.pageOffset}, ${options.pageLimit}`;
}
/**
* It creates a database with the name provided as an argument
* @param {string} databaseName - The name of the database to create.
* @returns {Promise<boolean>}- A promise which helps to know if createDataBase is successful
*/
export function createDataBase(databaseName) {
return new Promise(function (resolve, reject) {
if (!CONNECTION) {
reject('Please call init before createDataBase');
return;
}
if (!_isValidDatBaseName(databaseName)) {
reject('Please provide valid data base name');
return;
}
try {
const createDataBaseSql = `CREATE DATABASE ${databaseName}`;
CONNECTION.execute(createDataBaseSql,
function (err, _results, _fields) {
//TODO: emit success or failure metrics based on return value
if (err) {
LOGGER.error({err, databaseName, operation: 'createDataBase'}, 'Error creating database');
reject(err);
return;
}
resolve(true);
});
} catch (e) {
const errorMessage = `exception occurred while creating database ${e.stack}`;
reject(errorMessage);
//Todo: Emit metrics
}
});
}
/**
* It deletes a database with the given name
* @param {string} databaseName - The name of the database to be created.
* @returns {Promise<boolean>} A promise which helps to know if database delete is successful
*/
export function deleteDataBase(databaseName) {
return new Promise(function (resolve, reject) {
if (!CONNECTION) {
reject('Please call init before deleteDataBase');
return;
}
if (!_isValidDatBaseName(databaseName)) {
reject('Please provide valid data base name');
return;
}
try {
const createDataBaseSql = `DROP DATABASE ${databaseName}`;
CONNECTION.execute(createDataBaseSql,
function (err, _results, _fields) {
//TODO: emit success or failure metrics based on return value
if (err) {
LOGGER.error({err, databaseName, operation: 'deleteDataBase'}, 'Error deleting database');
reject(err);
return;
}
resolve(true);
});
} catch (e) {
const errorMessage = `execution occurred while deleting database ${e.stack}`;
reject(errorMessage);
//Todo: Emit metrics
}
});
}
function _isValidDatBaseName(databaseName) {
return (isString(databaseName) && databaseName.length <=
MAXIMUM_LENGTH_OF_MYSQL_DATABASE_NAME && isVariableNameLike(databaseName));
}
/** This function helps to initialize MySql Client
* This function should be called before calling any other functions in this library
*
* Best practice is to `import @aicore/libcommonutils` and call `getMySqlConfigs()` api to read values from of configs
* from environment variables.
* @example <caption> Sample config </caption>
*
* const config = {
* "host": "localhost",
* "port": "3306",
* "user" : "root",
* "password": "1234"
* };
*
* @example <caption> Sample initialization code </caption>
*
* // set following environment variables to access database securely
* // set MY_SQL_SERVER for mysql server
* // set MY_SQL_SERVER_PORT to set server port
* // set MY_SQL_USER to specify database user
* // set MY_SQL_PASSWORD to set mysql password
*
* import {getMySqlConfigs} from "@aicore/libcommonutils";
*
* const configs = getMySqlConfigs();
* init(configs)
*
*
* @param {Object} config - config to configure MySQL
* @param {string} config.host - mysql database hostname
* @param {string} config.port - port number of mysql db
* @param {string} config.user - username of database
* @param {string} config.password - password of database username
* @param {Number} config.connectionLimit - Maximum MySql connection that can be open to the server default value is 10
* @param {Object} logger - Logger instance for structured logging
* @returns {boolean} true if connection is successful false otherwise
*
*
**/
export function init(config, logger) {
// Store logger (fallback to console if not provided)
LOGGER = logger || console;
if (!isObject(config)) {
throw new Error('Please provide valid config');
}
if (!isString(config.host)) {
throw new Error('Please provide valid hostname');
}
if (!isString(config.port)) {
throw new Error('Please provide valid port');
}
if (!isString(config.user)) {
throw new Error('Please provide valid user');
}
if (!isString(config.password)) {
throw new Error('Please provide valid password');
}
if (CONNECTION) {
LOGGER.warn({connection: 'already_active'}, 'Connection already active');
throw new Error('One connection is active please close it before reinitializing it');
}
try {
config.waitForConnections = true;
config.connectionLimit = !config.connectionLimit ? 10 : config.connectionLimit;
config.queueLimit = 0;
CONNECTION = mysql.createPool(config);
return true;
} catch (e) {
LOGGER.error({err: e}, 'Failed to initialize MySQL connection');
return false;
}
}
/** This function helps to close the database connection
* @return {void}
*
*/
export function close() {
if (!isObject(CONNECTION)) {
return;
}
CONNECTION.end();
CONNECTION = null;
}
/**
* It checks if the nameSpace is a valid table name
* @param {string} nameSpace - The name of the table.
* @returns {boolean} A boolean value.
* @private
*/
function _isValidTableName(nameSpace) {
if (!nameSpace || !isString(nameSpace)) {
return false;
}
const split = nameSpace.split('.');
if (!split || split.length !== 2) {
return false;
}
const tableName = split[1];
return (isString(tableName) && tableName.length <=
MAXIMUM_LENGTH_OF_MYSQL_TABLE_NAME_AND_COLUMN_NAME && isVariableNameLike(tableName));
}
/**
* Returns true if the given key is a string of length greater than zero and less than or equal to the maximum size of a
* primary key.
* @param {string} key - The primary key of the item to be retrieved.
* @returns {boolean} A boolean value.
* @private
*/
function _isValidPrimaryKey(key) {
return isString(key) && key.length > 0 && key.length <= SIZE_OF_PRIMARY_KEY;
}
/** It creates a table in the database with the name provided as the parameter
*
* we have simplified our database schema, for us, our database has only two columns
* 1. `primary key` column, which is a varchar(255)
* 2. `JSON` column, which stores values corresponding to the primary key as `JSON`
* using this approach will simplify our database design by delegating the handling of the semantics of
* data to the application.To speed up any query, we have provided an option to add a secondary index
* for JSON fields using `createIndexForJsonField` api.
*
* @example <caption> How to use this function? </caption>
*
* import {getMySqlConfigs} from "@aicore/libcommonutils";
*
* const configs = getMySqlConfigs();
* init(configs)
* const tableName = 'customer';
* try {
* await createTable(tableName);
* } catch(e){
* console.error(JSON.stringify(e));
* }
*
*
* @param {string} tableName name of table to create
* @return {Promise} returns a `Promise` await on `Promise` to get status of `createTable`
* `on success` await will return `true`. `on failure` await will throw an `exception`.
*
*/
export function createTable(tableName) {
return new Promise(function (resolve, reject) {
if (!CONNECTION) {
reject('Please call init before createTable');
return;
}
if (!_isValidTableName(tableName)) {
reject('please provide valid table name in database.tableName format');
return;
//Todo: Emit metrics
}
try {
const createTableSql = `CREATE TABLE ${tableName}
(${PRIMARY_COLUMN} VARCHAR(${SIZE_OF_PRIMARY_KEY}) NOT NULL PRIMARY KEY,
${JSON_COLUMN} JSON NOT NULL)`;
CONNECTION.execute(createTableSql,
function (err, _results, _fields) {
//TODO: emit success or failure metrics based on return value
if (err) {
LOGGER.error({err, tableName, operation: 'createTable'}, 'Error creating table');
reject(err);
return;
}
resolve(true);
});
} catch (e) {
const errorMessage = `execution occurred while creating table ${e.stack}`;
reject(errorMessage);
//Todo: Emit metrics
}
});
}
/**
* It takes a table name and a document and then inserts the document into the database.
* @example <caption> Sample code </caption>
*
* try {
* const primaryKey = 'bob';
* const tableName = 'customers;
* const document = {
* 'lastName': 'Alice',
* 'Age': 100,
* 'active': true
* };
* await put(tableName, document);
* } catch (e) {
* console.error(JSON.stringify(e));
* }
*
* @param {string} tableName - The name of the table in which you want to store the data.
* @param {Object} document - The JSON string that you want to store in the database.
* @returns {Promise} A promise on resolving the promise will give documentID throws an exception
* otherwise. DocumentId is an alphanumeric string of length 128
*/
export function put(tableName, document) {
return new Promise(function (resolve, reject) {
if (!CONNECTION) {
reject('Please call init before put');
return;
}
if (!_isValidTableName(tableName)) {
reject('please provide valid table name in database.tableName format');
return;
//Todo: Emit metrics
}
if (!isObject(document)) {
reject('Please provide valid document');
return;
//Todo: Emit metrics
}
const updateQuery = `INSERT INTO ${tableName} (${PRIMARY_COLUMN}, ${JSON_COLUMN}) values(?,?)`;
try {
const documentID = createDocumentId();
CONNECTION.execute(updateQuery, [documentID, document],
function (err, _results, _fields) {
//TODO: emit success or failure metrics based on return value
if (err) {
LOGGER.error({err, tableName, operation: 'put'}, 'Error putting document');
reject(err);
return;
}
resolve(documentID);
});
} catch (e) {
const errorMessage = `Exception occurred while writing to database ${e.stack}`;
reject(errorMessage);
//TODO: Emit Metrics
}
});
}
/**
* It generates a random string of 16 hexadecimal characters
* When converting hexadecimal to string. The generated string will contain 32 characters
* @returns {string} A random string of hexadecimal characters.
* @private
*/
function createDocumentId() {
return crypto.randomBytes(16).toString('hex');
}
/**
* It deletes a document from the database based on the document id. Conditional deletes are also supported
* with the optional condition parameter.
* @example <caption> Sample code </caption>
*
* const tableName = 'customers';
* const documentID = '123456';
* try {
* await deleteKey(tableName, documentID);
* } catch(e) {
* console.error(JSON.stringify(e));
* }
*
* @example <caption> Sample code with conditional option</caption>
*
* const tableName = 'customers';
* const documentID = '123456';
* try {
* // Eg. delete the document only if the last modified is equals 21
* await deleteKey(tableName, documentID, "$.lastModified=21");
* } catch(e) {
* console.error(JSON.stringify(e));
* }
*
* @param {string} tableName - The name of the table in which the key is to be deleted.
* @param {string} documentID - document id to be deleted
* @param {string} [condition] - Optional coco query condition of the form "$.cost<35" that must be satisfied
* for delete to happen. See query API for more details on how to write coco query strings.
* @returns {Promise}A promise `resolve` promise to get status of delete. promise will resolve to true
* for success and throws an exception for failure.
*/
export function deleteKey(tableName, documentID, condition) {
return new Promise(function (resolve, reject) {
if (!CONNECTION) {
reject('Please call init before deleteKey');
return;
}
if (!_isValidTableName(tableName)) {
reject('please provide valid table name');
return;
//Todo: Emit metrics
}
if (!_isValidPrimaryKey(documentID)) {
reject('Please provide valid documentID');
return;
//Todo: Emit metrics
}
let deleteQuery = `DELETE FROM ${tableName} WHERE ${PRIMARY_COLUMN}= ?;`;
if(condition){
const sqlCondition = Query.transformCocoToSQLQuery(condition, []);
deleteQuery = `DELETE FROM ${tableName} WHERE ${PRIMARY_COLUMN}= ? AND (${sqlCondition});`;
}
try {
CONNECTION.execute(deleteQuery, [documentID],
function (err, _results, _fields) {
//TODO: emit success or failure metrics based on return value
if (err) {
LOGGER.error({err, tableName, documentID, operation: 'deleteKey'}, 'Error deleting key');
reject(err);
return;
}
resolve(true);
});
} catch (e) {
const errorMessage = `Exception occurred while deleting key ${documentID} from database ${e.stack}`;
reject(errorMessage);
//TODO: Emit Metrics
}
});
}
/**
* Deletes a document from the database based the given query condition and returns the number of documents deleted.
* @example <caption> Sample code </caption>
*
* const tableName = 'dbName:customers';
* try {
* // delete all documents with field 'location.city' set to paris
* let deletedDocumentCount = await deleteDocuments(tableName, "$.location.city = 'paris'", ['location.city']);
* } catch(e) {
* console.error(e);
* }
*
* @param {string} tableName - The name of the table in which the key is to be deleted.
* @param {string} queryString - The cocDB query string.
* @param {Array[string]} useIndexForFields - List of indexed fields in the document.
* @returns {Promise} A promise `resolve` with the number of deleted documents or throws an exception for failure.
*/
export function deleteDocuments(tableName, queryString, useIndexForFields = []) {
return new Promise(function (resolve, reject) {
if (!CONNECTION) {
reject('Please call init before deleteDocuments');
return;
}
if (!_isValidTableName(tableName)) {
reject('please provide valid table name');
return;
//Todo: Emit metrics
}
if (!isString(queryString) || isStringEmpty(queryString)) {
reject(`please provide valid queryString`);
return;
}
let queryParseDone = false;
try {
let sqlQuery = Query.transformCocoToSQLQuery(queryString, useIndexForFields);
queryParseDone = true;
const deleteQuery = `DELETE FROM ${tableName} WHERE ${sqlQuery};`;
CONNECTION.execute(deleteQuery,
function (err, results, _fields) {
//TODO: emit success or failure metrics based on return value
if (err) {
LOGGER.error({err, tableName, operation: 'deleteDocuments'}, 'Error deleting documents');
reject(err);
return;
}
resolve(results.affectedRows);
});
} catch (e) {
if (!queryParseDone) {
reject(e.message); // return helpful error messages from query parser
return;
}
reject("Exception occurred while deleting");
//TODO: Emit Metrics
}
});
}
/**
* It takes in a table name and documentId, and returns a promise that resolves to the document
* @example <caption> sample code </caption>
* const tableName = 'customers';
* const documentID = '12345';
* try {
* const results = await get(tableName, documentID);
* console.log(JSON.stringify(result));
* } catch(e){
* console.error(JSON.stringify(e));
* }
*
* @param {string} tableName - The name of the table in which the data is stored.
* @param {string} documentID - The primary key of the row you want to get.
* @returns {Promise} A promise on resolve promise to get the value stored for documentID
*/
export function get(tableName, documentID) {
return new Promise(function (resolve, reject) {
if (!CONNECTION) {
reject('Please call init before get');
return;
}
if (!_isValidTableName(tableName)) {
reject('please provide valid table name');
return;
//Todo: Emit metrics
}
if (!_isValidPrimaryKey(documentID)) {
reject('Please provide valid documentID');
return;
//Todo: Emit metrics
}
try {
const getQuery = `SELECT ${PRIMARY_COLUMN},${JSON_COLUMN} FROM ${tableName} WHERE ${PRIMARY_COLUMN} = ?`;
CONNECTION.execute(getQuery, [documentID],
function (err, results, _fields) {
//TODO: emit success or failure metrics based on return value
if (err) {
reject(err);
return;
}
if (results && results.length > 0) {
results[0][JSON_COLUMN].documentId = results[0][PRIMARY_COLUMN];
resolve(results[0][JSON_COLUMN]);
return;
}
reject('unable to find document for given documentId');
});
} catch (e) {
const errorMessage = `Exception occurred while getting data ${e.stack}`;
reject(errorMessage);
//TODO: Emit Metrics
}
});
}
/**
* It takes a JSON object and returns a SQL query and an array of values to be used in a prepared statement
* @param {Object} subQueryObject - This is the object that you want to query.
* @param {string} [parentKey] - This is the parent key of the current object.
* @returns {Object} An object with two properties: getQuery and valArray.
* @private
*/
function _queryScanBuilder(subQueryObject, parentKey = "") {
const valArray = [];
let getQuery = '';
let numberOfEntries = Object.keys(subQueryObject).length;
for (const [key, value] of Object.entries(subQueryObject)) {
if (isObject(value)) {
let subResults = _queryScanBuilder(value, parentKey + "." + key);
if (subResults) {
getQuery += subResults.getQuery;
subResults.valArray.forEach(result => {
valArray.push(result);
});
numberOfEntries = numberOfEntries - 1;
continue;
}
}
if (!isVariableNameLike(key)) {
throw new Error(`Invalid filed name ${key}`);
}
if (numberOfEntries > 1) {
getQuery = getQuery + `${JSON_COLUMN}->"$${parentKey}.${key}" = ? and `;
} else {
getQuery = getQuery + `${JSON_COLUMN}->"$${parentKey}.${key}" = ? `;
}
valArray.push(value);
numberOfEntries = numberOfEntries - 1;
}
return {
'getQuery': getQuery,
'valArray': valArray
};
}
/**
* It takes a table name and a query object and returns a query string and an array of values to be used in a prepared
* statement
* @param {string} tableName - The name of the table to query.
* @param {Object} queryObject - The query object that you want to run.
* @param {Object} options Optional parameter to add pagination.
* @param {number} options.pageOffset specify which row to start retrieving documents from. Eg: to get 10 documents from
* the 100'th document, you should specify `pageOffset = 100` and `pageLimit = 10`
* @param {number} options.pageLimit specify number of documents to retrieve. Eg: to get 10 documents from
* the 100'th document, you should specify `pageOffset = 100` and `pageLimit = 10`
* @returns {Object} An object with two properties: getQuery and valArray.
* @private
*/
function _prepareQueryForScan(tableName, queryObject, options) {
if (isObjectEmpty(queryObject)) {
return {
'getQuery': `SELECT ${PRIMARY_COLUMN},${JSON_COLUMN} FROM ${tableName} ${_getLimitString(options)}`,
'valArray': []
};
}
let getQuery = `SELECT ${PRIMARY_COLUMN},${JSON_COLUMN} FROM ${tableName} WHERE `;
const subQuery = _queryScanBuilder(queryObject);
return {
'getQuery': getQuery + subQuery.getQuery + ` ${_getLimitString(options)}`,
'valArray': subQuery.valArray
};
}
/**
* It takes a table name and a query object, and returns a promise that resolves to the
* array of matched documents.
* `NB: this api will not detect boolean fields while scanning`
* This query is doing database scan. using this query frequently can degrade database performance. if this query
* is more frequent consider creating index and use `getFromIndex` API
* NB: This query will return only 1000 entries.
* @example <caption> sample code </caption>
* const tableName = 'customers';
* const queryObject = {
* 'lastName': 'Alice',
* 'Age': 100
* };
* try {
* const scanResults = await getFromNonIndex(tableName, queryObject);
* console.log(JSON.stringify(scanResults));
* } catch (e){
* console.error(JSON.stringify(e));
* }
*
* @param {string} tableName - The name of the table you want to query.
* @param {Object} queryObject - This is the object that you want to query.
* @param {Object} options Optional parameter to add pagination.
* @param {number} options.pageOffset specify which row to start retrieving documents from. Eg: to get 10 documents from
* the 100'th document, you should specify `pageOffset = 100` and `pageLimit = 10`
* @param {number} options.pageLimit specify number of documents to retrieve. Eg: to get 10 documents from
* the 100'th document, you should specify `pageOffset = 100` and `pageLimit = 10`
* @returns {Promise} - A promise; on promise resolution returns array of matched documents. if there are
* no match returns empty array
*/
export function getFromNonIndex(tableName, queryObject = {}, options = {}) {
return new Promise(function (resolve, reject) {
if (!CONNECTION) {
reject('Please call init before getFromNonIndex');
return;
}
if (!isObject(queryObject)) {
reject(`please provide valid queryObject`);
return;
}
if (!_isValidTableName(tableName)) {
reject('please provide valid table name');
return;
//Todo: Emit metrics
}
let queryParseDone = false;
try {
const queryParams = _prepareQueryForScan(tableName, queryObject, options);
queryParseDone = true;
_queryIndex(queryParams, resolve, reject);
} catch (e) {
if (!queryParseDone) {
reject(e.message); // return helpful error messages from query parser
return;
}
const errorMessage = `Exception occurred while getting data`;
reject(errorMessage);
//TODO: Emit Metrics
}
});
}
/**
* It deletes a table from the database
* @example <caption> Sample code </caption>
* const tableName = 'customer';
* try{
* await deleteTable(tableName);
* } catch(e){
* console.error(JSON.stringify(e));
* }
*
* @param {string} tableName - The name of the table to be deleted.
* @returns {Promise} - A promise that will resolve to true if the table is deleted, or reject with an error
* if the table is not deleted.
*/
export function deleteTable(tableName) {
return new Promise(function (resolve, reject) {
if (!CONNECTION) {
reject('Please call init before getFromNonIndex');
return;
}
if (!_isValidTableName(tableName)) {
reject('please provide valid table name');
return;
//Todo: Emit metrics
}
try {
const deleteTableQuery = `DROP TABLE IF EXISTS ${tableName} CASCADE`;
CONNECTION.execute(deleteTableQuery,
function (err, _results, _fields) {
//TODO: emit success or failure metrics based on return value
if (err) {
reject(err);
return;
}
resolve(true);
});
} catch (e) {
const errorMessage = `Exception occurred while getting data`;
reject(errorMessage);
//TODO: Emit Metrics
}
});
}
/**
* _buildCreateJsonColumQuery(tableName, nameOfJsonColumn, jsonField, dataTypeOfNewColumn, isNotNull, isUnique)
*
* The function takes the following parameters:
*
* * tableName - the name of the table to add the column to
* * nameOfJsonColumn - the name of the new column
* * jsonField - the name of the field in the JSON column to extract
* * dataTypeOfNewColumn - the data type of the new column
* * isNotNull - a boolean value indicating whether the new column should be nullable
* * isUnique - a boolean value indicating whether the new column should be unique
*
* @param {string} tableName - The name of the table you want to add the column to.
* @param {string} nameOfJsonColumn - The name of the new column that will be created.
* @param {string} jsonField - The field in the JSON object that you want to extract.
* @param {string} dataTypeOfNewColumn - This is the data type of the new column.
* @param {boolean} isNotNull - If the new column should be NOT NULL
* @param {boolean} isUnique - If true, the new column will be a unique key.
* @returns {string} A string that is a query to add a column to a table.
* @private
*
*/
function _buildCreateJsonColumQuery(tableName, nameOfJsonColumn, jsonField,
dataTypeOfNewColumn, isNotNull, isUnique) {
return `ALTER TABLE ${tableName} ADD COLUMN ${nameOfJsonColumn} ${dataTypeOfNewColumn} GENERATED ALWAYS` +
` AS (${JSON_COLUMN}->>"$.${jsonField}") ${isNotNull ? " NOT NULL" : ""} ${isUnique ? " UNIQUE KEY" : ""};`;
}
/**
* It takes a table name, a json field name, and a boolean value indicating whether the index should be unique or not,
* and returns a string containing the SQL query to create the index
* @param {string} tableName - The name of the table to create the index on.
* @param {string} jsonField - The name of the JSON field that you want to index.
* @param {boolean} isUnique - If true, the index will be unique.
* @returns {string} A string that is a query to create an index on a table.
* @private
*/
function _buildCreateIndexQuery(tableName, jsonField, isUnique) {
if (isUnique) {
return `CREATE UNIQUE INDEX idx_${jsonField} ON ${tableName}(${jsonField});`;
}
return `CREATE INDEX idx_${jsonField} ON ${tableName}(${jsonField});`;
}
/**
* It creates an index on the JSON field in the table
* @param{function} resolve - A function that is called when the promise is resolved.
* @param {function} reject - A function that will be called if the promise is rejected.
* @param {string} tableName - The name of the table to create the index on
* @param {string} jsonField - The JSON field that you want to create an index on.
* @param {boolean} isUnique - true if the index is unique, false otherwise
* @returns {void}
* @private
*
* NB `private function exporting this for testing`
*
*/
export function _createIndex(resolve, reject, tableName, jsonField, isUnique) {
try {
const indexQuery = _buildCreateIndexQuery(tableName, jsonField, isUnique);
CONNECTION.execute(indexQuery,
function (err, _results, _fields) {
//TODO: emit success or failure metrics based on return value
if (err) {
reject(err);
return;
}
resolve(true);
});
} catch (e) {
const errorMessage = `Exception occurred while creating index for JSON field`;
reject(errorMessage);
//TODO: Emit Metrics
}
}
/**
* It creates a new column in the table for the JSON field and then creates an index on that column.
* `NB: this will not work with boolean fields`
* @example <caption> Sample code </caption>
* const tableName = 'customers';
* let jsonfield = 'lastName';
* // supported data types can be found on https://dev.mysql.com/doc/refman/8.0/en/data-types.html
* let dataTypeOfNewColumn = 'VARCHAR(50)';
* let isUnique = false;
* try{
* await createIndexForJsonField(tableName jsonfield, dataTypeOfNewColumn, isUnique);
* jsonfield = 'Age';
* dataTypeOfNewColumn = 'INT';
* isUnique = false;
*
* await createIndexForJsonField(tableName, nameOfJsonColumn, jsonfield, dataTypeOfNewColumn, isUnique);
* } catch (e){
* console.error(JSON.stringify(e));
* }
* @param {string} tableName - The name of the table in which you want to create the index.
* @param {string} jsonField - The name of the field in the JSON object that you want to index. The filed name
* should be a valid variable name of the form "x" or "x.y.z".
* @param {string} dataTypeOfNewColumn - This is the data type of the new column that will be created.
* visit https://dev.mysql.com/doc/refman/8.0/en/data-types.html to know all supported data types
* @param {boolean} isUnique - If true, the json filed has to be unique for creating index.
* @param {boolean} isNotNull - If true, the column will be created with NOT NULL constraint.
* @returns {Promise} A promise
*/
export function createIndexForJsonField(tableName, jsonField, dataTypeOfNewColumn, isUnique = false,
isNotNull = false) {
return new Promise(function (resolve, reject) {
if (!CONNECTION) {
reject('Please call init before createIndexForJsonField');
return;
}
if (!_isValidTableName(tableName)) {
reject('please provide valid table name');
return;
//Todo: Emit metrics
}
if (!isNestedVariableNameLike(jsonField)) {
reject('please provide valid name for json field');
return;
//Todo: Emit metrics
}
if (!isString(dataTypeOfNewColumn)) {
reject('please provide valid data type for json field');
return;
}
const sqlJsonColumn = getColumNameForJsonField(jsonField);
try {
const createColumnQuery = _buildCreateJsonColumQuery(tableName,
sqlJsonColumn,
jsonField,
dataTypeOfNewColumn, isNotNull, isUnique);
CONNECTION.execute(createColumnQuery,
function (err, _results, _fields) {
//TODO: emit success or failure metrics based on return value
if (err) {
reject(err);
return;
}
// Skip creating separate index if isUnique is true, because
// UNIQUE KEY constraint already creates an index automatically
if (isUnique) {
resolve(true);
return;
}
return _createIndex(resolve, reject, tableName, sqlJsonColumn, isUnique);
});
} catch (e) {
LOGGER.error({err: e, tableName, jsonField, operation: 'createIndexForJsonField'}, 'Error creating index');
const errorMessage = `Exception occurred while creating column for JSON field`;
reject(errorMessage);
//TODO: Emit Metrics
}
});
}
/**
* It takes a nested object and returns a query string and an array of values
* @param {Object} subQueryObject - This is the object that you want to convert to a query.
* @param {string} [parentKey] - This is the key of the parent object.
* @returns {Object} An object with two properties, getQuery and valArray.
* @private
*/
function _prepareQueryForNestedObject(subQueryObject, parentKey = "") {
const valArray = [];
let subQuery = '';
let numberOfEntries = Object.keys(subQueryObject).length;
for (const [key, value] of Object.entries(subQueryObject)) {
if (isObject(value)) {
const partialKey = (parentKey === "") ? key : parentKey + '.' + key;
let subResults = _prepareQueryForNestedObject(value, partialKey);
if (subResults) {
subQuery += subResults.getQuery;
subResults.valArray.forEach(result => {
valArray.push(result);
});
}
numberOfEntries = numberOfEntries - 1;
continue;
}
const fullKey = (parentKey === "") ? key : parentKey + '.' + key;
const sqlColumnName = getColumNameForJsonField(fullKey);
if (numberOfEntries > 1) {
subQuery = subQuery + sqlColumnName + ' = ? and ';
} else {
subQuery = subQuery + sqlColumnName + ' = ? ';
}
valArray.push(value);
numberOfEntries = numberOfEntries - 1;
}
return {
'getQuery': subQuery,
'valArray': valArray
};
}
/**
* It takes a table name and a query object and returns a query string and an array of values
* @param {string} tableName - The name of the table in which the data is stored.
* @param{Object} queryObject - The object that you want to search for.
* @param {Object} options Optional parameter to add pagination.
* @param {number} options.pageOffset specify which row to start retrieving documents from. Eg: to get 10 documents from
* the 100'th document, you should specify `pageOffset = 100` and `pageLimit = 10`
* @param {number} options.pageLimit specify number of documents to retrieve. Eg: to get 10 documents from
* the 100'th document, you should specify `pageOffset = 100` and `pageLimit = 10`
* @private
*/
function _prepareQueryOfIndexSearch(tableName, queryObject, options) {
let getQuery = `SELECT ${PRIMARY_COLUMN},${JSON_COLUMN} FROM ${tableName} WHERE `;
const result = _prepareQueryForNestedObject(queryObject);
return {
'getQuery': getQuery + result.getQuery + ` ${_getLimitString(options)}`,
'valArray': result.valArray
};
}
/**
* _queryIndex() is a function that takes a queryParams object, a resolve function, and a reject function as parameters.
* It then executes the query in the queryParams object, and if the query is successful, it returns the results of
* the query to the resolve function. If the query is unsuccessful, it returns the error to the reject function
* @param {Object} queryParams - This is an object that contains the query and the values to be used in the query.
* @param {Function}resolve - a function that takes a single argument, which is the result of the query.
* @param {Function} reject - a function that will be called if the query fails.
* @returns {Array} An array of objects
* @private
*/
function _queryIndex(queryParams, resolve, reject) {
CONNECTION.execute(queryParams.getQuery, queryParams.valArray,
function (err, results, _fields) {
//TODO: emit success or failure metrics based on return value
if (err) {
reject(err);
return;
}
if (results && results.length > 0) {
const retResults = [];
for (const result of results) {
result[JSON_COLUMN].documentId = result[PRIMARY_COLUMN];
retResults.push(result[JSON_COLUMN]);
}
resolve(retResults);
return;
}
resolve([]);
});
}
/**
* It takes a table name, a column name, and a query object, and returns a promise that resolves to an array of objects
* NB: This query will return only 1000 entries.
* @example <caption> Sample code </caption>
* const tableName = 'customer';
* const queryObject = {
* 'lastName': 'Alice',