Skip to content

Instantly share code, notes, and snippets.

@nickav
Last active December 4, 2019 15:50
Show Gist options
  • Save nickav/1203916177ffee2f5169ea8258e60dd2 to your computer and use it in GitHub Desktop.
Save nickav/1203916177ffee2f5169ea8258e60dd2 to your computer and use it in GitHub Desktop.
// Converts SQL query from named parameters :param to [param]
export const sqlParams = (
sql: string,
params: Record<string, any>
): [string, any[]] => {
const matches = sql.split(/([^:]:[A-z]+[A-z0-9])/g);
let i = 0;
const nextParams: any[] = [];
const nextSql = matches.map((str, index) => {
const isParam = index % 2 === 1;
if (!isParam) {
return str;
}
const prefix = str.slice(0, 1);
const paramName = str.slice(2);
const nextToken = `$${++i}`;
const param = params[paramName];
if (!params.hasOwnProperty(paramName)) {
console.warn(`sqlParams - missing parameter: '${paramName}'`);
}
nextParams.push(param);
return prefix + nextToken;
}).join('');
return [nextSql, nextParams];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment