node-sqlite3 icon indicating copy to clipboard operation
node-sqlite3 copied to clipboard

Named parameters

Open maxim-grishaev opened this issue 11 years ago • 3 comments
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);
            }
        );
    }
);

maxim-grishaev avatar Jul 14 '14 12:07 maxim-grishaev

crickets

tomasdev avatar Oct 18 '18 03:10 tomasdev

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)

LiamKarlMitchell avatar Apr 23 '19 04:04 LiamKarlMitchell

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] }), {});
}

wenjoy avatar Apr 16 '24 07:04 wenjoy