Skip to content

Instantly share code, notes, and snippets.

@rednebmas
Last active March 19, 2022 02:34
Show Gist options
  • Save rednebmas/577e600a5e60a5660b3e4c6ff1394576 to your computer and use it in GitHub Desktop.
Save rednebmas/577e600a5e60a5660b3e4c6ff1394576 to your computer and use it in GitHub Desktop.
Replace Postgres SQL params into SQL
// https://bit.ly/3sZFmEN
let userInput = `
SELECT "OrgUser"."id" AS "OrgUser_id", "OrgUser"."role" AS "OrgUser_role", "OrgUser"."user_id" AS "OrgUser_user_id", "OrgUser"."org_id" AS "OrgUser_org_id", "OrgUser"."created_at" AS "OrgUser_created_at", "OrgUser"."deleted_at" AS "OrgUser_deleted_at", "OrgUser"."updated_at" AS "OrgUser_updated_at" FROM "org_user" "OrgUser" WHERE "OrgUser"."user_id" = $1 AND "OrgUser"."deleted_at" IS NULL -- PARAMETERS: [7]
`;
let split = userInput.split('-- PARAMETERS: ');
var sql = split[0].trim();
let params = JSON.parse(split[1]);
params.forEach((param: any, i: number) => {
if (Array.isArray(param)) {
sql = sql.replace('$' + (i+1), `'{${param}}'`);
} else {
sql = sql.replace('$' + (i+1), String(param).replace(/"/g, "'"));
}
})
console.log('Parameter replaced query:\n\n' + sql + '\n\n');
@rednebmas
Copy link
Author

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