forked from paytm/node-sql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert.js
More file actions
70 lines (63 loc) · 1.82 KB
/
insert.js
File metadata and controls
70 lines (63 loc) · 1.82 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
'use strict';
var DefaultNode = require('./default');
var Node = require('./');
var ParameterNode = require('./parameter');
var Insert = Node.define({
type: 'INSERT',
constructor: function () {
Node.call(this);
this.names = [];
this.columns = [];
this.valueSets = [];
}
});
module.exports = Insert;
Insert.prototype.add = function (nodes) {
var hasColumns = false;
var hasValues = false;
var self = this;
var values = {};
nodes.forEach(function (node) {
var column = node.toNode();
var name = column.name;
var idx = self.names.indexOf(name);
if (idx < 0) {
self.names.push(name);
self.columns.push(column);
}
hasColumns = true;
hasValues = hasValues || column.value !== undefined;
values[name] = column;
});
// When none of the columns have a value, it's ambiguous whether the user
// intends to insert a row of default values or append a SELECT statement
// later. Resolve the ambiguity by assuming that if no columns are specified
// it is a row of default values, otherwise a SELECT will be added.
if (hasValues || !hasColumns) {
this.valueSets.push(values);
}
return self;
};
/*
* Get parameters for all values to be inserted. This function
* handles handles bulk inserts, where keys may be present
* in some objects and not others. When keys are not present,
* the insert should refer to the column value as DEFAULT.
*/
Insert.prototype.getParameters = function () {
var self = this;
return this.valueSets
.map(function (nodeDict) {
var set = [];
self.names.forEach(function (name) {
var node = nodeDict[name];
if (node) {
set.push(ParameterNode.getNodeOrParameterNode(node.value));
}
else {
set.push(new DefaultNode());
}
});
return set;
});
};