-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql-suspend.js
1790 lines (1424 loc) · 53.1 KB
/
mysql-suspend.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
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
"use strict";
/**
* @class
* <p>For use with MySQL databases.</p>
* <p>Created by <a href="http://www.github.com/phanxgames">Phanxgames</a></p>
*
* <h4>Requirements:</h4>
* - ECMAScript 2015 (ES6)<br>
* - Node.JS 6.2.2 or later (tested on 6.2.2)
*
* <h4>Installation:</h4>
* <pre>
* npm install mysql-suspend
* </pre>
* <p>Note: the dictionaryjs, mysql and suspend modules should be automatically installed as dependencies, but you may need to install these as well.</p>
*
* Copy the dbConfig.ex.json file into your project source folder, rename to dbConfig.json,
* and update with your database connection information.
*
*
* <h4>Important:</h4>
* <p>You may only use one connection with each instance of this class.
* Close any opened connection before opening a new one.
* You may reuse an instance with a new connection if you close the previous.</p>
*
* <h4>Asynchronous nature:</h4>
* <p>All methods that include a callback (cb) have been designed to be used with the
* suspend library and may be placed behind a yield command. Be sure to leave the cb
* parameter null to use the suspend.resume functionality automatically.</p>
*
* <p>IMPORTANT: You will also need to set the resume reference in the constructor or the
* {@link MysqlSuspend#setResume} method, before the suspend.resume functionality will
* be enabled.</p>
*
* <p>If you do provide a callback, the 3rd parameter, "next" (ex: cb(err,result, next))
* will be the suspend.resume function reference so you may resume execution
* to move past the next yield command.</p>
*
* <h4>Example:</h4>
* <pre>
* var suspend = require("suspend");
* var MysqlSuspend = require("mysql-suspend");
*
* //Attach your dbConfig to the mysql-suspend module
* MysqlSuspend.config = require('./dbConfig.json');
*
* var db = new MysqlSuspend(suspend.resume);
*
* suspend(function*() {
* yield db.start();
*
* //find all users' email with a username that contains "phanx"
* yield db.query("select email from users where username LIKE ? ;",["%phanx%"]);
*
* if (db.error()) {
* console.error("Error:",db.error());
* return;
* }
*
* console.log(db.rowCount + " rows found!");
*
* for (let row of db.rows) {
* console.log(row);
* if (row.email == "test@test.com") {
* //..
* }
* }
*
* //..place other below examples here..
*
* yield db.end();
*
* })();
* </pre>
*/
class MysqlSuspend {
/**
* Pass in a unique config just for this instance by using require to get
* the JSON contents.
* <h4>Example:</h4>
* <pre>
* //..
* var suspend = require("suspend");
*
* var myconfig = require("./dbConfig2.json");
* var db = new MysqlSuspend(suspend.resume,myconfig);
* //..
* </pre>
* @param {Function} [resume=null] -
* set to suspend.resume from generator context
* to use suspend library with yields. See {@link setResume}.
* @param {Object} [config=null] - Overwrite the global config for just this instance.
*/
constructor(resume,config) {
this.config = null;
this.resume = resume;
this.resume_next = null;
this.start_stack = null;
this.opened = null;
this.client = null; //connection
this.pool = null;
this.guid = null;
this.result = null;
this.resultCount = 0;
this.last_error = null;
this._throwErrors = true;
this.setLocalConfig(config);
}
//##########################################################################
// Config Methods
//##########################################################################
/**
* Disabling throwErrors will stop suspend from throwing errors on callbacks.
* This is enabled by default.
* @param {Boolean} value
*/
set throwErrors(value) {
this._throwErrors = value;
}
/**
* @description Required to set this before you first initalize this class.<br>
* This should be static across your entire project and only needs to be set once.<br>
* Set to the Contents of dbConfig.json as Object.
* <h4>Example:</h4>
* <pre>
* var Mysql = require("mysql-suspend");
* Mysql.config = require("./dbConfig.json");
* //..
* </pre>
*/
static set config(config) {
dbConfig.config = config;
}
/**
*
* @param {Object} config
*/
setLocalConfig(config) {
this.config = config;
if (this.config!=null) {
updateAutoCloseInterval(config.auto_closer_enabled,config.auto_closer_minutes);
}
}
/**
* Enables automatic calling of suspend.resume on all methods with
* optional callbacks. See Class comment at top of file.
* @param {Function} resume
* set to suspend.resume, set to null to disable
*/
setResume(resume) {
this.resume = resume;
}
//##########################################################################
// Connection Methods
//##########################################################################
usePool() {
if (dbConfig.config.usePool==true) return true;
return false;
}
/**
* Opens a database connection. Must be called before using any other method.
* <p>Alias: open(cb)</p>
* @param {MysqlSuspend~cbOnError} [cb=null] - Use callback or leave null to use suspend.resume.
* <br> Returns cb()
*/
start(cb) {
var self = this;
self.initHandleCallback();
//get the stack from the scope of method call
self.start_stack = new Error().stack;
try {
if (self.usePool()) {
if (self.pool==null)
self.pool = mysql.createPool(dbConfig.config.mysql);
self.pool.getConnection(function(err, conn) {
if (err) {
console.error("Problem getting database connection from pool:\n"
+ self.start_stack + "\n", err);
self.handleCallback(cb,err);
self.start_stack = null;
return;
}
self.guid = generateToken(6, dictTokens);
self.opened = getTimestamp();
self.client = conn;
openConnections.set(self.guid, self);
self.handleCallback(cb, null);
});
} else {
if (self.opened!=null) {
var err = new Error("Database connection already open.");
console.error(err);
self.handleCallback(cb, err);
return;
}
let connection = mysql.createConnection(dbConfig.config.mysql);
connection.connect(function(err) {
if (err) {
console.error("Problem getting database connection:\n" + self.start_stack + "\n", err);
self.handleCallback(cb,err);
self.start_stack = null;
return;
}
self.guid = generateToken(6, dictTokens);
self.opened = getTimestamp();
self.client = connection;
openConnections.set(self.guid, self);
self.handleCallback(cb, null);
});
}
} catch (err) {
console.error("Problem getting database connection:\n" + self.start_stack + "\n", err);
self.handleCallback(cb, err);
self.start_stack = null;
}
}
/**
* @ignore
*/
open(cb) {
this.start(cb);
}
/**
* Closes the connection.
* You must call this when you are done with this database connection.
* If you do not end the connection the pool will be exhausted.
* <p>Alias: close(cb)</p>
* @param {MysqlSuspend~cbOnEmpty} [cb=null] - Use callback or leave null to use suspend.resume.
* <br>Returns cb(err)
*/
end(cb) {
var self = this;
self.initHandleCallback();
if (self.opened!=null) {
var elapsed = getTimeDiff(self.opened,"ms");
console.log("Connection released after in use for " + elapsed + " ms.");
}
if (self.client == null) {
self.handleCallback(cb, null);
return;
}
if (self.usePool()) {
self.client.release();
self.handleCallback(cb, null);
} else {
self.client.end(function (err) {
if (err) {
console.error("Error closing connection", err);
}
openConnections.remove(self.guid);
self.client = null;
self.opened = null;
self.start_stack = null;
self.result = null;
self.handleCallback(cb, null);
self.resume_next = null;
});
}
}
/**
* @ignore
*/
close(cb) {
this.end(cb);
}
//##########################################################################
// Query Methods
//##########################################################################
/**
* Executes SQL statement on database.
* <p>Use question-marks (ie: ?) as unnamed parameters within the SQL statement.</p>
* <h4>Example:</h4>
* <pre>
* //..
* yield db.query("select username from users where email=?;",["test@test.com"]);
* for (let row of db.rows) {
* console.log(row.username);
* }
* //..
* </pre>
* @param {string} sql - sql statement to execute
* @param {Array} [paras=null] - array of parameters, replacing "?" in SQL
* @param {MysqlSuspend~cbOnQuery} [cb=null] - Use callback or leave null to use suspend.resume.
* <br>Returns cb(err,results) where result is an array of rows.
*/
query(sql, paras, cb) {
var self = this;
self.initHandleCallback();
self.resultCount = 0;
//Check if database connection is open.
if (self.client==null) {
var err = new Error("Database Connection is not open.");
console.error(err);
self.handleCallback(cb,err);
return;
}
//get the stack from the scope of method call
var stack = new Error().stack;
//Replaces question marks within SQL statement with numbered parameters flags
//sql = replaceQMarks(sql);
//TODO implement parametrized queries
//Start timer to collect query execution time
var querystart = timeStart();
//execute the query on the mysql client
self.client.query(sql,paras,function(err,result) {
//calculate execution time
var elapsed = timeEnd(querystart);
//check if there is a problem with the result
if (err || result==null ) {
var errObj = {
stack: stack,
sql: sql,
paras: paras
};
if (err!=null && err.hasOwnProperty("message"))
errObj.message = err.message;
else
errObj.message = "Unspecified Database Query Error."
console.error("Database Error (" + elapsed + "s): ", errObj);
self.handleCallback(cb,errObj);
return;
}
console.log("Query completed in " + elapsed +" seconds.");
if (Array.isArray(result))
self.result = result;
else {
self.result = [result];
}
self.result = result;
self.resultCount = result.length;
self.handleCallback(cb,null,self.result);
stack = null;
});
}
/**
* Merge allows you to insert or update a record by proving insert
* and update sql statements.
* <p>Try using instead the {@link MysqlSuspend#mergeHelper} to generate the
* two sql statements.</p>
* @param {String} sqlInsert - sql statement with unnamed parameters (ie: ?)
* @param {Array} [parasInsert=null] - array of parameters to replace ? in sql
* @param {String} sqlUpdate - sql statement with unnamed parameters (ie: ?)
* @param {Array} [parasUpdate=null] - array of parameters to replace ? in sql
* @param {MysqlSuspend~cbOnMerge} [cb=null] - Use callback or leave null to use suspend.resume.
* <br>Returns cb(err,result) where result will be either
* "insert" or "update" depending on which action was used.
*/
merge(sqlInsert,parasInsert,sqlUpdate,parasUpdate,cb) {
var self = this;
self.initHandleCallback();
self.resultCount = 0;
if (self.client==null) {
var err = new Error("Database connect is not open.");
console.error(err);
self.handleCallback(cb,err);
return;
}
var stack = new Error().stack;
//sqlInsert = replaceQMarks(sqlInsert);
//sqlUpdate = replaceQMarks(sqlUpdate);
var querystart = process.hrtime();
var loopCount = 0;
function doLoop() {
loopCount++;
if (loopCount > 10) {
var errObj = {
message: "Database Merge exceeded iteration limit",
stack: stack,
sqlInsert: sqlInsert,
sqlUpdate: sqlUpdate,
parasInsert: parasInsert,
parasUpdate: parasUpdate
};
var elapsed = timeEnd(querystart);
console.error("Database Error ("+ elapsed + " s): ", errObj);
self.handleCallback(cb,errObj);
return;
}
//attempt to update the record
self.client.query(sqlUpdate,parasUpdate,function(err,result) {
var elapsed = timeEnd(querystart);
if (err) {
var errObj = {
stack: stack,
sql: sqlUpdate,
paras: parasUpdate
};
if (err!=null && err.hasOwnProperty("message"))
errObj.message = err.message;
else
errObj.message = "Unspecified Merge:Update error.";
console.error("Database Error (" + elapsed + " s): ",errObj);
self.handleCallback(cb,errObj);
return;
}
//check if any rows were updated/affected
if (result!=null && result.hasOwnProperty("rowCount") &&
result.rowCount > 0) {
self.resultCount = result.rowCount;
//Merge completed by successfully updating!
console.log("Query completed in " + elapsed + " seconds.");
self.handleCallback(cb,null,"update");
stack = null;
return;
}
self.client.query(sqlInsert,parasInsert,function(err,result) {
var elapsed = timeEnd(querystart);
if (err) {
//error with inserting? let's try that one again
doLoop();
return;
}
if (result!=null && result.hasOwnProperty("rowCount") &&
result.rowCount > 0) {
console.log("Query completed in " + elapsed + " seconds.");
self.resultCount = result.rowCount;
self.handleCallback(cb,null,"insert");
stack = null;
return;
}
//we shouldn't get to this point, so... Let's loop again!
doLoop();
});
});
}
doLoop();
}
//##########################################################################
// Select Methods
//##########################################################################
/**
* Executes SQL statement on database and returns the first row.
* <p>Use question-marks (ie: ?) as unnamed parameters within the SQL statement.</p>
* <h4>Example:</h4>
* <pre>
* //..
* let row = yield db.selectRow("select username from users where email=?;",["test@test.com"]);
* //..
* </pre>
* @param {string} sql - sql statement to execute
* @param {Array} [paras=null] - array of parameters, replacing "?" in SQL
* @param {MysqlSuspend~cbOnQuery} [cb=null] - Use callback or leave null to use suspend.resume.
* <br>Returns cb(err,results) where result is an array of rows.
*/
selectRow(sql, paras, cb) {
this.initHandleCallback();
this.query(sql, paras, (err,result) => {
if (err || result==null || result.length==0) {
this.handleCallback(cb,err,result);
return;
}
this.handleCallback(cb,null,result[0]);
});
}
/**
* Executes SQL statement on database and returns the array of rows.
* <p>Use question-marks (ie: ?) as unnamed parameters within the SQL statement.</p>
* <h4>Example:</h4>
* <pre>
* //..
* let arr = yield db.selectArray("select username from users where email=?;",["test@test.com"]);
* //..
* </pre>
* @param {string} sql - sql statement to execute
* @param {Array} [paras=null] - array of parameters, replacing "?" in SQL
* @param {MysqlSuspend~cbOnQuery} [cb=null] - Use callback or leave null to use suspend.resume.
* <br>Returns cb(err,results) where result is an array of rows.
*/
selectArray(sql, paras, cb) {
this.query(sql, paras, cb);
}
//##########################################################################
// Transaction Methods
//##########################################################################
/**
* Begins a transaction.
* @param {MysqlSuspend~cbOnError} [cb=null] - Use callback or leave null to use suspend.resume.
* <br>Returns cb(err)
*/
begin(cb) {
this.query("START TRANSACTION;",null,cb);
}
/**
* Commits the transaction.
* @param {MysqlSuspend~cbOnError} [cb=null] - Use callback or leave null to use suspend.resume.
* <br>Returns cb(err)
*/
commit(cb) {
this.query("COMMIT;",null,cb);
}
/**
* Rolls back the transaction.
* @param {MysqlSuspend~cbOnError} [cb=null] - Use callback or leave null to use suspend.resume.
* <br>Returns cb(err)
*/
rollback(cb) {
this.query("ROLLBACK;",null,cb);
};
//##########################################################################
// Helper Methods
//##########################################################################
/**
* Select Statement Helper.
* <h4>Example:</h4>
* Select emails from users table that have a username that starts with the letter "h":
* <pre>
* //..
* yield db.selectHelper({
* table:"users",
* columns:["username","email"],
* where: db.whereHelper({
* "username -like":"h%"
* }),
* orderBy: db.orderByHelper({
* "email":"ASC"
* })
* });
*
* for (let row of db.rows) {
* console.log(row);
* //Output example: {username:"Tester",email:"test@test.com"}
* }
*
* //..
* </pre>
* @param {Object} options - Required. See properties:
* @param {String} options.table - Table name
* @param {Array} options.columns - Array of column names to select.
* @param {String} [options.where=null] - where clause sql statement segment (ie: name=? OR id=? )
* <br>You may also use {@link MysqlSuspend#whereHelper}
* @param {Array} [options.whereParas=null] - Array of values to replace parameters in where SQL
* <br>Not needed if you use whereHelper.
* @param {String} [options.orderBy=null] - order clause sql statement segment (ie: name ASC)
* <br>You may also use {@link MysqlSuspend#orderByHelper}
* @param {int} [options.limit=null] - Number of records to return, or null for infinite.
* @param {int} [options.start=0] - Start row index position.
* @param {MysqlSuspend~cbOnQuery} [cb=null] - Use callback or leave null to use suspend.resume.
* <br>Returns cb(err,results) where result is an array of rows.
*/
selectHelper(options,cb) {
if (options==null) {
let err = new Error("SelectHelper: Options parameter is required.");
if (this._throwErrors)
throw err;
else
console.error(err);
return;
}
var table = options.table || null;
var columns = options.columns || null;
var where = options.where || null;
var whereParas = options.whereParas || null;
var orderBy = options.orderBy || null;
var limit = options.limit || null;
var start = options.start || 0;
if (table == null) {
let err = new Error("SelectHelper: Table option is required.");
if (this._throwErrors)
throw err;
else
console.error(err);
return;
}
//table,columns,where,whereParas,orderBy
var sql = "SELECT ";
var finalParas = null;
if (Array.isArray(columns))
sql += columns.join(",");
else if (columns!=null)
sql += columns;
else
sql += " * ";
sql += " FROM " + table;
if (where!=null) {
if (isObject(where) &&
where.hasOwnProperty("sql") &&
where.hasOwnProperty("paras")
) {
sql += " WHERE " + where.sql;
finalParas = where.paras;
} else {
where = where.trim();
var lowerWhere = where.toLowerCase();
if (lowerWhere.substr(0,5)=="where")
where.substr(5);
sql += " WHERE " + where;
finalParas = whereParas;
}
}
if (orderBy!=null) {
orderBy = orderBy.trim();
var lowerOrderBy = orderBy.toLowerCase();
if (lowerOrderBy.substr(0,8)=="order by")
orderBy.substr(8);
sql += " ORDER BY " + orderBy;
}
if (limit!=null) {
sql += " LIMIT " + limit + " OFFSET " + start ;
}
sql += " ;";
if (finalParas==null || finalParas.length==0) finalParas = null;
this.query(sql,finalParas,cb);
}
/**
* Insert Statement Helper
* <h4>Example:</h4>
* Insert new user into users table.
* <pre>
* //..
* yield db.insertHelper({
* table:"users",
* columns:{
* "username":"tester",
* "email":"oldemail@test.com"
* }
* });
* //..
* </pre>
* @param {Object} options - Required. See properties:
* @param {String} options.table - Table name
* @param {Array} [options.columns=null] - Leave null to use table order of columns.
* <br>Array of column names to update, use with options.values property to specifiy values.
* @param {Object} [options.columns=null] - Or Object where keys are column names and values are values.
* Note: options.values property not needed.
* @param {Array} [options.values=null] - Array of values used with options.columns (Array) property.
* @param {MysqlSuspend~cbOnError} [cb=null] - Use callback or leave null to use suspend.resume.
* <br>Returns cb(err)
*/
insertHelper(options,cb) {
if (options==null) {
let err = new Error("InsertHelper: Options parameter required.");
if (this._throwErrors)
throw err;
else
console.error(err);
return;
}
var table = options.table || null;
var columns = options.columns || null;
var values = options.values || null;
if (table == null) {
let err = new Error("InsertHelper: Table option is required.");
if (this._throwErrors)
throw err;
else
console.error(err);
return;
}
var sql = "INSERT INTO " + table;
let tempColumns;
let tempValues;
if (columns != null) {
tempColumns = null;
tempValues = null;
if (isObject(columns)) {
tempColumns = [];
tempValues = [];
for (let key in columns) {
if (columns.hasOwnProperty(key)) {
tempColumns.push(key);
tempValues.push(columns[key]);
}
}
} else {
//split if columns is a string
if (!Array.isArray(columns))
tempColumns = columns.split(",");
else
tempColumns = columns;
tempValues = values;
}
if (tempValues==null || tempColumns==null ||
tempColumns.length != tempValues.length) {
let err = new Error("InsertHelper: Number of Columns and Values do not match.");
if (this._throwErrors)
throw err;
else
console.error(err);
return;
}
sql += "(" + tempColumns.join(",") + ") VALUES ";
} else {
tempValues = values;
}
sql += " (";
for (let i=0; i<tempValues.length; i++) {
sql += "?,";
}
sql = removeLastChara(sql) + ");";
this.query(sql,tempValues,cb);
}
/**
* Update Statement Helper
* <h4>Example:</h4>
* Updates user's email by username.
* <pre>
* //..
* yield db.updateHelper({
* table: "users",
* columns: {
* "email":"newemail@test.com"
* },
* where: db.whereHelper({
* "username":"tester"
* })
* });
* //..
* </pre>
* @param {Object} options - Required. See properties:
* @param {String} options.table - Table name
* @param {Array} options.columns - Array of column names to update, use with options.values property to specifiy values.
* @param {Object} options.columns - Or Object where keys are column names and values are values.
* Note: options.values property not needed.
* @param {Array} [options.values=null] - Array of values used with options.columns (Array) property.
* @param {String} [options.where=null] - where clause sql statement segment (ie: name=? OR id=? )
* <br>You may also use {@link MysqlSuspend#whereHelper}
* @param {Array} [options.whereParas=null] - Array of values to replace parameters in where SQL
* <br>Not needed if you use whereHelper.
* @param {MysqlSuspend~cbOnError} [cb=null] - Use callback or leave null to use suspend.resume.
* <br>Returns cb(err)
*/
updateHelper(options,cb) {
var self = this;
if (options==null) {
let err = new Error("UpdateHelper: Options parameter required.");
if (this._throwErrors)
throw err;
else
console.error(err);
return;
}
var table = options.table;
var columns = options.columns;
var values = options.values;
var where = options.where;
var whereParas = options.whereParas;
if (table == null) {
let err = new Error("UpdateHelper: Table option is required.");
if (this._throwErrors)
throw err;
else
console.error(err);
return;
}
var sql = "UPDATE " + table + " SET ";
var finalParas = null;
let tempColumns;
let tempValues;
if (isObject(columns)) {
tempColumns = [];
tempValues = [];
for (let key in columns) {
if (columns.hasOwnProperty(key)) {
tempColumns.push(key);
tempValues.push(columns[key]);
}
}
} else {
//split if columns is a string
if (!Array.isArray(columns))
tempColumns = columns.split(",");
else
tempColumns = columns;
tempValues = values;
}
if (tempValues==null || tempColumns==null ||
tempColumns.length != tempValues.length) {
let err = new Error("UpdateHelper: Number of Columns and Values do not match.");
if (this._throwErrors)
throw err;
else
console.error(err);
return;
}
for (let column of tempColumns) {
sql += column+"=?,";
}
sql = removeLastChara(sql);
finalParas = tempValues;
if (finalParas==null) finalParas = [];
if (where!=null) {
if (isObject(where) &&
where.hasOwnProperty("sql") &&
where.hasOwnProperty("paras")
) {
sql += " WHERE " + where.sql;
Array.prototype.push.apply(finalParas,where.paras);
} else {
where = where.trim();
var lowerWhere = where.toLowerCase();
if (lowerWhere.substr(0,5)=="where")