elixir-sqlite/sqlitex

How do I insert a blob? Is it possible?

tslater opened this issue · 8 comments

I have binary UUIDs that I'm inserting into Sqlite from a JSON string.
Currently I'm binding them after decoding them like so:
Base.decode16!("0000000225313C3467355473F0FF8E2D", case: :mixed)

In another (C-based) application sqlite3_column_type returns SQLITE_TEXT instead of SQLITE_BLOB.

Is there a way to make sure it's inserted as a blob? Note that my column is already defined as a blob type.

I can find in esqlite, a blob test...but I don't understand it:
esqlite3:bind(Statement, [{blob, [<<"eleven">>, 0]}, 12]), % iolist bound as blob with trailing eos.

Ok, i figured it out:
{:blob, Base.decode16!(value, case: :mixed)}

Some kinda awesome magic.

@tslater I had never tried to do this 😊

Glad you figured it out. Can you post a snippet of what that looks like in the sqlitex API?

Here's an example I adapted from one of the test cases:

    {:ok, db} = Sqlitex.open(":memory:")
    :ok = Sqlitex.exec(db, "CREATE TABLE t (a BLOB)")
    [] = Sqlitex.query(db, "INSERT INTO t VALUES (?1)", bind: [ 
        {:blob, Base.decode16!("0000000225313C3467355473F0FF8E2D")} 
    ])
    row = Sqlitex.query(db, "SELECT a FROM t")

I find it interesting that the result has the blob tuple:

[[a: {:blob,
   <<0, 0, 0, 2, 37, 49, 60, 52, 103, 53, 84, 115, 240, 255, 142, 45>>}]]

Everything was working for me before I did the blob tuple and I just inserted the value, the difference was that sqlite didn't know it was a blob and interpreted it as a string in other clients in other programming languages.

BTW, awesome work! I just looked at your profile because it looked familiar and I noticed that we're both in Utah Valley. Is MX using Elixir?

Nothing in production so far at MX. I have a few tools I have written in Elixir and I prototype that I'm hoping to get into production this spring.

That's cool. Do you think they'll eventually make a transition, or would that be crazy talk? I know MX is Ruby crazy... Some people seem to think Elixir is almost a Ruby successor because of Jose and some syntax sharing, but in reality it's so different. I'm just curious to see if any companies will adopt it as their mainstream language.

I don't think we would consider switching away from Ruby overall anytime in the next few years. It works really well for most of what we need, but there are a few things we do where (I think) Elixir would work better.

We have a Rails + Faye server right now that listens to some rabbitmq event and pushes realtime data down some websockets to the users in a live session. That is where I'm hoping to slide in my Elixir prototype because it solves that problem much better than Rails + Faye