Skip to content

Commit

Permalink
Merge pull request #5 from brandsExclusive/upsert
Browse files Browse the repository at this point in the history
Upsert
  • Loading branch information
mastfissh authored Aug 3, 2017
2 parents 5f8fd0f + fdac01f commit ce4d236
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 7 deletions.
15 changes: 8 additions & 7 deletions lib/createGeneric.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ function createGeneric(table, settable_fields, object) {
return "$" + counter;
});

let query = `INSERT INTO ${table} (`
+ set_fields.join(",")
+ ") VALUES ("
+ placeholders
+ ") RETURNING *;";

let query = `
INSERT INTO ${table} (
${set_fields.join(",")}
) VALUES (
${placeholders}
) RETURNING *;
`
return db.getFirstRow(query, values);
}
module.exports = createGeneric;
module.exports = createGeneric;
1 change: 1 addition & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,5 @@ module.exports.getCount = (text, values) => {
};

module.exports.createGeneric = require('./createGeneric');
module.exports.upsert = require('./upsert');
module.exports.queryBuilder = require('./queryBuilder');
36 changes: 36 additions & 0 deletions lib/upsert.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const db = require('./index.js');
module.exports = function (object, table, settable_fields, upsert_index) {
if(!(upsert_index in object)){
throw new Error(upsert_index+" is required for upsert.")
}
let set_fields = settable_fields.filter(function(field){
return Object.keys(object).includes(field);
});

let values = set_fields.map(function(field){
return object[field];
});
let counter = 0;
let placeholders = set_fields.map(function() {
counter = counter + 1;
return "$" + counter;
});

let query = `
INSERT INTO ${table} (
${set_fields.join(",")}
) VALUES (
${placeholders}
)
ON CONFLICT (${upsert_index})
DO
UPDATE SET (
${set_fields.join(",")}
) = (
${placeholders}
)
WHERE ${table}.${upsert_index} = '${object[upsert_index]}'
RETURNING *;
`
return db.getFirstRow(query, values);
}

0 comments on commit ce4d236

Please sign in to comment.