Dynamic SQL in Lua

From: Marc Balmer <marc(at)msys(dot)ch>
To: Lua mailing list <lua-l(at)lists(dot)lua(dot)org>, pgsql-general(at)postgresql(dot)org
Subject: Dynamic SQL in Lua
Date: 2013-06-15 08:37:50
Message-ID: 51BC27DE.10906@msys.ch
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

The PostgreSQL Lua binding found on https://github.com/mbalmer/luapgsql
has been extended to make it a bit easier to create SQL commands
dynamically and still be able to use execParams().

Imagine a table with user information that contains usernames,
hostnames, locations (e.g. building a user works in) and more data. In
a web application, a HTML form field could be set to a location name or
'all', indicating that we want information for all locations.

The simple approach would then be to create the SQL on the fly and pass
it to the db:exec() function:

sql = {
string.format('select * from userinfo where name = '%s' and host = %s',
name, host }
}

if location ~= 'all' then
sql[#sql + 1] = string.format(' and location = '%s', location)
end

sql = table.concat(sql, '\n')
db:exec(sql)

Constructing SQL this way is bad thing (SQL injection...), so
db:execParams() is what should be used. As it is now possible to pass
tables as parameter values to the db:execParams() function, this can now
be done in a halway sane form by using a table for the parameters and
creating the placeholders ('$1', '$2' etc.) based on the current size of
the parameter array:

p = { 'mbalmer', 'localhost' } -- parameter array

sql = { 'select * from userinfo where name = $1 and host = $2' }

if location ~= 'all' then
p[#p + 1] = location
sql[#sql + 1] = string.format(' and location = $%d', #p)
end

sql = table.concat(sql, '\n')
db:execParams(sql, p)

Browse pgsql-general by date

  From Date Subject
Next Message Yuriy Rusinov 2013-06-15 09:16:38 WIN1251 localization
Previous Message Michael Paquier 2013-06-15 01:46:16 Re: [GENERAL] Can't increase shared_buffers for PostgreSQL on openSUSE 12.3