Last active
September 1, 2023 07:14
-
-
Save jart/f9b1a7ebe5c7ebea3abe8f98125c692c to your computer and use it in GitHub Desktop.
redbean sqlite tutorial
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
re = require "re" | |
sqlite3 = require "lsqlite3" | |
reNumberPath = re.compile[[^/([0-9][0-9]*)$]] | |
function SetupSql() | |
if not db then | |
db = sqlite3.open('redbean.sqlite3') | |
db:busy_timeout(1000) | |
db:exec[[PRAGMA journal_mode=WAL]] | |
db:exec[[PRAGMA synchronous=NORMAL]] | |
getBarStmt = db:prepare[[ | |
SELECT | |
foo | |
FROM | |
Bar | |
WHERE | |
id = ? | |
]] | |
end | |
end | |
local function GetBar(id) | |
if not getBarStmt then | |
Log(kLogWarn, 'prepare failed: ' .. db:errmsg()) | |
return nil | |
end | |
getBarStmt:reset() | |
getBarStmt:bind(1, id) | |
for bar in getBarStmt:nrows() do | |
return bar | |
end | |
return nil | |
end | |
function OnHttpRequest() | |
SetupSql() | |
_, id = reNumberPath:search(GetPath()) | |
if id then | |
bar = GetBar(id) | |
SetHeader('Content-Type', 'text/palin; charset=utf-8') | |
Write(string(bar.foo)) | |
return | |
end | |
Route() | |
SetHeader('Content-Language', 'en-US') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment