Skip to content

Instantly share code, notes, and snippets.

@jeremybradbury
Created April 17, 2021 01:59
Show Gist options
  • Save jeremybradbury/d5d03cb39b8032a8ec0e63cd77a5690e to your computer and use it in GitHub Desktop.
Save jeremybradbury/d5d03cb39b8032a8ec0e63cd77a5690e to your computer and use it in GitHub Desktop.
nodejs pg helper - upsertRow
// you'll likely want the pool creation in another file & imported here instead of a new pool
const pool = new require("pg").Pool(); // left here for completeness
// import { pool } from "../db"
// usage example: `upsertRow("profile", {id:"999", bio: "I like to..." image: "https://..."})`
const upsertRow = async (table, row = {}) => {
try {
const fields = Object.keys(row);
const values = Object.values(row);
let q = `INSERT INTO ${table} (${fields.reduce((x, y) => `"${x}", "${y}"`)})
VALUES(${values.reduce((x, y) => `'${x}', '${y}'`)})
ON CONFLICT ("id") DO UPDATE`;
for (let i = 0; i < fields.length; i++) {
if (fields[i].includes("id")) continue;
q += ` SET ${fields[i]} = EXCLUDED.${fields[i]}`;
}
// console.info("query",q); // uncomment for troubleshooting
({
rows: [row], // extract first row into row variable
} = await pool.query(q));
} catch (err) {
console.error(
`upsertRow(${table},${JSON.stringify(row)})`
);
console.error(err)
return false;
}
return row;
}
@jeremybradbury
Copy link
Author

Just wanted to point out this in an intentional antipattern placed here for a student excercise.

Hopefully it's obvious: don't actually use this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment