Skip to content

Conversation

mjstephan
Copy link

@mjstephan mjstephan commented Jul 7, 2025

Fixes #798 and #732 for SQLite in lapis/db/sqlite.lua

NOTE: I need help correcting lapis/db/sqlite.moon, because I am not familiar with MoonScript. Also if there is an issue with my coding style or naming conventions, please change if necessary...

Currently there is no way to issue persistent PRAGMA statements for connections. Also there is no way to have transaction support for multiple SQL statements, since sqlite.lua uses lsqlite3 db:nrows, which only allows a single statement in SQLite.

Added functionality for setting SQLite pragma commands needed for all connections (foreign_keys, busy_timeout, etc.) in connect function of sqlite.lua. To use this feature, config file would need to have a connection_pragma_defaults table like this (key is pragma command, value is pragma value):

sqlite = {
    database = "db/sqlite_database.db",
    connection_pragma_defaults = {
      foreign_keys = true,
      busy_timeout = 5000
    }

Also added the following functions
exec -allowing the use of lsqlite3 db:exec function, which allows multiple statements and transactions
exec_scalar - utility function for easily retrieving a single value
prepare - allowing the use of db:prepare for prepared statements

For instance, if you have the config file setup like the example above:

-- using updated version of sqlite.lua
local db = require("lapis.db.sqlite")
local timeout = db.exec_scalar("PRAGMA busy_timeout;")
print(timeout) -- 5000

local foreign_keys = db.exec_scalar("PRAGMA foreign_keys;")
print(foreign_keys) -- 1

Added functionality for setting SQLite pragma commands needed for all connections (foreign_keys, busy_timeout) in connect function.  To use these config file would need to have a connection_pragma_defaults keys like this (key is pragma command, value is pragma value):
```
sqlite = {
    database = "db/sqlite_database.db",
    connection_pragma_defaults = {
      foreign_keys = true,
      busy_timeout = 20000
    }
```

Also added the following functions
exec -allowing the use of lsqlite3 db:exec function, which allows multiple statements and transactions
exec_scalar - utility function for easily retrieving a single value
prepare - allowing the use of db:prepare for prepared statements
@mjstephan mjstephan changed the title Update sqlite.lua Fix SQLite connection starts without foreign key enforcement #798 and Transactions #732 Jul 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

SQLite connection starts without foreign key enforcement
1 participant