colddb/flatdb.lua

89 lines
1.6 KiB
Lua
Raw Normal View History

2015-05-02 15:57:17 +02:00
local mp = require("MessagePack")
2015-04-06 15:44:20 +02:00
local function isFile(path)
2015-05-01 15:04:19 +02:00
local f = io.open(path, "r")
if f then
f:close()
return true
end
return false
2015-04-06 15:44:20 +02:00
end
local function isDir(path)
2015-05-01 15:04:19 +02:00
local tmp = path.."/"..os.tmpname()
local f = io.open(tmp, "w")
if f then
f:close()
os.remove(tmp)
return true
end
return false
2015-04-06 15:44:20 +02:00
end
2015-04-07 09:37:11 +02:00
local function load_page(path)
2015-05-02 15:57:17 +02:00
local ret
local f = io.open(path, "rb")
if f then
ret = mp.unpack(f:read("*a"))
f:close()
end
return ret
2015-04-06 15:44:20 +02:00
end
2015-04-07 09:37:11 +02:00
local function store_page(path, page)
if type(page) == "table" then
2015-04-06 15:44:20 +02:00
local f = io.open(path, "wb")
if f then
2015-05-02 15:57:17 +02:00
f:write(mp.pack(page))
2015-04-06 15:44:20 +02:00
f:close()
return true
end
end
return false
end
local pool = {}
local db_funcs = {
2015-04-07 09:37:11 +02:00
save = function(db, p)
if p then
if type(p) == "string" and type(db[p]) == "table" then
return store_page(pool[db].."/"..p, db[p])
2015-04-06 15:44:20 +02:00
else
return false
end
end
2015-04-07 09:37:11 +02:00
for p, page in pairs(db) do
2015-05-01 15:04:19 +02:00
if not store_page(pool[db].."/"..p, page) then
return false
end
2015-04-06 15:44:20 +02:00
end
return true
end
}
local mt = {
__index = function(db, k)
if db_funcs[k] then return db_funcs[k] end
if isFile(pool[db].."/"..k) then
2015-04-07 09:37:11 +02:00
db[k] = load_page(pool[db].."/"..k)
2015-04-06 15:44:20 +02:00
end
return rawget(db, k)
end
}
pool.hack = db_funcs
return setmetatable(pool, {
__mode = "kv",
__call = function(pool, path)
2015-05-01 15:04:19 +02:00
assert(isDir(path), path.." is not a directory.")
2015-04-06 15:44:20 +02:00
if pool[path] then return pool[path] end
local db = {}
setmetatable(db, mt)
pool[path] = db
pool[db] = path
return db
end
})