-
Notifications
You must be signed in to change notification settings - Fork 1
/
LocalStorageDB.js
794 lines (740 loc) · 17.7 KB
/
LocalStorageDB.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
/*------------------------------------------------------------------------------
Function: LocalStorageDB()
Author: Aaron Gustafson (aaron at easy-designs dot net)
Creation Date: 2011-10-03
Version: 0.4
Homepage: http://github.com/easy-designs/LocalStorageDB.js
License: MIT License (see homepage)
------------------------------------------------------------------------------*/
;if ( 'localStorage' in window )
{
/**
* LocalStorageDB()
* a simple cross-browser DB using localStorage
*
* @param str name - the name for your DB
* @return obj - a LocalStorageDB instance
*
*/
function LocalStorageDB( name )
{
this.version = '0.4';
var
UNDEFINED,
TRUE = true,
FALSE = false,
NULL = null,
__cache,
WINDOW = window,
HYPHEN = '-',
PREFIX = 'LocalStorageDB-',
TABLES = '::tables::',
encode = JSON.stringify,
decode = JSON.parse,
// DB innards
DB = {},
AFFECTED_ROWS = 0,
// The RESULT_SET object inherits from Array
RESULT_SET = function(){};
RESULT_SET.prototype = Array.prototype;
RESULT_SET.prototype.ORDER_BY = function( order )
{
var
arr = this,
l, key, sort;
if ( order == 'RANDOM' )
{
arr.sort(function(){
return 0.5 - Math.random();
});
}
else
{
// convert order to an array
order = order.split(',');
l = order.length;
// loop in reverse order (to keep the specificity correct)
while ( l-- )
{
order[l] = order[l].trim().split(' ');
key = order[l][0];
sort = order[l][1];
arr.sort(function(a,b){
var
ret = 0;
// work on copies
a = clone(a);
b = clone(b);
if ( typeof a[key] == 'string' )
{
a = a[key].toLowerCase();
b = b[key].toLowerCase();
if ( sort == 'ASC' )
{
ret = a < b ? -1 : ( a > b ? 1 : 0 );
}
else
{
ret = a < b ? 1 : ( a > b ? -1 : 0 );
}
}
if ( typeof a[key] == 'number' )
{
ret = sort=='DESC' ? b[key] - a[key] : a[key] - b[key];
}
return ret;
});
}
}
return arr;
};
RESULT_SET.prototype.LIMIT = function( start, end )
{
if ( ! end )
{
end = start;
start = 0;
}
return this.splice( start, end );
};
RESULT_SET.prototype.toArray = function()
{
var arr = this;
return Array.prototype.slice.call(arr);
};
// for Firefox when users manually disable localStorage
try {
__cache = WINDOW.localStorage;
} catch (e) {
if ( 'console' in WINDOW )
{
console.log('localStorage is not available',e);
}
// die
return FALSE;
}
/**
* init() -> undefined
* Initializes the DB and loads its contents in to memory
*/
function init()
{
var
tables = readFromCache( TABLES ),
t = tables.length;
if ( t )
{
// store for easier access
DB[TABLES] = tables;
}
else
{
DB[TABLES] = [];
cache( TABLES );
}
// garbage collection
tables = NULL;
}
/**
* tableExists( table ) -> boolean
* Verifies the existence of a table
*
* @param str table - the table
*/
function tableExists( table )
{
if ( TABLES in DB )
{
var
tables = DB[TABLES],
t = tables.length;
while ( t-- )
{
if ( table == tables[t] )
{
return TRUE;
}
}
// garbage collection
tables = t = NULL;
}
return FALSE;
}
/**
* insertData( table, data ) -> undefined
* Inserts data in to the table, ensuring it matches the definition
*
* @param str table - the table
* @param object data - the object to be inserted
*/
function insertData( table, data )
{
var
p = DB[table].dfn,
i = DB[table].index++,
d = {},
k;
for ( k in p )
{
if ( p.hasOwnProperty( k ) )
{
// ids get auto-assigned, otherwise use the supplied data or the prototype fallback
d[k] = ( k == 'id' ) ? i : ( data[k] || p[k] );
}
}
console.log(DB[table]);
var temp=encode(DB[table].keysfun(d));
if (DB[table].keyval[temp]==true) {
throw new Error( 'primary key value already exists' );
}
DB[table].data.push( d );
DB[table].keyval[temp]=true;
AFFECTED_ROWS++;
// garbage collection
d = data = NULL;
}
/**
* findMatches( t, c ) -> array
* Finds items within the table that match the supplied criteria
*
* @param array t - the table
* @param mixed c - the criteria object to be matched or the criteria function
*/
function findMatches( t, c )
{
t = load( t );
var
d = clone( t.data ), // never let a select mutate a row
i = d.length,
a = new RESULT_SET(),
r, p;
if ( c instanceof Function )
{
while ( i-- )
{
r = c( d[i] );
if ( !! r )
{
a.push( d[i] );
}
}
}
else if ( c instanceof Object )
{
rows: while ( i-- )
{
r = d[i];
for ( p in c )
{
if ( c.hasOwnProperty( p ) &&
r[p] != c[p] )
{
continue rows;
}
}
a.push( r );
}
}
else if ( ! c )
{
a = d.reverse();
}
// garbage collection
t = d = c = NULL;
// return
return a.reverse();
}
/**
* withMatches( d, c, f ) -> undefined
* Iterates data and performs a function based on items that match the supplied criteria
*
* @param array d - the data set
* @param object c - the criteria to be matched
* @param function f - the callback to be executed
*/
function withMatches( d, c, f )
{
var
i = d.length,
r, p;
rows: while ( i-- )
{
r = d[i];
for ( p in c )
{
if ( c.hasOwnProperty( p ) &&
r[p] != c[p] )
{
continue rows;
}
}
// trigger the callback, supplying the index
f( i );
}
// garbage collection
d = c = f = i = r = p = NULL;
}
/**
* load( table ) -> boolean
* Loads the supplied table name
*/
function load( table )
{
return readFromCache( table );
}
/**
* cache( table ) -> boolean
* Caches the supplied table name
*/
function cache( table )
{
return writeToCache( table, DB[table] );
}
/**
* clone( obj ) -> object
* Clones a given object
*/
function clone( obj )
{
return decode( encode( obj ) );
}
// ------------------------
// STORAGE MECHANICS
// ------------------------
function readFromCache( table )
{
table = PREFIX + name + HYPHEN + table;
table = __cache.getItem( table );
return !! table ? decode( table ) : [];
}
function writeToCache( table, data )
{
table = PREFIX + name + HYPHEN + table;
try {
__cache.setItem( table, encode( data ) );
} catch (e) {
// Quota was exceeded
if ( 'console' in WINDOW )
{
console.log('Storage quota was exceeded :-(',e);
}
}
return true;
}
function removeFromCache( table )
{
table = table ? PREFIX + name + HYPHEN + table : PREFIX + name;
__cache.removeItem( table );
return true;
}
/**
* LocalStorageDB.AFFECTED_ROWS() -> number
* The number of rows affected by the last operation
*/
this.AFFECTED_ROWS = function()
{
return AFFECTED_ROWS;
};
/**
* LocalStorageDB.SHOW_TABLES() -> array
* Provides an array of table names
*/
this.SHOW_TABLES = function()
{
return DB[TABLES];
};
/**
* LocalStorageDB.CREATE( table, proto, data ) -> boolean
* Creates a new table and (optionally) in serts data into it
*
* Option 1: Create a table
* LocalStorageDB.CREATE( table, proto )
* @param str table - the table name
* @param obj dfn - the data object to use as a definition for all rows
*
* Option 2: Create a table and prefill it with data
* LocalStorageDB.CREATE( table, proto, data )
* @param str table - the table name
* @param obj dfn - the data object to use as a definition for all rows
* @param array data - the data you want to prefill the table with
*/
this.CREATE = function( table, dfn, keys,data)
{
if ( ! dfn ||
tableExists( table ) )
{
throw new Error( table + ' already exists' );
return FALSE;
}
// set up the table
DB[table] = {};
DB[table].data = [];
DB[table].dfn = dfn;
DB[table].index = 1;
DB[table].keysfun = keys;
DB[table].keyval={};
console.log(DB[table].keys);
// cache the table index
DB[TABLES].push( table );
cache( TABLES );
// insert the data (if asked)
if ( data &&
( data instanceof Array ||
data instanceof Object ) )
{
this.INSERT_INTO( table, data );
// caching and garbage collection handled elsewhere
}
else
{
// cache the table
cache( table );
}
// garbage collection
dfn = data = NULL;
return TRUE;
};
/**
* LocalStorageDB.DESCRIBE( table ) -> object
* Returns the definition object
*
* @param str table - the table name
*/
this.DESCRIBE = function( table )
{
if ( tableExists( table ) )
{
return load( table ).dfn;
}
else
{
throw new Error( table + ' is not a valid table name' );
}
};
/**
* LocalStorageDB.TRUNCATE() -> undefined
* Empties a table
*
* @param str table - the table you'd like to empty
*/
this.TRUNCATE = function( table )
{
AFFECTED_ROWS = 0;
if ( !! table )
{
if ( tableExists( table ) )
{
DB[table] = load( table );
AFFECTED_ROWS = DB[table].data.length;
DB[table].index = 0;
DB[table].data = [];
cache( table );
}
else
{
throw new Error( table + ' is not a valid table name' );
}
}
else
{
throw new Error( 'truncate rquires a table name' );
}
};
/**
* LocalStorageDB.DROP( table ) -> undefined
* Drops a table form the DB
*
* @param str table - the table you'd like to drop
*/
this.DROP = function( table )
{
if ( !! table )
{
if ( tableExists( table ) )
{
var
tables = DB[TABLES],
i = tables.length;
while ( i-- )
{
if ( tables[i] == table )
{
DB[TABLES].splice(i,1);
break;
}
}
cache( TABLES );
removeFromCache( table );
// garbage collection
tables = NULL;
}
else
{
console.log('there is not table:'+table);
}
}
else
{
throw new Error( 'DROP rquires a table name' );
}
};
/**
* LocalStorageDB.INSERT( table, data ) -> undefined
* Adds data to the table
*
* Option 1: Add a row
* LocalStorageDB.INSERT( table, data )
* @param str table - the table to use
* @param obj data - the data object to insert
*
* Option 2: Add rows
* LocalStorageDB.INSERT( table, data )
* @param str table - the table to use
* @param array data - an array of data objects to insert
*/
this.INSERT_INTO = function( table, data)
{
AFFECTED_ROWS = 0;
if ( tableExists( table ) )
{
if ( DB[table] == UNDEFINED )
{
DB[table] = load( table );
}
if ( data instanceof Array )
{
for ( var i=0, len = data.length; i < len; i++ )
{
if ( data[i] instanceof Object )
{
insertData( table, data[i] );
}
}
}
else if ( data instanceof Object )
{
insertData( table, data );
}
else
{
throw new Error( 'LocalStorageDB.insert() expects an Object or an array of Objects to be inserted as data' );
}
cache( table );
// garbage collection
data = NULL;
}
else
{
throw new Error( table + ' is not a valid table name' );
}
};
//TODO PRIMARY KEY AND FOREIGN KEY
this.JOIN = function(primary, foreign, primaryKey, foreignKey, select)
{
var m = primary.length, n = foreign.length, index = [], c = [];
for (var i = 0; i < m; i++) { // loop through m items
var row = primary[i];
index[encode(row[primaryKey])] = row; // create an index for primary table
}
for (var j = 0; j < n; j++) { // loop through n items
var y = foreign[j];
var x = index[encode(y[foreignKey])]; // get corresponding row from primary
if (x != null) {
c.push(select(x, y)); // select only the columns you need
}
}
return c;
};
this.CROSS = function(table1, table2, select)
{
var m = table1.length, n = table2.length, index = [], c = [];
for (var i = 0; i < m; i++) { // loop through m items
var row1 = table1[i];
for (var j = 0; j < n; j++) { // loop through n items
var row2 = table2[j];
c.push(select(row1, row2));
}
}
return c;
};
this.INTERSECT = function(table1, table2)
{
var m = table1.length, n = table2.length, index = [], c = [];
for (var i = 0; i < m; i++) { // loop through m items
var row1 = table1[i];
index[JSON.stringify(row1)] = JSON.stringify(row1); // create an index for primary table
}
for (var j = 0; j < n; j++) { // loop through n items
var row2 = table2[j];
if (JSON.stringify(row2) === index[JSON.stringify(row2)]) // get corresponding row from primary
{
c.push(row2);
} // select only the columns you need
}
return c;
};
this.UNION = function(table1, table2)
{
var m = table1.length, n = table2.length, index = [], c = [];
for (var i = 0; i < m; i++) { // loop through m items
var row1 = table1[i];
index[JSON.stringify(row1)] = JSON.stringify(row1); // create an index for primary table
c.push(row1)
}
for (var j = 0; j < n; j++) { // loop through n items
var row2 = table2[j];
if (!(JSON.stringify(row2) === index[JSON.stringify(row2)])) // get corresponding row from primary
{
c.push(row2);
} // select only the columns you need
}
return c;
};
/**
* LocalStorageDB.SELECT( table, criteria ) -> array
* Selects rows from a given table based on the supplied criteria
*
* Option 1: Select the entire DB table
* LocalStorageDB.SELECT( table )
* @param str table - the table to read
*
* Option 2: Select based on criteria object
* LocalStorageDB.SELECT( table, criteria )
* @param str table - the table to read
* @param obj criteria - the criteria to match
*
* Option 3: Select based on criteria function
* LocalStorageDB.SELECT( table, criteria )
* @param str table - the table to read
* @param function criteria - the function to run against each row
*/
this.SELECT = function( table, criteria )
{
if ( tableExists( table ) )
{
return findMatches( table, criteria );
}
else
{
throw new Error( table + ' is not a valid table name' );
}
};
/**
* LocalStorageDB.UPDATE( table, mutation, criteria ) -> undefined
* Updates data in the table
*
* Option 1: Update all rows
* LocalStorageDB.UPDATE( table, mutation )
* @param str table - the table to use
* @param obj mutation - the data object to use for mutating the table
*
* Option 2: Update select rows
* LocalStorageDB.UPDATE( table, mutation, criteria )
* @param str table - the table to use
* @param obj mutation - the data object to use for mutating the table
* @param obj criteria - the criteria to match
*
* Option 3: Custom mutation
* LocalStorageDB.UPDATE( table, mutation )
* @param str table - the table to use
* @param function mutation - a function for use in mutating the table
*/
this.UPDATE = function( table, mutation, criteria )
{
AFFECTED_ROWS = 0;
if ( tableExists( table ) )
{
DB[table] = load( table );
var i = DB[table].data.length,
o_data, n_data, p, changed;
if ( mutation instanceof Function )
{
while ( i-- )
{
changed = FALSE;
o_data = DB[table].data[i];
n_data = mutation( clone( o_data ) ); // clone before mutating
if ( !! n_data )
{
for ( p in o_data )
{
if ( o_data.hasOwnProperty( p ) &&
o_data[p] != n_data[p] )
{
changed = TRUE;
break;
}
}
if ( changed )
{
DB[table].data[i] = n_data;
AFFECTED_ROWS++;
}
}
}
}
else if ( mutation instanceof Object )
{
withMatches( DB[table].data, criteria, function( i ){
var newData = DB[table].data[i];
for ( p in DB[table].dfn )
{
if ( DB[table].dfn.hasOwnProperty( p ) &&
mutation.hasOwnProperty( p ) )
{
newData[p] = mutation[p];
}
}
DB[table].data[i] = newData;
AFFECTED_ROWS++;
// garbage collection
i = newData = NULL;
});
}
else
{
throw new Error( 'LocalStorageDB.UPDATE() expects a mutation object or function as the second argument' );
}
cache( table );
// garbage collection
o_data = n_data = NULL;
}
else
{
throw new Error( table + ' is not a valid table name' );
}
};
/**
* LocalStorageDB.DELETE() -> undefined
* Removes rows matching criteria from table
*
* Option 1: Remove all rows
* LocalStorageDB.DELETE( table )
* @param str table - the table to delete all rows from
*
* Option 2: Remove select rows
* LocalStorageDB.DELETE( table, criteria )
* @param str table - the table to delete rows from
* @param obj criteria - the criteria to match
*/
this.DELETE = function( table, criteria )
{
AFFECTED_ROWS = 0;
if ( criteria == UNDEFINED )
{
return this.truncate( table );
}
else
{
DB[table] = load( table );
withMatches( DB[table].data, criteria, function( i ){
DB[table].data.splice(i,1);
AFFECTED_ROWS++;
});
cache( table );
}
};
// load it up!
init();
}
}