Last active
March 19, 2022 02:34
-
-
Save rednebmas/577e600a5e60a5660b3e4c6ff1394576 to your computer and use it in GitHub Desktop.
Replace Postgres SQL params into SQL
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
// 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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://bit.ly/3sZFmEN