-
Notifications
You must be signed in to change notification settings - Fork 28
Open
Description
I see there was some discussion of supporting named parameters in grncdr/node-any-db-adapter-spec#7, but it isn't entirely clear to me from the actual package readmes how to go about using them in the usual any-db paradigm of "write SQL here, get parameters from there, pass both to query" unless I'm supposed to build the SQL using the parameters every time with the any-db-parameters helper.
Ideally, what I'd like is to be able to write code like this:
function queryWithNamedParameters(connection, sql, parameters, callback, prefix) { // parameters is an object/hashmap
if (!connection.supportsNamedParameters) { // HYPOTHETICAL: this is what I am looking for
let parser = /([\s\S]*?)('(?:''|[^'])*'|"(?:""|[^"])*"|[[](?:]]|[^\]])*]|\/[*][\s\S]*?[*]\/|--.*?(?:\n|$)|$)/g // breaks SQL up into comments/strings and non-comment/string segments so we can replace variables only outside comments/strings
let sqlTransformed = ""
let parametersTransformed = []
for (let match = parser.exec(sql); match[0] != ""; match = parser.exec(sql)) {
const parameter = new RegExp(escapeRegExp(prefix || "$") + "([a-zA-Z]+)")
while (parameter.test(match[1])) {
parametersTransformed.push(parameters[parameter.exec(match[1])[1]])
match[1] = match[1].replace(parameter, "?")
}
sqlTransformed += match[1] + match[2]
}
sql = sqlTransformed
parameters = parametersTransformed
}
return connection.query(sql, parameters, callback)
}...Which, in case it isn't clear, would basically turn named parameters into positional ones (assuming I've written it right), but only if the specific database doesn't already support positional parameters (in which case they would be used against the database directly).
Metadata
Metadata
Assignees
Labels
No labels