const {parse} = require("pgsql-ast-parser")
function normalize(query) {
let i = 0;
const byName = {};
const normalized = query.replace(/(?<!:):(\w+)\b/gi, (_, x) => {
if (byName[x]) {
return '#x27; + byName[x];
}
return '#x27; + (byName[x] = ++i)
});
const keys = Object.keys(byName);
function toArgList(args) {
const ret = Array(keys.length);
for (const k of keys) {
ret[byName[k] - 1] = args[k];
}
return ret;
}
return {normalized, toArgList};
}
// transform a named query:
const {normalized, toArgList} = normalize('select * from xxx where id = :id AND other=:other + :id');
console.log(normalized);
console.log(toArgList({id: 'myId', other: 42 }));
// parsable !
parse(normalized)