changeset 1799:d2dd1db9ece6

mod_storage_lmdb: Rearrange module to allow using as a library
author Kim Alvefur <zash@zash.se>
date Fri, 28 Aug 2015 00:34:43 +0200
parents 3ae8c81a348b
children 669d1208221a
files mod_storage_lmdb/mod_storage_lmdb.lua
diffstat 1 files changed, 42 insertions(+), 17 deletions(-) [+]
line wrap: on
line diff
--- a/mod_storage_lmdb/mod_storage_lmdb.lua	Fri Aug 28 00:16:39 2015 +0200
+++ b/mod_storage_lmdb/mod_storage_lmdb.lua	Fri Aug 28 00:34:43 2015 +0200
@@ -15,19 +15,12 @@
 local serialize = serialization.serialize;
 local deserialize = serialization.deserialize;
 
-local base_path = path.resolve_relative_path(prosody.paths.data, module.host);
-lfs.mkdir(base_path);
-
-local env = lmdb.env_create();
-assert(env:set_maxdbs(module:get_option_number("lmdb_maxdbs", 20)));
-local env_flags = 0;
-for i, flag in ipairs(module:get_option_array("lmdb_flags", {})) do
-	env_flags = env_flags + assert(lmdb["MDB_"..flag:upper()], "No such flag "..flag);
-end
-env:open(base_path, env_flags, tonumber("640", 8));
+local drivers = {};
+local provider = {};
 
 local keyval = {};
 local keyval_mt = { __index = keyval, flags = lmdb.MDB_CREATE };
+drivers.keyval = keyval_mt;
 
 function keyval:set(user, value)
 	local t = self.env:txn_begin(nil, 0);
@@ -65,22 +58,54 @@
 	keyval = keyval_mt;
 }
 
-function open(_, store, typ)
+
+function provider:init(config)
+	if config.base_path then
+		lfs.mkdir(config.base_path);
+	end
+	local env = lmdb.env_create();
+	env:set_maxdbs(config.maxdbs or 20);
+	local env_flags = 0;
+	if config.flags then
+		for flag in config.flags do
+			env_flags = env_flags + assert(lmdb["MDB_"..flag:upper()], "No such flag "..flag);
+		end
+	end
+	env:open(config.base_path or ".", env_flags, tonumber("640", 8));
+	self.env = env;
+end
+
+function provider:open(store, typ)
 	typ = typ or "keyval";
 	local driver_mt = drivers[typ];
 	if not driver_mt then
 		return nil, "unsupported-store";
 	end
+	local env = self.env;
 	local t = env:txn_begin(nil, 0);
 	local db = t:dbi_open(store.."_"..typ, driver_mt.flags);
-	assert(t:commit());
+	local ok, err = t:commit();
+	if not ok then
+		module:log("error", "Could not open database %s_%s: %s", store, typ, tostring(err));
+		return ok, err;
+	end
 
 	return setmetatable({ env = env, store = store, type = typ, db = db }, driver_mt);
 end
 
-function module.unload()
-	env:sync(1);
-	env:close();
+if prosody then
+	provider:init({
+		base_path = path.resolve_relative_path(prosody.paths.data, module.host);
+		flags = module:get_option_set("lmdb_flags", {});
+		maxdbs = module:get_option_number("lmdb_maxdbs", 20);
+	});
+
+	function module.unload()
+		provider.env:sync(1);
+		provider.env:close();
+	end
+
+	module:provides("storage", provider);
+else
+	return provider;
 end
-
-module:provides("storage");