This example accompanies the tutorial Using Lua to Access a PostgreSQL Database. It shows how to keep one PostgreSQL connection object alive and reuse it for all database operations from the application.
mako.conf- Holds the PostgreSQL connection settings in tablecinfo.www/.preload- Loads the configuration, checks thatpgsql.sois available, and creates the sharedpgobject.www/.lua/pg.lua- Helper library that wrapspgsql.so, maintains one persistent connection, and runs work on a database thread.www/index.lsp- Form-driven test page that inserts and lists messages from the database.
- Create an ElephantSQL account and compile the required C code as explained in the tutorial.
- Open
mako.confand set the values in tablecinfousing the connection details from your ElephantSQL account. - Save
mako.conf. - Start the example from the
PostgreSQLdirectory with:
cd LSP-Examples/PostgreSQL
makoBecause the app includes a local mako.conf, starting Mako in this directory loads the configured PostgreSQL example automatically.
- Confirm that the console prints
DB connected: yes. - Open
http://localhost:portno, whereportnois the server's listening port. - Enter data in the HTML form and click
Save Message.
www/.preload first verifies that the PostgreSQL Lua binding pgsql.so is available. It then loads mako.conf, creates the helper object from www/.lua/pg.lua, and stores it as pg for the rest of the app.
pg.lua maintains one connection, pings it when needed, resets it if the connection drops, and runs queries on a dedicated BAS thread. index.lsp converts the normal response to a deferred response, then asks app.pg.run(...) to perform the SQL work on that background thread. The page creates the messages table on first use, inserts any submitted text, reads the rows back, and renders them as HTML.
- If Mako cannot load
pgsql.so, the example stops early and prints the library search path to the trace output. - This example depends on the
mako.conffile in the directory, so runmakofrom insidePostgreSQL/rather than from somewhere else.