-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #5 from brandsExclusive/upsert
Upsert
- Loading branch information
Showing
3 changed files
with
45 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |