Skip to content

Commit d3b43b4

Browse files
committed
support ARRAY[] in INSERT values argument
1 parent 3272f9b commit d3b43b4

File tree

2 files changed

+24
-10
lines changed

2 files changed

+24
-10
lines changed

index.js

+14-10
Original file line numberDiff line numberDiff line change
@@ -124,13 +124,9 @@ function INSERT(table) {
124124

125125
INSERT.prototype = {
126126
VALUES: function(object) {
127-
var values = this.values,
128-
columns = Object.keys(object),
129-
placeholders = columns.map(function(c,i) {
130-
values.push(object[c]);
131-
return '$' + values.length;
132-
});
133-
this.text += '('+columns.join(', ')+') VALUES(' + placeholders.join(', ') + ')';
127+
var columns = Object.keys(object),
128+
insert_values = get_insert_values(object, columns, this.values);
129+
this.text += '('+columns.join(', ')+') VALUES(' + insert_values + ')';
134130
return this;
135131
},
136132
RETURNING: function(returning) {
@@ -169,10 +165,18 @@ DELETE.prototype = {
169165
}
170166
};
171167

172-
function get_set_placeholder(value, values) {
168+
function get_insert_values(object, columns, values) {
169+
return columns.map(function(c,i) {
170+
return get_placeholder(object[c], values);
171+
}).join(', ');
172+
}
173+
174+
175+
// used in get_set_clause and get_insert_values...
176+
function get_placeholder(value, values) {
173177
if (Array.isArray(value)) {
174178
return 'ARRAY[' + value.map(function(item){
175-
return get_set_placeholder(item, values);
179+
return get_placeholder(item, values);
176180
}).join(', ') + ']'
177181
} else {
178182
values.push(value);
@@ -183,7 +187,7 @@ function get_set_placeholder(value, values) {
183187
// only used in UPDATE, but here for clarity/efficiency
184188
function get_set_clause(set, values) {
185189
return Object.keys(set).map(function(c,i){
186-
return c + ' = ' + get_set_placeholder(set[c], values);
190+
return c + ' = ' + get_placeholder(set[c], values);
187191
}).join(', ');
188192
}
189193

test/insert.js

+10
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,14 @@ describe('INSERT', function(){
5858
sql.values.should.eql([null,null,null]);
5959
});
6060
});
61+
describe('#(table).VALUES(set_with_arrays)', function(){
62+
it('should return an object with array placeholders and flattened values', function(){
63+
var sql = INSERT('foo').VALUES({ a: [ 1, 2 ], b: [ [ 3, 4 ], [ 5, 6 ] ], c: [ 7, 8 ] });
64+
sql.should.have.text;
65+
sql.should.have.values;
66+
sql.text.should.equal('INSERT INTO foo(a, b, c) VALUES(ARRAY[$1, $2], ARRAY[ARRAY[$3, $4], ARRAY[$5, $6]], ARRAY[$7, $8])');
67+
sql.values.should.be.an.instanceOf(Array)
68+
sql.values.should.eql([1,2,3,4,5,6,7,8]);
69+
});
70+
});
6171
});

0 commit comments

Comments
 (0)