Skip to content

Commit

Permalink
Reorganized metatables to create one for all DBM objects.
Browse files Browse the repository at this point in the history
Closes #28.
  • Loading branch information
pkulchenko committed Nov 11, 2023
1 parent f7949de commit 17e5f5c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
28 changes: 15 additions & 13 deletions fullmoon.lua
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
-- Copyright 2021-23 Paul Kulchenko
--

local NAME, VERSION = "fullmoon", "0.378"
local NAME, VERSION = "fullmoon", "0.380"

--[[-- support functions --]]--

Expand Down Expand Up @@ -661,9 +661,21 @@ end

--[[-- storage engine --]]--

local sqlite3
local NONE = {}
local dbmt = { -- share one metatable among all DBM objects
-- simple __index = db doesn't work, as it gets `dbm` passed instead of `db`,
-- so remapping is needed to proxy this to `t.db` instead
__index = function(t,k)
if sqlite3[k] then return sqlite3[k] end
local db = rawget(t, "db")
return db and db[k] and function(self,...) return db[k](db,...) end or nil
end,
__gc = function(t) return t:close() end,
__close = function(t) return t:close() end
}
local function makeStorage(dbname, sqlsetup, opts)
local sqlite3 = require "lsqlite3"
sqlite3 = sqlite3 or require "lsqlite3"
if type(sqlsetup) == "table" and opts == nil then
sqlsetup, opts = nil, sqlsetup
end
Expand Down Expand Up @@ -724,17 +736,7 @@ local function makeStorage(dbname, sqlsetup, opts)
self.db = db
self.prepcache = {}
self.pid = unix.getpid()
-- simple __index = db doesn't work, as it gets `dbm` passed instead of `db`,
-- so remapping is needed to proxy this to `t.db` instead
return setmetatable(self, {
__index = function(t,k)
if sqlite3[k] then return sqlite3[k] end
local db = rawget(t, "db")
return db and db[k] and function(self,...) return db[k](db,...) end or nil
end,
__gc = function(t) return t:close() end,
__close = function(t) return t:close() end
})
return setmetatable(self, dbmt)
end
local function norm(sql)
return (sql:gsub("%-%-[^\n]*\n?",""):gsub("^%s+",""):gsub("%s+$",""):gsub("%s+"," ")
Expand Down
10 changes: 10 additions & 0 deletions test.lua
Original file line number Diff line number Diff line change
Expand Up @@ -1118,6 +1118,16 @@ if isRedbean then
assert(dbm:fetchAll(query..";"..query:gsub("101","102")))
is(dbm.prepcache[query:gsub("101","102")] ~= nil, true, "last statement is cached")

-- test for closing the DB
do
local dbm = fm.makeStorage(":memory:", "")
local db = dbm.db
is(db:isopen(), true, "DB is initially open")
dbm = nil
collectgarbage() -- collect the DBM object, which closes the DB
is(db:isopen(), false, "DB is closed after garbage collection")
end

-- tests for using the storage with forked processes
dbm = fm.makeStorage(":memory:", script)
dbm.pid = 0 -- reset the pid
Expand Down

0 comments on commit 17e5f5c

Please sign in to comment.