diff --git a/lib/createGeneric.js b/lib/createGeneric.js index 6de1309..8a2401e 100644 --- a/lib/createGeneric.js +++ b/lib/createGeneric.js @@ -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; \ No newline at end of file +module.exports = createGeneric; diff --git a/lib/index.js b/lib/index.js index 32e3da4..e05def3 100644 --- a/lib/index.js +++ b/lib/index.js @@ -50,4 +50,5 @@ module.exports.getCount = (text, values) => { }; module.exports.createGeneric = require('./createGeneric'); +module.exports.upsert = require('./upsert'); module.exports.queryBuilder = require('./queryBuilder'); diff --git a/lib/upsert.js b/lib/upsert.js new file mode 100644 index 0000000..2b51601 --- /dev/null +++ b/lib/upsert.js @@ -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); +}