comparison mod_storage_gdbm/mod_storage_gdbm.lua @ 1570:67fafebdceb7

mod_storage_gdbm: Storage backend based on lgdbm
author Kim Alvefur <zash@zash.se>
date Tue, 18 Nov 2014 13:05:04 +0100
parents
children d9f3c66ea938
comparison
equal deleted inserted replaced
1569:711fabfe6604 1570:67fafebdceb7
1 -- mod_storage_gdbm
2 -- Copyright (C) 2014 Kim Alvefur
3 --
4 -- This file is MIT/X11 licensed.
5 --
6 -- Depends on lgdbm:
7 -- http://webserver2.tecgraf.puc-rio.br/~lhf/ftp/lua/#lgdbm
8
9 local gdbm = require"gdbm";
10 local path = require"util.paths";
11 local lfs = require"lfs";
12 local serialize, deserialize = import("util.serialization", "serialize", "deserialize");
13
14 local base_path = path.resolve_relative_path(prosody.paths.data, module.host);
15 lfs.mkdir(base_path);
16
17 local cache = {};
18
19 local driver = {};
20 local driver_mt = { __index = driver };
21
22 function driver:set(user, value)
23 local ok, err = gdbm.replace(self._db, user or "@", serialize(value));
24 if not ok then return nil, err; end
25 return true;
26 end
27
28 function driver:get(user)
29 local data, err = gdbm.fetch(self._db, user or "@");
30 if not data then return nil, err; end
31 return deserialize(data);
32 end
33
34 function open(_, store, typ)
35 typ = typ or "keyval";
36 if typ ~= "keyval" then
37 return nil, "unsupported-store";
38 end
39
40 local db_path = path.join(base_path, store) .. ".db";
41
42 local db = cache[db_path];
43 if not db then
44 db = assert(gdbm.open(db_path, "c"));
45 cache[db_path] = db;
46 end
47 return setmetatable({ _db = db; _path = db_path; store = store, typ = type }, driver_mt);
48 end
49
50 function module.unload()
51 for path, db in pairs(cache) do
52 gdbm.sync(db);
53 gdbm.close(db);
54 end
55 end
56
57 module:provides"storage";