node-sqlite3
node-sqlite3 copied to clipboard
Named parameters
trafficstars
I'd like to be able to pass parameters without prefixes :, $, @ in it's keys.
Now this code fails with INSERT SQLITE_RANGE: bind or column index out of range undefined.
I think it should work.
var sqlite3 = require('sqlite3');
var db = new sqlite3.Database(':memory:');
db.get(
'CREATE TABLE test (one INT)',
function (err) {
db.get(
'INSERT INTO test VALUES (:one)', {one: 1},
function clbk (err, row) {
console.log('INSERT', err && err.message, row);
}
);
db.get(
'SELECT * FROM test',
function clbk (err, row) {
console.log('SELECT', err && err.message, row);
}
);
}
);
crickets
This module seems like it can do it. https://github.com/JoshuaWise/better-sqlite3/blob/HEAD/docs/api.md#binding-parameters
Thought JS Proxy would work here, but it doesn't seem like it works with native code.
var handler = {
get: function(obj, prop) {
if (prop.length > 1 && (prop.startsWith('@') || prop.startsWith('$') || prop.startsWith(':'))) {
var newprop = prop.substr(1);
if (obj.hasOwnProperty(newprop)) {
return obj[newprop];
}
}
return obj[prop];
}
};
new Proxy(YourObjectHere, handler)
It's using c module under the hood to handle the object passed into, so proxy will not work here.
FYI, one workaround is to add prefix like $ on your own:
function addPrefix(obj: any) {
return Object.keys(obj).reduce((x, y) => ({ ...x, [`$${y}`]: obj[y] }), {});
}