-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbo.js
executable file
·1933 lines (1357 loc) · 48.4 KB
/
dbo.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
/*
The MIT License (MIT)
Copyright (c) 2015 Johan Zetterberg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
NOTES
=====
Async update
------------
We can wait for .load but never for .add
Data from .add needs to be available right away!
Todo
----
Ideas
-----
DBO.List.debug(field): throw on set
*/
"use strict";
// Dependencies
var mysql = require("mysql"),
cli = require("cli-color"),
deasync = require("deasync");
// Allow larger stack traces because the mysql modules takes up at least 10 lines by himself (meh) ...
Error.stackTraceLimit = Infinity;
// Private variables and functions ...
var database,
db_config = {host: "127.0.0.1", user: "user", password : "password", database: "database"},
dbRetry = 2000,
listedTables = [],
debug = {};
debug.warn = function(msg) {
if(DBO.cfg.debug.showWarnings) {
debug.log("warn", msg, "yellow");
}
}
debug.sql = function(sql) {
if(DBO.cfg.debug.showSQL) {
debug.log("SQL ", sql, "cyan");
}
}
debug.info = function(info) {
if(DBO.cfg.debug.showInfo) {
debug.log("info", info, "white");
}
}
debug.log = function(type, msg, color) {
if(!color) {
throw new Error("No color defined. You probably meant to call debug.info.");
}
if(DBO.cfg.debug.useColors) {
console.log("DBO " + type + ": " + cli[color](msg));
}
else {
console.log("DBO " + type + ": " + msg);
}
}
function handleDbDisconnect() {
// Recreate the connection, since the old one cannot be reused.
database = mysql.createConnection(db_config);
database.connect(function(err) {
if(err) {
/*
The server is either down or restarting (takes a while sometimes).
We introduce a delay before attempting to reconnect, to avoid a hot loop, and to allow our node script to process asynchronous requests in the meantime.
If you're also serving http, display a 503 error.
Connection to the MySQL server is usually lost due to either server restart, or a connnection idle timeout (the wait_timeout
*/
debug.warn("Error when connecting to the database!\n", err, "Trying again in " + dbRetry + "ms ...");
setTimeout(handleDbDisconnect, dbRetry);
}
});
database.on("error", function(err) {
if(err.code === "PROTOCOL_CONNECTION_LOST") {
handleDbDisconnect();
}
else {
throw new Error("Database error: ", err);
}
});
}
// Public objects and functions ...
var DBO = {};
DBO.cfg = {};
DBO.cfg.pointToParentInLinks = true;
DBO.cfg.asyncListsCreation = false; // If false, we have to wait for the list to populate
DBO.cfg.checkHasProperty = true; // For optimization if we decide to be evil
DBO.cfg.updateDelay = 1000; // Wait this many ms before pushing updates to the database
DBO.cfg.enableArray = true; // If we should write to the Array.prototype
DBO.cfg.debug = {showSQL: true, showWarnings: true, useColors: true, showInfo: true};
if(Array.prototype.load || Array.prototype.add) {
DBO.cfg.enableArray = false;
debug.warn("Array already has prototype that dbo wants to use. DBO.Array will not be supported!" )
}
DBO.connect = function(dbCfg) {
db_config = dbCfg;
if(database) {
throw new Error("Already connected to the database!");
}
else {
handleDbDisconnect()
}
}
DBO.disconnect = function(callback) {
// Wait for possible timeouts before disconnecting (maybe we should keep track of all tables!?)
setTimeout(function() {
database.end(function(err) {
if(callback) callback();
if(err) throw err;
});
}, DBO.cfg.updateDelay + 100);
}
DBO.Table = function(arg, callback) {
/*
The DBO.Table holds the *data* object.
*/
var table = this,
dbTable = arg.table,
identifiers = arg.keys;
if(!database) {
throw new Error("You need to connect to a database! See DBO.connect()");
}
else if(dbTable === false) {
throw new Error("DBO.Table can not be used in offline mode!");
}
else if(!dbTable) {
throw new Error("No table defined in argument " + JSON.stringify(arg) + "!");
}
else if(!identifiers) {
throw new Error("No key(s) defined in argument " + JSON.stringify(arg) + "!");
}
var query = database.query("SELECT * FROM ?? WHERE ?", [dbTable, identifiers], function(err, rows) {
if (err) throw new Error(err);
if(rows.length == 1) {
var data = rows[0];
table.init(data, dbTable, identifiers, true);
}
else {
throw new Error("Expected 1 row! " + rows.length + " rows was returned from:\n" + query.sql);
}
if(callback) callback();
});
debug.sql(query.sql);
}
DBO.Table.prototype.init = function(data, dbTable, identifiers, inserted) {
var table = this;
if(!dbTable) {
throw new Error("Table init without dbTable");
}
if(!identifiers) {
throw new Error("Table init without identifiers");
}
Object.defineProperty(table, "__table", { value: dbTable, enumerable: false });
Object.defineProperty(table, "__identifiers", { value: identifiers, enumerable: false });
Object.defineProperty(table, "__updateTimer", { value: {}, enumerable: false, writable: true });
Object.defineProperty(table, "__changed", { value: {}, enumerable: false, writable: true });
Object.defineProperty(table, "__hasChanged", { value: false, enumerable: false, writable: true });
Object.defineProperty(table, "__inserted", { value: inserted, enumerable: false, writable: true });
for(var field in data) {
table.define(field, data[field]);
}
// Object.keys(data).forEach(table.define);
//debug.info("" + dbTable + " " + JSON.stringify(identifiers) + " initiated.");
}
DBO.Table.prototype.define = function (name, currentValue) {
var table = this;
/*
Call Object.defineProperty on the attribute to add getter and setter
*/
if(currentValue == null) { // NuLL can cause bugs ...
debug.warn(table.__table + "." + name + " is NULL where " + JSON.stringify(table.__identifiers));
//throw new Error(table.__table + "." + name + " is NULL where " + JSON.stringify(table.__identifiers));
}
Object.defineProperty( table, name, {
get: function(){ return currentValue; },
set: function(value) {
if(value == undefined) {
throw new Error("The new value for " + name + " is undefined!");
}
else if(value !== value) {
throw new Error("The new value for " + name + " is NaN!");
}
else if(value == null) {
debug.warn("The new value for " + name + " is null!");
}
/*
debug.info(JSON.stringify(value) + " = " + value);
debug.info("dbTable=" + table.__table);
debug.info("name=" + name);
debug.info("identifiers=" + JSON.stringify(table.__identifiers));
*/
// Database queries are costly, so check if the value actually updates before updating it.
if(currentValue != value) {
table.__changed[name] = true;
table.__hasChanged = true;
// Set update timer if it's not set
//debug.info("timeoutSet(table.__updateTimer)=" + timeoutSet(table.__updateTimer));
if(!timeoutSet(table.__updateTimer)) {
table.__updateTimer = setTimeout(function() {table.update();}, DBO.cfg.updateDelay)
}
}
currentValue = value;
},
enumerable: true,
});
}
DBO.Table.prototype.update = function () {
var table = this;
/*
Update all changed fields
Only make an UPDATE if the row has been INSERT:ed
*/
//debug.info("update called. inserted=" + table.__inserted + " hasChanged=" + table.__hasChanged);
//debug.info(JSON.stringify(table));
if(table.__inserted && table.__hasChanged) {
var fields = {};
for(var name in table.__changed) {
fields[name] = table[name];
table.__changed[name] = false;
}
table.__hasChanged = false;
var query = database.query("UPDATE ?? SET ? WHERE " + createWhereString(table.__identifiers), [table.__table, fields], function(err, result) {
if (err) throw new Error(err);
});
debug.sql(query.sql);
}
}
DBO.List = function(arg, callback) {
/*
Creates a list of something, initiates and gives each item its data ...
The first key will be used as index to the associative array.
Keys can be passed in as key or keys (array).
*/
var list = this,
data,
dbTable = arg.table,
constructor = arg.fun,
identifiers = arg.keys,
done = false;
if(identifiers === undefined) {
if(arg.key) {
identifiers = [arg.key];
}
else {
identifiers = ["id"];
debug.info("Identifier for table " + dbTable + " set to 'id'");
}
}
else if(!Array.isArray(identifiers)) {
throw new Error("Identifiers must be an array");
}
else if(identifiers.length == 0) {
identifiers = ["id"];
debug.info("Identifier for table " + dbTable + " set to 'id'");
}
Object.defineProperty(list, "__table", { value: dbTable, enumerable: false });
Object.defineProperty(list, "__constructor", { value: constructor, enumerable: false });
Object.defineProperty(list, "__identifiers", { value: identifiers, enumerable: false });
Object.defineProperty(list, "__links", { value: [], enumerable: false });
Object.defineProperty(list, "__columns", { value: {}, enumerable: false });
Object.defineProperty(list, "__increment", { value: 0, enumerable: false, writable: true });
Object.defineProperty(list, "__childLinks", { value: [], enumerable: false });
Object.defineProperty(list, "__root", { value: null, enumerable: false });
Object.defineProperty(list, "__index", { value: {}, enumerable: false });
if(dbTable === false) {
debug.warn("No database will be used for persistent storage!");
return;
}
else if(!database) {
throw new Error("You need to connect to a database! See DBO.connect()");
}
else if(!dbTable) {
throw new Error("No database table specified!");
}
else if(DBO.cfg.asyncListsCreation === false && callback) {
throw new Error("Can not have a callback when DBO.cfg.asyncListsCreation is set to false!");
}
if(listedTables.indexOf(dbTable) > -1) {
throw new Error("There's already a List for " + dbTable + "!");
}
else {
listedTables.push(dbTable);
}
var query = database.query("SHOW COLUMNS FROM ??", [dbTable], function(err, rows) {
if (err) throw new Error(err);
var defaultValue, dataType;
for(var i=0; i<rows.length; i++) {
defaultValue = rows[i].Default;
// Avoid null ...
if(defaultValue == null) {
// Check type
dataType = rows[i].Type.replace(" unsigned", "").replace(" signed", "").replace(/\(.*\)/, "");
switch(dataType) {
case "text": defaultValue = ""; break;
case "varchar": defaultValue = ""; break;
case "tinyint": defaultValue = false; break;
case "int": defaultValue = 0; break;
case "bigint": defaultValue = 0; break;
case "decimal": defaultValue = 0; break;
case "timestamp": defaultValue = new Date(); break;
case "datetime": defaultValue = new Date(); break;
default: defaultValue = new Date(); break;
}
debug.info("Default value for " + dbTable + "." + rows[i].Field + " (null) set to " + type(defaultValue) + " " + defaultValue);
}
// Set value for "CURRENT_TIMESTAMP"
if((dataType == "timestamp" || dataType == "datetime") && defaultValue == "CURRENT_TIMESTAMP") {
defaultValue = new Date();
}
list.__columns[rows[i].Field] = {default: defaultValue, auto_increment: (rows[i].Extra == "auto_increment")}
}
// Check if database table has the columns specified in identifiers
for(var i=0; i< identifiers.length; i++) {
if(!list.__columns[identifiers[i]]) {
throw new Error("" + dbTable + " do not have column " + identifiers[i] + "!");
}
}
if(list.__columns[identifiers[0]].auto_increment) {
// The (primary) key has "auto_increment". Get the current AUTO_INCREMENT value
var query = database.query("SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?", [db_config.database, dbTable], function(err, rows) {
if (err) throw new Error(err);
list.__increment = rows[0].AUTO_INCREMENT;
selectData();
});
debug.sql(query.sql);
}
else {
selectData();
}
});
debug.sql(query.sql);
if(DBO.cfg.asyncListsCreation === false) {
while(!done) {
deasync.runLoopOnce();
}
if(callback) callback();
}
function selectData() {
var query = database.query("SELECT * FROM ??", [dbTable], function(err, rows) {
if (err) throw new Error(err);
for(var i=0; i<rows.length; i++) {
fillData(rows[i])
}
// Create an index for each identifier
/*
for(var i=0; i<identifiers.length; i++) {
createIndex(list, identifiers[i]);
}
*/
done = true;
if(callback && DBO.cfg.asyncListsCreation) callback();
});
debug.sql(query.sql);
}
function fillData(row) {
var name = row[identifiers[0]];
var dataTable = Object.create(DBO.Table.prototype); // We use Object.create here because we don't want to call the actual function. That would result in another database SELECT.
var table_identifiers = {};
for(var i=0; i< identifiers.length; i++) {
table_identifiers[identifiers[i]] = row[identifiers[i]];
}
dataTable.init(row, dbTable, table_identifiers, true);
if(constructor) {
list[name] = new constructor(dataTable); // Important we use new here so that the object function is called.
}
else {
list[name] = {};
}
list[name].data = dataTable;
}
}
DBO.List.prototype.add = function(values) {
var list = this,
object,
dataTable,
dbTable = list.__table,
identifiers = list.__identifiers, // Keys used to identify rows
columns = list.__columns, // List of all columns, with default values
identifierValues = {}, // Values used to identify this row
dataValues = {}, // Values to populate the data table
identifierValue; // The value used to identify the object in the object list
if(list.__root) {
throw new Error("Method 'add' was called on a branched list. Call .add on the root list instead!");
//debug.info("Method 'add' was called on a broken up list. Call .add on the root list instead!");
//return list.__root.add(values);
}
// Populate dataValues
for(var key in columns) {
//debug.info(key);
if(values.hasOwnProperty(key)) {
dataValues[key] = values[key];
}
else {
if(columns[key].default === "CURRENT_TIMESTAMP") {
dataValues[key] = new Date();
}
else {
dataValues[key] = columns[key].default;
}
}
}
// Check if the keys exist in values or are auto_increment. And get the values for them.
identifiers.forEach(function(key) { // identifiers is an Array
if(values.hasOwnProperty(key)) {
identifierValues[key] = values[key];
}
else if(columns[key].auto_increment) {
identifierValues[key] = list.__increment++; // ... mySQL can only have one auto_increment field.
dataValues[key] = identifierValues[key];
}
else {
throw new Error(key + " needs to have a value!");
}
});
identifierValue = identifierValues[identifiers[0]];
// Check if the index (first identifier) is a duplicate
if(list.hasOwnProperty(identifierValue)) {
throw new Error(identifier + " " + identifiers[0] + " already exist in the " + dbTable + "-list! " + identifiers[0] + " must be unique!");
//return list[identifierValue];
}
dataTable = Object.create(DBO.Table.prototype);
dataTable.init(dataValues, dbTable, identifierValues, false); // data, dbTable, identifiers(object literal), inserted
if(list.__constructor) {
object = new list.__constructor(dataTable); // We use new here so that the object function is called
}
else {
object = {}; // New vanilla object
}
object.data = dataTable;
// Insert the new object to the list
list[identifierValue] = object;
updateLinks();
if(dbTable) {
// Make the INSERT
var query = database.query("INSERT INTO ?? SET ?", [dbTable, values], function(err, result) {
/*
If there is an error here it's possible that the ID already exist because another app has made inserts.
(That's why we will switch to Postgree in the future so that we can monitor inserts from other apps.)
*/
if (err) throw err;
dataTable.__inserted = true;
});
debug.sql(query.sql);
}
else {
// OFFLINE MODE
debug.warn("The data added to " + dbTable + " was not inserted to the database!");
}
return object;
function updateLinks() {
// Set child links
list.__childLinks.forEach(setLinkAttribute);
// Keep the parent links up to date with the added object ...
list.__links.forEach(updateLink);
/*
for(var i=0, link; i<list.__links.length; i++) {
link = list.__links[i];
updateLink(link);
}
*/
function setLinkAttribute(childLink) {
var findObj = {},
search;
findObj[childLink.key] = dataTable[childLink.key];
search = childLink.list.find(findObj);
object[childLink.attribute] = search;
}
function updateLink(link) {
var parentList = link.list,
key = link.key,
attribute = link.attribute,
keyValue = object.data[key];
for(var index in parentList) {
if(parentList.hasOwnProperty(index)) {
if(index == keyValue) { // if player.name = army.owner
// Link the new object
parentList[index][attribute][identifierValue] = object;
}
}
}
}
}
}
DBO.List.prototype.link = function(arg) {
// {list: shares, key: "player", attribute: "shareholders"}
var list = this,
identifier = list.__identifiers[0],
otherList = arg.list,
key = arg.key,
attribute = arg.attribute || otherList.__table,
parentName = (typeof arg.pp === "string") ? arg.pp : key,
pointToParent = (arg.pp == undefined) ? DBO.cfg.pointToParentInLinks : arg.pp;
if(key === undefined) {
key = list.__table;
debug.warn("Key not defined in link to " + otherList.__table + ". Key '" + key + "' will be used!");
/*
This can cause hard to debug bugs if the table has two keys
Is there some way to intelligently throw an error instead!?
*/
}
if(!otherList.random().data.hasOwnProperty(key)) throw new Error("Field " + key + " does not exist in " + otherList.__table);
if(list.random()[attribute]) {
for(var name in listObject) console.log(name);
throw new Error(attribute + " in (" + list.__table + ") will be overwritten ... You probably don't want that, or there is a bug!");
}
//console.time("checkLinkExist");
for(var i=0, link; i<otherList.__links.length; i++) {
link = otherList.__links[i];
// Check if there's already a link between the two lists using key
if(link.list == list && link.key == key) {
throw new Error("The two lists are already linked using " + key + " as " + link.attribute + "!");
}
}
//console.timeEnd("checkLinkExist");
list.__childLinks.push({key: key, list: otherList, attribute: attribute});
otherList.__links.push({key: key, list: list, attribute: attribute});
//if(!otherList.__index.hasOwnProperty(key)) createIndex(otherList, key);
//console.time("makeLinks");
var keyValue, listObject, identifierValue;
for(var id in otherList) {
keyValue = otherList[id].data[key];
if(list.hasOwnProperty(keyValue)) {
listObject = list[keyValue];
identifierValue = listObject.data[identifier];
if(!listObject[attribute]) listObject[attribute] = list.branch();
if(keyValue == identifierValue) {
listObject[attribute][id] = otherList[id];
if(pointToParent) {
// Also make a pointer at the parent for easy access
if(otherList[id][parentName]) {
debug.warn("Key " + parentName + " in " + otherList.__table + " " + id + " already exist!\n ... You might want to call DBO.link with pp: false or set DBO.cfg.pointToParentInLinks = false");
}
else {
otherList[id][parentName] = listObject;
}
}
}
}
}
//console.timeEnd("makeLinks");
}
DBO.List.prototype.kill = function(keyValue) {
var list = this,
dbTable = list.__table,
key = list.__identifiers[0];
delete list[keyValue];
var query = database.query("DELETE FROM ?? WHERE ?? = ?", [dbTable, key, keyValue], function(err, result) {
if (err) throw new Error(err);
});
debug.sql(query.sql);
/*
Javascript is smart, so we don't have to do this:
// Traverse all links and remove this object
for(var i=0, link, attribute, parentList; i<list.__links.length; i++) {
link = list.__links[i];
attribute = link.attribute;
parentList = link.list;
delete parentList[attribute][keyValue];
}
*/
}
DBO.List.prototype.random = function() {
// Return a random object from the list
var list = this,
keys = Object.keys(list),
key = keys[Math.floor(Math.random()*keys.length)];
// What happens if there are no keys!? possible bug!
return list[key];
}
DBO.List.prototype.first = function() {
var list = this,
keys = Object.keys(list);
/*
You should never make assumptions about the order of elements in a JavaScript object.
*/
if(keys.length > 1) {
throw new Error("List contains more then one object. You might have duplicate data! Consider using Table.random instead!")
}
else if(keys.length == 0) {
return false;
}
for (var first in list) return list[first];
}
DBO.List.prototype.find = function(keyValues) {
/*
Works like ... AND ... AND ...
Use List.filter for more advanced search.
*/
var list = this,
identifier = list.__identifiers[0],
identifierValue,
foundObjects = list.branch(),
allMatch = true,
keys,
obj;
// Bug: calling .find on a list from a link (attribute).
if(typeof keyValues == "function") {
debug.info("A function was passed into 'find'. Method 'filter' will be used!");
return list.filter(keyValues);
}
else if(!keyValues) {
debug.warn("Method List.find called without argument! Returning full list.")
return list;
}
if(keyValues.hasOwnProperty(identifier)) {
// Take a shortcut, search only one object
identifierValue = keyValues[identifier];
if(list.hasOwnProperty(identifierValue)) {
allMatch = true;
for(var key in keyValues) {
if(list[identifierValue].data[key] != keyValues[key]) {
allMatch = false;
break;
}
}
if(allMatch) {
foundObjects[identifierValue] = list[identifierValue];
}
}
}
else {
// Search all objects (we might be able to optimize this code ...)
keys = Object.keys(list);
for(var i=0; i<keys.length; i++) {
obj = keys[i];
allMatch = true;
for(var key in keyValues) {
if(list[obj]["data"][key] != keyValues[key]) {
allMatch = false;
break;
}
}
if(allMatch) {
foundObjects[obj] = list[obj];
}
}
}
return foundObjects;
}
DBO.List.prototype.count = function(keyValues) {
/*
We might be able to optimize this by caching!?
*/
var list = this;
if(keyValues) {
list = list.find(keyValues);
}
return Object.keys(list).length;
}
DBO.List.prototype.sum = function(key) {
/* Takes any object, a list or the return from list.find and count a field with float type
*/
var sum = 0,
list = this;
for(var id in list) {
sum += list[id].data[key];
}
return sum;
}
DBO.List.prototype.filter = function(fun) {
/*
Filter a list using a function that returns true or false
*/
var list = this,
keys = Object.keys(list),
filtredList = list.branch();
for(var i=0; i<keys.length; i++) {
check(keys[i]);
}
function check(key) {
if(fun(list[key].data)) filtredList[key] = list[key];
}
return filtredList;
}
DBO.List.prototype.shuffledKeys = function() {
var list = this,
keys = Object.keys(list);
keys = shuffleArray(keys);
return keys;
function shuffleArray(array) {
// Fisher-Yates shuffle: Randomize array element order in-place.
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
}
DBO.List.prototype.sortedKeys = function(sortBy) {
var list = this,
keys = Object.keys(list),
keysSorted = keys.sort(sortFunction);
/*