Search code examples
node.jssqlitenode-sqlite3

Bind blob parameter in node-sqlite3


I have an SQLite3 table with BLOB primary key (id):

CREATE TABLE item (
    id BLOB PRIMARY KEY,
    title VARCHAR(100)
);

In javascript models, the primary key (id) is represented as a Javascript string (one HEX byte per character):

var item = { 
    id: "2202D1B511604790922E5A090C81E169",
    title: "foo"
}

When I run the query below, the id parameter gets bound as a string. But I need it to be bound as a BLOB.

db.run('INSERT INTO item (id, title) VALUES ($id, $title)', {
    $id: item.id,
    $title: item.title
});

To illustrate, the above code generates the following SQL:

INSERT INTO item (id, title) VALUES ("2202D1B511604790922E5A090C81E169", "foo");

What I need is this:

INSERT INTO item (id, title) VALUES (X'2202D1B511604790922E5A090C81E169', "foo");

Solution

  • Apparently, the string needs to be converted to a buffer:

    db.run('INSERT INTO item (id, title) VALUES ($id, $title)', {
        $id: Buffer.from(item.id, 'hex'),
        $title: item.title
    });