Search code examples
sqlsqliteluasql-injectionescaping

How to quote values for LuaSQL?


LuaSQL, which seems to be the canonical library for most SQL database systems in Lua, doesn't seem to have any facilities for quoting/escaping values in queries. I'm writing an application that uses SQLite as a backend, and I'd love to use an interface like the one specified by Python's DB-API:

c.execute('select * from stocks where symbol=?', t)

but I'd even settle for something even dumber, like:

conn:execute("select * from stocks where symbol=" + luasql.sqlite.quote(t))

Are there any other Lua libraries that support quoting for SQLite? (LuaSQLite3 doesn't seem to.) Or am I missing something about LuaSQL? I'm worried about rolling my own solution (with regexes or something) and getting it wrong. Should I just write a wrapper for sqlite3_snprintf?


Solution

  • I haven't looked at LuaSQL in a while but last time I checked it didn't support it. I use Lua-Sqlite3.

    require("sqlite3")
    
    db = sqlite3.open_memory()
    
    db:exec[[ CREATE TABLE tbl( first_name TEXT, last_name TEXT ); ]]
    
    stmt = db:prepare[[ INSERT INTO tbl(first_name, last_name) VALUES(:first_name, :last_name) ]]
    
    stmt:bind({first_name="hawkeye", last_name="pierce"}):exec()
    stmt:bind({first_name="henry", last_name="blake"}):exec()
    
    for r in db:rows("SELECT * FROM tbl") do
        print(r.first_name,r.last_name)
    end