-
Notifications
You must be signed in to change notification settings - Fork 0
/
adb.js
executable file
·1993 lines (1925 loc) · 60.1 KB
/
adb.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
/*
Active Database (ADb)
--------------------------------
Copyright: Copyright (c) 2006-2009 Andy Kant, http://andykant.com/
Website: http://github.com/andykant/active-database
License: MIT-style license
Version: 1.0.0.20
--------------------------------
Credits:
- ADb.$type is based on $type from mootools.js
<http://mootools.net> (c) Valerio Proietti, MIT-style license.
- ADb.$xfn is equivalent to $xfn from xfn.js
<http://github.com/andykant/extended-function-factory> (c) Andy Kant,
MIT-style license.
--------------------------------
About:
- ADb is a relational database system implemented in JavaScript.
- ADb's implementation is based on the ActiveRecord design pattern.
*/
// Create ADb class.
var ADb = function(tables) {
// Alias for creating a new database.
return new ADb.Database(tables);
};
/*
Static Methods:
$array - Create a copy of an array.
$bind - Binds an object's context to the 'this' pointer in a function.
$each - Iterate through each object in an array.
$error - Generates a database error.
$export - Serializes an object into a string.
$extend - Extend an object's properties.
$generator - Default value function generator.
$import - Imports a serialized string into an object.
$index - Returns the index of an object in an array.
$init - Lists all names in an array as a string of variable initialization directives.
$test - Tests a datatype to ensure that it is acceptable for database storage.
$type - Finds the type of an object.
$validate - Validates an object as being of the specified type.
Static Factories:
$ext - Initializes a new extension cache.
$observer - Implements an observer pattern, used for event listening.
$ref - A placeholder data reference used to reference a foreign key before it might be created.
$xfn - Converts a function to an extended function.
Static Properties:
$debug - (boolean) Whether or not debug mode is enabled (defaults to 'false').
$extensions - (object) A hashtable for extensions to cache data.
$version - (string) The current version of the library.
*/
ADb.$debug = false;
ADb.$version = '1.0.0.20';
ADb.$extensions = {};
/*
Static Method: $array
Create a copy of an array.
Arguments:
arr - (array) Array to copy.
Returns:
(array) - Copied array object.
Usage:
ADb.$each(ADb.$array(arguments), function(obj, i) {
some_arr[i] = obj;
});
*/
ADb.$array = function(arr) {
var tmp = [];
for (var i = 0; i < arr.length; i++)
tmp.push(arr[i]);
return tmp;
};
/*
Static Method: $bind
Binds an object's context to the 'this' pointer in a function.
Arguments:
fn - (function) The function to alter.
ctx - (object) The context to bind.
Returns:
(function) - The new bound function.
Usage:
var fn = ADb.$bind(function(arg1, arg2) {
this.property = arg1 + arg2;
}, this);
*/
ADb.$bind = function(fn, ctx) {
return function(){
return fn.apply(ctx, arguments);
};
};
/*
Static Method: $each
Iterate through each object in an array.
Arguments:
obj - (array/object) Object to iterate through.
fn - (function) Function to execute for each iteration.
Will be passed object and iterator values.
ctx - <OPTIONAL> (object) Context to run function with.
Usage:
- General use.
ADb.$each(arguments, function(arg, i) {
some_arr[i] = arg;
}, this);
- Iterating over an array.
ADb.$each(arr, function(some_obj, idx) {
alert(idx + ': ' + some_obj);
}, this);
- Iterating over an object.
ADb.$each(obj, function(some_obj, hash) {
alert(hash + ': ' + some_obj);
}, this);
- Iterating over an unknown object type.
ADb.$each(obj, function(some_obj) {
alert(some_obj);
}, this);
*/
ADb.$each = function(obj, fn, ctx) {
ctx = ctx || null;
if (ADb.$type(obj) == 'array') {
for (var i = 0; i < obj.length; i++) {
var result = fn.call(ctx, obj[i], i);
if (ADb.$type(result)) return result;
}
} else if (ADb.$type(obj) == 'object') {
for (var i in obj) {
var result = fn.call(ctx, obj[i], i);
if (ADb.$type(result)) return result;
}
} else if (ADb.$type(obj)) {
var result = fn.call(ctx, obj, null);
if (ADb.$type(result)) return result;
}
};
/*
Static Method: $error
Generates a database error.
Arguments:
message - (string) The message to append to the error string.
Usage:
ADb.$error('Invalid datatype.');
*/
ADb.$error = function(message) {
if (ADb.$debug) {
if (typeof console != 'undefined')
console.error('ADb Error: ' + message);
else
throw(new Error('ADb Error: ' + message));
}
};
/*
Static Method: $export
Serializes an object into a string.
Arguments:
obj - (object) The object to serialize.
force - <OPTIONAL> (boolean) Forces the object to serialize via the 'toString' object method.
Returns:
(string) - If an object is serializable, defined as it would be evaluated to a JavaScript object.
'null' - (string) If an object isn't serializable.
Usage:
var date_obj = new Date();
var date_string = ADb.$export(date_obj);
if (date_obj == ADb.$import(date_string)) {
...
}
*/
ADb.$export = function(obj, force) {
var type = ADb.$type(obj);
force = force || false;
if (force || type.match(/^(auto|regexp|boolean|number)$/)) return obj.toString();
else if (type == 'date') return "new Date('" + obj.toString() + "')";
else if (type == 'string') return "'" + obj + "'";
else if (type == 'array') {
var arr_str = [];
arr_str.push('[');
for (var i = 0; i < obj.length; i++) {
if (i > 0)
arr_str.push(',');
arr_str.push(ADb.$export(obj[i]));
}
arr_str.push(']');
return arr_str.join('');
} else if (type == 'object') {
var obj_str = [];
obj_str.push('{');
var first = true;
for (var i in obj) {
if (!first)
obj_str.push(',');
obj_str.push("'" + i + "':" + ADb.$export(obj[i]));
if (first)
first = false;
}
obj_str.push('}');
return obj_str.join('');
} else {
return 'null';
}
};
/*
Static Method: $extend
Extend an object's properties.
Arguments:
base - (object) Object to overwrite properties of.
extender - (object) Object whose properties should be used to overwrite.
xfn - <OPTIONAL> (boolean) Whether to convert functions to extended functions.
Usage:
var options = {
name: 'options',
value: 37
};
ADb.$extend(options, {name: 'error', message: 'failure'});
// options = {name: 'error', message: 'failure', value: 37};
*/
ADb.$extend = function(base, extender, xfn) {
xfn = xfn || false;
for (name in extender) {
if (xfn && ADb.$validate('function', extender[name]))
base[name] = ADb.$xfn(extender[name]);
else
base[name] = extender[name];
}
};
/*
Static Method: $generator
Default value function generator.
Arguments:
type - (string) The datatype to produce a generator for.
Returns:
(function) - Generator for the object type.
Generators:
'auto' - Returns -1 (number).
'function' - Returns an empty function.
'textnode' - Returns an empty textnode.
'element' - Returns an empty 'div' element.
'date' - Returns the current date/time.
'array' - Returns an empty array.
'regexp' - Returns a wildcard regular expression.
'object' - Returns an empty object.
'string' - Returns an empty string.
'boolean' - Returns false.
'number' - Returns 0.
Usage:
var default_string = ADb.$generator('string')();
var default_number = ADb.$generator('number')();
var default_date = ADb.$generator('date')();
*/
ADb.$generator = function(type) {
if (type == 'auto') return function(){return -1;};
else if (type == 'function') return function(){return function(){};};
else if (type == 'textnode') return function(){return document.createTextNode('');};
else if (type == 'element') return function(){return document.createElement('div');};
else if (type == 'date') return function(){return new Date();};
else if (type == 'array') return function(){return [];};
else if (type == 'regexp') return function(){return /^.*$/;};
else if (type == 'object') return function(){return {};};
else if (type == 'string') return function(){return '';};
else if (type == 'boolean') return function(){return false;};
else if (type == 'number') return function(){return 0;};
else return function(){return null;};
};
/*
Static Method: $import
Imports a serialized string into an object.
Arguments:
data - (string) The string to evaluate into an object.
Returns:
(object) - If a string is deserializable.
(null) - If a string isn't deserializable.
Usage:
var date_obj = new Date();
var date_string = ADb.$export(date_obj);
if (date_obj == ADb.$import(date_string)) {
...
}
*/
ADb.$import = function(data) {
return eval('(' + data + ')');
};
/*
Static Method: $index
Returns the index of an object in an array.
Arguments:
arr - (array) Array to iterate.
obj - (object) Object to look for.
Returns:
(number) - Index in the array.
-1 - (number) If the object does not exist in the array.
Usage:
var idx = ADb.$index('red');
*/
ADb.$index = function(arr, obj) {
if (ADb.$validate('function', arr.indexOf)) {
return arr.indexOf(obj);
} else {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == obj)
return i;
}
return -1;
}
};
/*
Static Method: $init
Lists all names in an array as a string of variable initialization directives.
Arguments:
vars - (array[string]) Array of private variable names to evaluate.
Returns:
(string) - String to be evaluated to define environment methods.
Usage:
eval(ADb.$init(this.$expose('__')));
*/
ADb.$init = function(vars) {
vars = vars || [];
var init = [];
for (var i = 0; i < vars.length; i++)
init.push("var " + vars[i] + " = this.$expose('" + vars[i] + "');");
return init.join('');
};
/*
Static Method: $test
Tests a datatype to ensure that it is acceptable for database storage.
Arguments:
type - (string) The datatype to test.
isKey - <OPTIONAL> (boolean) Whether the datatype is being used for a key.
Returns:
true - (boolean) If the datatype is valid.
false - (boolean) If the datatype is invalid.
Usage:
- Test for a valid datatype:
if (ADb.$test('number')) {
...
}
- Test for a valid datatype for a key:
if (ADb.$test('string', true) {
...
}
*/
ADb.$test = function(type, isKey) {
if (isKey)
return /^(auto|string|number)$/.test(type);
else
return /^(auto|function|textnode|element|date|array|regexp|object|string|boolean|number)$/.test(type);
};
/*
Static Method: $type
Finds the type of an object.
Based on $type in mootools.js <http://mootools.net> (c) Valerio Proietti, MIT-style license.
Arguments:
obj - (object) The object to find the type of.
Returns:
'function' - (string) If obj is a function.
'textnode' - (string) If obj is a node but not an element.
'element' - (string) If obj is a DOM element.
'date' - (string) If obj is a date.
'array' - (string) If obj is an array.
'regexp' - (string) If obj is a regular expression.
'object' - (string) If obj is an object.
'string' - (string) If obj is a string.
'number' - (string) If obj is a number.
'boolean' - (string) If obj is a boolean.
'adb.database' - (string) If obj is an ADb.Database.
'adb.table' - (string) If obj is an ADb.Table.
'adb.column' - (string) If obj is an ADb.Column.
'adb.row' - (string) If obj is an ADb.Row.
'adb.ref' - (string) If obj is an ADb.$ref.
'adb.observer' - (string) If obj is an ADb.$observer.
false - (boolean) If the object is not defined or none of the above, or if it's an empty string.
Usage:
- Test for an object's existence:
if (ADb.$type(obj)) {
...
}
- Test for an object's type:
if (ADb.$type(obj) == 'string') {
...
}
*/
ADb.$type = function(obj) {
var type = false;
if (arguments.length == 0 || typeof obj == 'undefined' || obj == null) type = false;
else if (obj instanceof Function) type = 'function';
else if (obj.nodeName) {
if (obj.nodeType == 3 && !/\S/.test(obj.nodeValue)) type = 'textnode';
else if (obj.nodeType == 1) type = 'element';
}
else if (obj instanceof Date) type = 'date';
else if (obj instanceof Array) type = 'array';
else if (obj instanceof RegExp) type = 'regexp';
else if (obj instanceof ADb.Database) type = 'adb.database';
else if (obj instanceof ADb.Table) type = 'adb.table';
else if (obj instanceof ADb.Column) type = 'adb.column';
else if (obj instanceof ADb.Row) type = 'adb.row';
else if (obj instanceof ADb.$ref) type = 'adb.ref';
else if (obj instanceof ADb.$observer) type = 'adb.observer';
else if (typeof obj == 'object') type = 'object';
else if (typeof obj == 'string') type = 'string';
else if (typeof obj == 'boolean') type = 'boolean';
else if (typeof obj == 'number' && isFinite(obj)) type = 'number';
return type;
};
/*
Static Method: $validate
Validates an object as being of the specified type.
Arguments:
type - (string) The type to validate against.
obj - (object) The object to validate against the type.
Returns:
true - (boolean) If the object is of the specified type.
false - (boolean) If the object isn't of the specified type.
Usage:
- General use.
if (ADb.$validate('string', obj)) {
some_arr.push(obj);
}
*/
ADb.$validate = function(type, obj) {
type = type == 'auto' ? 'number' : type;
return (ADb.$type(obj) && type == ADb.$type(obj)) ? true : false;
};
/*
Static Factory: ADb.$ext
Initializes a new extension cache.
Arguments:
name - (string) The name of the extension.
version - <OPTIONAL> (string/number) The version of the extension.
Public Properties:
$name - (string) The name of the extension.
$version - (string) The version of the extension.
*/
ADb.$ext = function(name, version) {
ADb.$extensions[name] = {
$name: name,
$version: ADb.$export(version) || ''
};
return true;
};
/*
Static Factory: ADb.$observer
Implements an observer pattern, used for event listening.
Returns:
(adb.observer) - An initialized observer.
Public Methods:
publish - Publish data to the subscribers of the observer.
subscribe - Subscribe a function to the observer.
unsubscribe - Unsubscribe a function from the observer.
Usage:
var obs = new ADb.$observer();
*/
ADb.$observer = function() {
/*
Private Properties:
_subscribers - Internal storage container for subscribers of the observer.
*/
var _subscribers = [];
/*
Public Method: publish
Publish data to the subscribers of the observer.
Arguments:
data - The data that will be published.
Usage:
obs.publish('some type of object');
*/
this.publish = function(data) {
for (var i = 0; i < _subscribers.length; i++)
_subscribers[i](data);
};
/*
Public Method: subscribe
Subscribe a function to the observer.
Arguments:
fn - Function that will be passed data as it is published.
Usage:
var fn = function(data) {
alert(data);
};
obs.subscribe(fn);
*/
this.subscribe = function(fn) {
for (var i = 0; i < _subscribers.length; i++) {
if (_subscribers[i] == fn)
return;
}
_subscribers.push(fn);
};
/*
Public Method: unsubscribe
Unsubscribe a function from the observer.
Arguments:
fn - Function that will be unsubscribed.
Usage:
var fn = function(data) {
alert(data);
};
obs.subscribe(fn);
obs.unsubscribe(fn);
*/
this.unsubscribe = function(fn) {
for (var i = 0; i < _subscribers.length; i++) {
if (_subscribers[i] == fn)
_subscribers[i].splice(i,1);
}
};
// Bind and extend all private/$column methods.
ADb.$each(['this.publish','this.subscribe','this.unsubscribe'], function(varname) {
if (ADb.$validate('function', eval('(' + varname + ')')))
eval(varname + ' = ADb.$xfn(ADb.$bind(' + varname + ', this));');
}, this);
};
/*
Static Factory: ADb.$ref
A placeholder data reference used to reference a foreign key before it might be created.
The referenced value that will be returned is the primary key value of the first matched row.
This is primarily used when defining tables and their data in bulk.
Arguments:
table - (string) Table to reference.
column - (string) Column to reference.
value - (object) Value to reference.
Returns:
(adb.ref) - An initialized reference.
Public Properties:
table - (string) The name of the table to reference.
column - (string) The name of the column to reference.
value - (object) The value to reference.
Usage:
db.fruits.$add([null, 'apple', new Date('11/17/2006'), 'juicy', new ADb.$ref('colors', 'name', 'red')]);
*/
ADb.$ref = function(table, column, value) {
this.table = table;
this.column = column;
this.value = value;
};
/*
Extended Function Factory rev.3
Equivalent on $xfn in xfn.js <http://github.com/andykant/extended-function-factory>
(c) Andy Kant, MIT-style license.
Static Factory: $xfn
Converts a function to an extended function.
Allows preprocessor/postprocessor functions to be added to a function in order to increase its abilities.
Arguments:
fn - (function) The function to extend.
Returns:
(function) - An extended function object.
Public Methods:
$xfn.extend - Converts every function property in an object to an extended function.
<CALL> - Calls processors before/after calling the original function.
pre.add - (function fn, <OPTIONAL> number priority) Add a preprocessor.
pre.remove - (function fn) Remove a preprocessor.
post.add - (function fn, <OPTIONAL> number priority) Add a postprocessor.
post.remove - (function fn) Remove a postprocessor.
*/
ADb.$xfn = function(fn) {
if (typeof fn != 'function') {
return fn;
}
// Define functionality.
var _pre = [];
var _post = [];
var _search = function(left, right, priority, proc) {
if (right < left) {
return left;
}
var index = Math.floor((left + right) / 2);
if (priority < proc[index][1]) {
return _search(index + 1, right, priority, proc);
} else if (priority > proc[index][1]) {
return _search(left, index - 1, priority, proc);
} else {
while (index < proc.length && priority == proc[index][1]) {
index++;
};
return index;
}
};
var _add = function(proc) {
return function(fn, priority) {
priority = priority || 0;
var idx = _search(0, proc.length - 1, priority, proc);
for (var i = proc.length; i > idx; i--) {
proc[i] = proc[i-1];
}
proc[idx] = [fn, priority];
};
};
var _remove = function(proc) {
return function(fn) {
for (var i = 0; i < proc.length; i++) {
if (proc[i][0] == fn) {
proc.splice(i,1);
}
}
};
};
// Return extended function.
var func = function() {
for (var i = 0; i < _pre.length; i++) {
arguments = _pre[i][0].apply(this, arguments);
if (typeof arguments == 'undefined') return undefined;
}
var result = fn.apply(this, arguments);
for (var i = 0; i < _post.length; i++) {
result = _post[i][0].call(this, result);
if (typeof result == 'undefined') return undefined;
}
return result;
};
func.pre = {
add: _add(_pre),
remove: _remove(_pre)
};
func.post = {
add: _add(_post),
remove: _remove(_post)
};
return func;
};
// Extend an entire object.
ADb.$xfn.extend = function(obj) {
for (var prop in obj) {
if (typeof obj[prop] == 'function') {
obj[prop] = ADb.$xfn(obj[prop]);
}
}
};
// Set the revision number.
ADb.$xfn.revision = 3;
// Extend all ADb static methods (except for $xfn).
for (var name in ADb) {
if (typeof ADb[name] == 'function' && name != '$xfn' && name.match(/^\$/))
ADb[name] = ADb.$xfn(ADb[name]);
}
/*
Class: ADb.Database
ActiveRecord-based JavaScript database system.
--------------------------------
Arguments:
tables - (object) An object including one or more table declarations, hashed by table name.
Returns:
(adb.database) - An initialized database.
--------------------------------
Public Methods:
$create - Create one or more tables in the database.
$delete - <DESTRUCTIVE> Deletes a table from the database.
$export - Serializes the database into a string.
$tables - Returns a list of table names.
Public Observers:
$events.create - Event fired upon table creation. Subscribers passed table name.
$events.delete - Event fired upon table deletion. Subscribers passed table name.
Public Properties:
<DYNAMIC> - A public property will provided for each table in the database.
The properties will be named according to the table name (db.fruits for the 'fruits' table).
--------------------------------
Usage:
- Initialize an empty database:
var db = new ADb.Database();
- Initialize an empty database using the ADb alias (equivalent to calling ADb.Database):
var db = new ADb();
- Initialize database with one or more tables:
var db = new ADb({
'colors': {
'columns': [
{'name': 'id', 'type': 'auto', 'pk': true},
{'name': 'name', 'type': 'string', 'generator': function(){return 'n/a';} }
],
'rows': [
{'name': 'red'},
[null, 'orange'],
[null, 'yellow']
]
},
'fruits': {
'columns': [
{'name': 'name', 'type': 'string', 'pk': true},
{'name': 'created', 'type': 'date'},
{'name': 'description', 'type': 'string', generator: function(){return 'nothing!';} },
{'name': 'color', 'fk': 'colors'}
],
'rows': [
['apple', new Date('11/13/2006'), 'juicy', new ADb.$ref('colors', 'name', 'red')],
['orange', new Date('11/14/2006'), 'sour', new ADb.$ref('colors', 'name', 'orange')],
['pear', new Date('11/15/2006'), 'moist', new ADb.$ref('colors', 'name', 'yellow')],
['strawberry', new Date('11/15/2006'), 'sweet', new ADb.$ref('colors', 'name', 'red')]
]
}
});
*/
ADb.Database = ADb.$xfn(function(tables) {
/*
Event Observers:
$events - Event observer container.
create - Event fired upon table creation. Subscribers passed table name.
delete - Event fired upon table deletion. Subscribers passed table name.
Usage:
db.$events['delete'].subscribe(function(name) {
alert(name + ' was deleted.');
});
*/
this.$events = {
'create': new ADb.$observer(),
'delete': new ADb.$observer()
};
// Initialization.
if (tables || false) {
for (var name in tables)
this.$create(name, tables[name]);
}
});
// Extend ADb.Database.
ADb.$extend(ADb.Database.prototype, {
/*
Public Method: $create
Creates a table in the database.
Arguments:
name - (string) The name of the table.
table - (object) The table declaration.
Returns:
true - If successful.
false - If unsuccessful.
Usage:
db.$create('colors', {
'columns': [
{'name': 'id', 'type': 'auto', 'pk': true},
{'name': 'name', 'type': 'string', 'generator': function(){return 'n/a';} }
],
'rows': [
{'name': 'red'},
[null, 'orange'],
[null, 'yellow']
]
});
*/
$create: function(name, table) {
var tbl = new ADb.Table(name, table, this);
if (ADb.$validate('adb.table', tbl) && tbl.$name && name == tbl.$name) {
this[name] = tbl;
this.$events['create'].publish(name);
return true;
} else {
return false;
}
},
/*
Public Method: $delete <DESTRUCTIVE>
Deletes a table from the database.
Arguments:
name - (string) The name of the table to delete.
Usage:
db.$delete('fruits');
*/
$delete: function(name) {
var table = this[name];
delete this[name];
this.$events['delete'].publish(name);
},
/*
Public Method: $export
Serializes the database into a string.
Arguments:
force - <OPTIONAL> (boolean) Forces the object to serialize via the 'toString' object method.
Returns:
(string) - A string defined as it would be evaluated to a JavaScript object.
This happens to be the same as a database declaration.
Usage:
var db_string = db.$export();
*/
$export: function(force) {
// Generate the output string.
force = force || false;
var output = [];
output.push('{');
// Append each serialized table.
ADb.$each(this.$tables(), function(name, i) {
if (i) output.push(',');
output.push("'" + name + "':" + this[name].$export(force));
}, this);
output.push('}');
return output.join('');
},
/*
Public Method: $tables
Returns a list of table names.
Returns:
(array[string]) - An array of table names.
Usage:
ADb.$each(db.$tables(), function(name) {
db.$delete(name);
});
*/
$tables: function() {
var names = [];
for (var name in this) {
if (!name.match(/^\$/))
names.push(name);
}
return names;
}
}, true);
/*
Class: Database.Table <INTERNAL>
Specifies an ADb.Database table.
--------------------------------
Arguments:
name - (string) The name for the table.
table - (object) The table declaration.
database - (object) The database that owns the table.
Returns:
(adb.table) - An initialized table.
--------------------------------
Public Methods:
<DYNAMIC> - Find methods will be provided for each column in the table.
The methods will be named according to the column name ('find_by_name' for the 'name' column).
find - (adb.row) Returns corresponding row for the primary key.
find_all - (array[adb.row]) Returns all rows.
find_by_... - (adb.row/array[adb.row]) Returns matching row(s).
$add - Adds one or more rows to the table.
$columns.find - Finds a column based on a name.
$columns.fk - Checks whether a column is a foreign key.
$columns.pk - Checks whether a column is a primary key.
$export - Serializes the table into a string.
$expose - <DESTRUCTIVE> Exposes private objects.
$new - Creates a new row object according to the table's column definitions.
Public Observers:
$events.create - Event fired upon row creation. Subscribers passed ADb.Row.
$events.delete - Event fired upon row deletion. Subscribers passed ADb.Row.
$events.save - Event fired upon row save. Subscribers passed ADb.Row.
Public Properties:
$columns - An array of all column definitions.
$database - Reference to the database object.
$fk - A hashtable of columns and the foreign key tables that they are linked to.
$name - The name of the table.
$pk - The name of the primary key column (if there is one).
--------------------------------
Usage:
var table = new ADb.Database.Table('colors', {
'columns': [
{'name': 'id', 'type': 'auto', 'pk': true},
{'name': 'name', 'type': 'string', 'generator': function(){return 'n/a';} }
],
'rows': [
{'name': 'red'},
[null, 'orange'],
[null, 'yellow']
]
}, db);
*/
ADb.Table = ADb.$xfn(function(name, table, database) {
/*
Private Properties:
__ - An array containing a list of private variables.
_auto - A hashtable containing the current index for auto-incremented columns.
_index - A hashtable containing the array indices of every row hashed by primary key.
_rows - An object containing all data in the table.
*/
var __ = ['_auto','_index','_rows','_addRow','_deleteRow','_findAll',
'_findBy','_findByPK','_rowExists','_saveRow'];
var _auto = {};
var _index = {};
var _rows = [];
/*
Public Properties:
$columns - An array of all column definitions.
$database - Reference to the database object.
$fk - A hashtable of columns and the foreign key tables that they are linked to.
$name - The name of the table.
$pk - The name of the primary key column (if there is one).
*/
this.$columns = [];
this.$database = database || false;
this.$fk = {};
this.$name = name || '';
this.$pk = false;
/*
Event Observers:
$events - Event observer container.
create - Event fired upon row creation. Subscribers passed ADb.Row.
delete - Event fired upon row deletion. Subscribers passed ADb.Row.
save - Event fired upon row save. Subscribers passed ADb.Row.
Usage:
db.colors.$events['delete'].subscribe(function(row) {
alert(row.name + ' was deleted from colors.');
});
*/
this.$events = {
'create': new ADb.$observer(),
'delete': new ADb.$observer(),
'save': new ADb.$observer()
};
/*
Private Methods:
_addRow - (adb.row) Adds a row to the table and returns an object containing it.
_deleteRow - (boolean) Deletes the row and returns whether it was successful.
_findAll - (array[adb.row]) A skeleton for public 'find_all' methods that returns all rows.
_findBy - (array[adb.row]/adb.row/false) A skeleton for public 'find_by' methods that returns all
matches on a specific column.
_findByPK - (adb.row) A skeleton for a public 'find' method that returns a row matching a primary key.
_rowExists - (boolean) Checks if a row exists with the specified index.
_saveRow - (boolean) Saves the row and returns true when it finishes.
*/
var _addRow = function(row) {
// Create nulls for missing columns.
ADb.$each(this.$columns, function(col) {
if (!ADb.$type(row[col.name]))
row[col.name] = null;
}, this);
// Generate values where applicable.
for (var col in row) {
var column = this.$columns.find(col);
if (!ADb.$type(row[col])) {
// Generate default value.
if (column.type == 'auto') {
++_auto[col];
if (this.$columns.pk(col)) {
while(ADb.$type(_index[_auto[col]]))
++_auto[col];
}
row[col] = _auto[col];
}
else
row[col] = column.generator();
} else if (ADb.$validate('adb.ref', row[col])) {
// Grab the referenced value.
row[col] = this.$database[row[col].table]['find_by_' + row[col].column](row[col].value, 1)[this.$database[row[col].table].$pk];
}
}
// Finish up.
var index = _rows.push(row) - 1;
if (this.$pk)
_index[_rows[index][this.$pk]] = index;
else
_index[index] = index;
// Return the resulting ADb.Row.
var datarow = new ADb.Row(_rows[index], this, index);
this.$events['create'].publish(datarow);
return datarow;
};
var _deleteRow = function(index) {
// Make sure it exists.
if (_rowExists(index)) {
// Delete the row.
var datarow = new ADb.Row(_rows[index], this, -1);
if (this.$pk)
delete _index[_rows[index][this.$pk]];
delete _rows[index];
this.$events['delete'].publish(datarow);
return true;
} else {
return false;
}
};
var _findAll = function() {
var matches = [];
ADb.$each(_rows, function(row, index) {
if (row)
matches.push(new ADb.Row(row, this, index));
}, this);
return matches;
};
var _findBy = function(column, data, limit) {
var matches = [];
limit = limit || 0;
var match = ADb.$each(_rows, function(row, index) {
if (row && row[column] == data) {
if (limit == 1)
return new ADb.Row(row, this, index);
else