forked from brianc/node-sql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwhere.js
More file actions
74 lines (70 loc) · 1.71 KB
/
where.js
File metadata and controls
74 lines (70 loc) · 1.71 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
'use strict';
var Node = require('./index');
var BinaryNode = require('./binary');
var TextNode = require('./text');
var normalizeNode = function(table, node) {
var result = node;
if(typeof node === 'string') {
result = new TextNode('(' + node + ')');
}
else if (Array.isArray(node)) {
result = false;
if (node.length === 0) {
result = new TextNode('(1 = 1)');
} else {
node.forEach(function (subNode) {
if (!result) {
result = subNode;
} else {
result = result.and(subNode);
}
});
}
}
else if (!node.toNode && typeof node === 'object'){
result = false;
for (var colName in node) {
if (node.hasOwnProperty(colName)) {
var column = table.getColumn(colName);
var query = column.equals(node[colName]);
if (!result) {
result = query;
} else {
result = result.and(query);
}
}
}
}
return result;
};
module.exports = Node.define({
constructor: function(table) {
Node.call(this);
this.table = table;
},
type: 'WHERE',
add: function(node) {
node = normalizeNode(this.table, node);
return Node.prototype.add.call(this, node);
},
or: function(other) {
var right = normalizeNode(this.table, other);
// calling 'or' without an initial 'where'
if(!this.nodes.length) {
return this.add(other);
}
return this.nodes.push(new BinaryNode({
left: this.nodes.pop(),
operator: 'OR',
right: right
}));
},
and: function(other) {
var right = normalizeNode(this.table, other);
return this.nodes.push(new BinaryNode({
left: this.nodes.pop(),
operator: 'AND',
right: right
}));
}
});