3

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");
astreltsov
  • 1,943
  • 1
  • 16
  • 22

2 Answers2

2

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
});
0x8BADF00D
  • 7,138
  • 2
  • 41
  • 34
astreltsov
  • 1,943
  • 1
  • 16
  • 22
0

Try casting the string as a blob:

INSERT INTO item(id, title) VALUES(CAST(id_string AS BLOB), 'foo');

Note also that the right way to quote strings in SQL is to use single quotes.

varro
  • 2,382
  • 2
  • 16
  • 24