diff --git a/pg/format.js b/pg/format.js index 7905bea..50112ac 100644 --- a/pg/format.js +++ b/pg/format.js @@ -6,6 +6,8 @@ const escape = require('./escape'); * @returns { string } */ module.exports = function(statement, obj){ + obj = JSON.parse(JSON.stringify(obj)); // clone obj to avoid mutations + const array_mode = Array.isArray(obj); if(array_mode && obj.length === 0) throw new Error('array should have at least one element'); @@ -46,4 +48,4 @@ module.exports = function(statement, obj){ values += (values.length > 0 ? ',' : '') + key + '=' + obj[key]; return statement.replace('?', values); } -} \ No newline at end of file +} diff --git a/pg/format.test.js b/pg/format.test.js index a86e2d8..f5ea80b 100644 --- a/pg/format.test.js +++ b/pg/format.test.js @@ -8,4 +8,9 @@ tap.equal(format('INSERT INTO customer ?', { fullname: 'Test', balance: 1 }), `I tap.equal(format('UPDATE customer SET ?', { last_seen: 'NOW()', visits: 3 }), `UPDATE customer SET last_seen=NOW(),visits=3`); tap.equal(format('UPDATE customer SET ?', { fullname: 'Test', '!visits': '(SELECT COUNT(*) FROM customer_visits)' }), `UPDATE customer SET fullname='Test',visits=(SELECT COUNT(*) FROM customer_visits)`); -tap.equal(format('INSERT INTO customer ?', [{ fullname: 'Test', balance: 1 }, { fullname: 'Test 2', balance: 3 }]), `INSERT INTO customer (fullname,balance) VALUES ('Test',1),('Test 2',3)`); \ No newline at end of file +tap.equal(format('INSERT INTO customer ?', [{ fullname: 'Test', balance: 1 }, { fullname: 'Test 2', balance: 3 }]), `INSERT INTO customer (fullname,balance) VALUES ('Test',1),('Test 2',3)`); + +const input = [{a: 1, b: null}]; +const backup = JSON.parse(JSON.stringify(input)); +format('INSERT INTO customer ?', input); +tap.same(input, backup, 'format should not mutate its params');