richtaur / jsql

JavaScript Query Language

This URL has Read+Write access

Matt Hackett (author)
Sun Mar 22 23:00:49 -0700 2009
commit  ff68bbc4b5e2fa944d83e55c0f3052aedcaf7d8b
tree    f63f382ce0ee42386a9ef155f05c89fe3c71803f
parent  9eda058954f2410cca49d0766b471889b67d2eae
jsql / jsql.js
100755 576 lines (417 sloc) 11.044 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/**
* JavaScript Query Language v0.1
* Provides a query layer for interacting with the DOM
* Matt Hackett 2009 scriptnode.com
*/
JSQL = (function() {
 
// Constants (sort of)
var BODIES = ['body', 'document', 'document.body'],
CONDITIONAL_EQUALS = 1,
CONDITIONAL_NOT_EQUAL = 2;
 
// debug gets called but does nothing by default. Set with setDebug()
var debug = function() {};
 
/**
* Does a very basic check to see if a value is in an array (cannot use indexOf; not cross-browser yet)
* @param {Array} arr The array to look in
* @param {Mixed} val The value to check
* @return {Mixed} The index of the value or -1 on failure
* @member JSQL
* @private
*/
var inArray = function(arr, val) {
 
var i,
len = arr.length;
 
for (i = 0; i < len; i++) {
if (arr[i] === val) {
return i;
}
}
 
return -1;
 
};
 
/**
* Executes a JSQL query
* @param {String} qry The query to execute
* @return {Object} An object with two keys (error is true or false) which changes based on request type.
* Returns either the affected elements (count for UPDATE), number of affected elements (count for DELETE), or the requested elements themselves (elements, an array, for SELECT)
* @member JSQL
* @public
*/
var query = function(qry) {
 
var index = 0,
operation = {
parsedTargets : [],
targets : {},
type : '',
values : [],
where : []
},
query,
result = {
each : function(fn) {
 
for (var i = 0; i < this.elements.length; i++) {
fn.call(this.elements[i]);
}
 
return this;
 
},
error : false
};
 
/**
* Executes a DELETE query -- removes selected nodes from the DOM
* @private
*/
var execDelete = function() {
 
var c, el,
len = operation.parsedTargets.length;
 
result.count = 0;
result.elements = [];
 
for (c = 0; c < len; c++) {
 
el = operation.parsedTargets[c];
 
if (el && el.parentNode) {
el.parentNode.removeChild(el);
result.count++;
result.elements.push(el);
}
 
}
};
 
/**
* Executes the query based on the operation object
* @private
*/
var execQuery = function() {
 
if (result.error) {
return;
}
 
if (operation.type == 'DELETE') {
execDelete();
} else if (operation.type == 'SELECT') {
execSelect();
} else if (operation.type == 'UPDATE') {
execUpdate();
}
 
};
 
/**
* Executes a SELECT query -- returns selected nodes
* @private
*/
var execSelect = function() {
 
var c, el,
len = operation.parsedTargets.length;
 
result.count = 0;
result.elements = [];
 
for (c = 0; c < len; c++) {
 
el = operation.parsedTargets[c];
 
if (el) {
result.elements.push(el);
}
 
}
 
result.count = result.elements.length;
 
};
 
/**
* Executes an UPDATE query -- alters selected nodes
* @private
*/
var execUpdate = function() {
 
var c, el, i,
len = operation.parsedTargets.length;
 
result.count = 0;
result.elements = [];
 
for (c = 0; c < len; c++) {
 
el = operation.parsedTargets[c];
 
for (i = 0; i < operation.values.length; i++) {
if (el) {
 
var val = operation.values[i],
dots = val.key.split('.');
 
// (Half-assed) support for style., parentNode., etc attributes
if (dots.length == 2) {
debug('Setting "' + val.key + '" to "' + val.value + '"', el);
el[dots[0]][dots[1]] = val.value;
} else {
debug('Setting "' + val.key + '" to "' + val.value + '"', el);
el[val.key] = val.value;
}
 
result.count++;
result.elements.push(el);
 
}
}
 
}
 
};
 
/**
* Format the query into a usable format (array, split properly)
* Stores the value into query for use by other methods
* @param {String} qry The query to format
* @private
*/
var formatQuery = function(qry) {
 
// These split up words for easy parsing
var splits = [
' ',
'=',
','
];
 
var escs = ['"', "'"]; // These encapsulate strings that ignore splits
 
var c, cut,
esc = false,
len = qry.length,
word = '',
words = [];
 
for (var i = 0; i <= len; i++) {
 
c = qry.substr(i, 1);
cut = true;
 
if (esc) {
if (c == esc) {
c = '';
esc = false;
} else {
cut = false;
}
} else if (inArray(escs, c) > -1) {
if (qry.substr(i + 1, 1) == c) {
// We have an empty string '', "" (intentional)
c = false;
cut = true;
word = false;
i++;
words.push('');
} else {
cut = false;
esc = c;
c = '';
}
} else if (inArray(splits, c) > -1) {
if (c == ' ') {
c = false;
}
} else {
cut = false;
}
 
if (c) {
word += c;
}
 
if (cut) {
if (word) {
words.push(word);
}
word = '';
}
 
}
 
query = words;
 
};
 
/**
* Out of the targets in the query, find out which ones match the WHERE clause
*/
var getParsedTargets = function() {
 
if (result.error) {
return;
}
 
var c, el,
els = getTargets(),
len = els.length,
operate, w, where;
 
for (c = 0; c < len; c++) {
 
el = els[c];
operate;
 
if (el) {
 
operate = true;
 
if (operation.where) {
for (w = 0; w < operation.where.length; w++) {
 
where = operation.where[w];
 
if (where.type == CONDITIONAL_EQUALS) {
 
debug('Checking if (' + where.key + ' = "' + where.value + '") => ' + el[where.key], el);
 
if (el[where.key] != where.value) {
operate = false;
break;
}
 
} else if (where.type == CONDITIONAL_NOT_EQUAL) {
if (el[where.key] == where.value) {
operate = false;
break;
}
}
 
}
}
 
if (operate) {
operation.parsedTargets.push(el);
}
 
}
 
}
 
};
 
/**
* Gets the targets and their children
* @return {Array} The array of nodes within the selector
*/
var getTargets = function() {
 
var c, children, cLen,
els = [],
i,
len = operation.targets.length;
 
for (i = 0; i < len; i++) {
 
children = operation.targets[i].getElementsByTagName('*');
cLen = children.length;
 
for (c = 0; c < cLen; c++) {
els.push(children[c]);
}
 
}
 
return els;
 
};
 
/**
* Checks to see if an index exists in query before accessing its value
* @param {Number} sel The index to check
* @return {Mixed} The value of the index or false on failure
* @private
*/
var getWord = function(sel) {
 
if (query[sel]) {
return query[sel];
}
 
return false;
 
};
 
/**
* Parses the query itself, plopping the results into the operation object
* @private
*/
var parseQuery = function() {
 
var type = query[0].toUpperCase();
 
if (type == 'DELETE') {
 
var word = getWord(1);
 
if (word && (word.toUpperCase() == 'FROM')) {
 
operation.targets = parseTargets(2);
operation.where = parseWhere();
 
} else {
 
result.error = 'Syntax error. Expected FROM, got ' + word;
 
return;
 
}
 
} else if (type == 'SELECT') {
 
var word1 = getWord(1),
word2 = getWord(2);
 
if (word1 && (word1 == '*')) {
if (word2 && (word2.toUpperCase() == 'FROM')) {
operation.targets = parseTargets(3);
operation.where = parseWhere();
} else {
result.error = 'Syntax error. Expected FROM, got ' + word;
return;
}
} else {
result.error = 'Syntax error. Expected *, got ' + word;
return;
}
 
 
} else if (type == 'UPDATE') {
 
operation.targets = parseTargets(1);
operation.values = parseValues();
operation.where = parseWhere();
 
debug('Operation: ', operation);
 
} else {
 
result.error = 'Unknown command ' + getWord(0);
return;
 
}
 
operation.type = type;
 
};
 
/**
* Parse the targets out of the query (eg, UPDATE #my-form)
* @param {Number} start The index of the starting point in query
* @return {Object} The captured element
* @private
*/
var parseTargets = function(start) {
 
index = start;
 
var sel = getWord(index),
error = 'Unknown target ' + sel;
 
if (sel) {
 
var c = sel.substr(0, 1);
 
// By id?
if (c == '#') {
 
var el = document.getElementById(sel.substr(1, sel.length));
 
if (el) {
 
index++;
 
return [el];
 
}
 
 
// The entire body?
} else if (inArray(BODIES, sel) > -1) {
 
index++;
 
return [document.body];
 
}
 
}
 
result.error = error;
 
};
 
/**
* Parse the values of the query (eg, SET key = 'value')
* @return {Object} The values in key/value pair
*/
var parseValues = function() {
 
var qry = getWord(index),
values = [];
 
if (qry.toUpperCase() == 'SET') {
 
index++;
 
while ((index < query.length) && query[index].toUpperCase() != 'WHERE') {
 
var
key = query[index++],
eq = query[index++],
value = query[index++];
 
if (eq != '=') {
result.error = 'Expected =, got ' + eq;
return;
}
 
if (value === 'false') {
value = false;
} else if (value === undefined) {
value = '';
}
 
values.push({
key : key,
value : value
});
 
};
 
return values;
 
} else {
result.error = 'Expected SET, got ' + query[index];
}
 
};
 
/**
* Parses the WHERE clause of the query
* @return {Object} The key/value where object
* @private
*/
var parseWhere = function() {
 
if (result.error || !query[index]) {
return [];
}
 
if (query[index].toUpperCase() == 'WHERE') {
 
var where = [];
index++;
 
while ((index < query.length) && (query[index].toUpperCase() != 'LIMIT')) {
 
var key = query[index++],
cond = query[index++],
value = query[index++];
 
if (cond == '=') {
type = CONDITIONAL_EQUALS;
} else if (cond == '!=') {
type = CONDITIONAL_NOT_EQUAL;
} else {
result.error = 'Unknown conditional "' + eq + '"';
return;
}
 
where.push({
key : key,
type : type,
value : value || ''
});
 
};
 
return where;
 
}
 
};
 
formatQuery(qry);
parseQuery();
getParsedTargets();
execQuery();
 
return result;
 
};
 
/**
* Sets the private debug method to something useful
* @param {Function} The function to call to handle debug messages
* @public
*/
query.setDebug = function(fn) {
debug = fn;
};
 
return query;
 
})();