Search code examples
apachepostgresqlluamod-lua

Can't connect to postgresql from mod_lua


I've downloaded and installed Apache 2.4.4 (which now comes with mod_lua module). Enabled it like so:

--httpd.conf--

LoadModule lua_module modules/mod_lua.so
AddHandler lua-script .lua

and ran a simple script and it works.

--htdocs/hello.lua--

function handle(r)
    r.content_type = "text/html"
    r:puts("Hello Lua World!\n")
end

I'd now like to connect to a local pg database but can't get it work.

function handle(r)
    r.content_type = "text/html"
    r:puts("Hello Lua World!\n")
    local db, err = r:dbacquire("postgres", "postgres://user:secret@localhost/db0")
    if not err then
     r:puts("connected!")
    else
     r:puts("couldn't connect!")
    end
end

No error messages whatsoever. Am I missing further configuration?

Thanks for any input!


Solution

  • Turns out I got the driver name and connection string wrong. Replacing the dbacquire line in the question with this should make it work.

    db = r:dbacquire("pgsql", "hostname=localhost dbname=foo user=bar password=baz")
    

    Better yet, by embedding these in the httpd.conf like so

    DBDriver pgsql
    DBDParams "hostname=localhost dbname=foo user=bar password=baz"
    

    You can get away by simply doing this in your lua scripts

    db = r:dbacquire()
    --start using your db here