comparison mod_storage_mondodb/mod_storage_mongodb.lua @ 504:0e9b43db7a2c

mod_storage_mondodb: Add module
author James Callahan <james@chatid.com>
date Mon, 12 Dec 2011 21:39:08 +1100
parents
children
comparison
equal deleted inserted replaced
503:db32236d7682 504:0e9b43db7a2c
1 local next = next;
2 local setmetatable = setmetatable;
3
4 local log = require "util.logger".init("mongodb");
5 local params = module:get_option("mongodb");
6
7 local mongo = require "mongo";
8
9 local conn = mongo.Connection.New ( true );
10 conn:connect ( params.server );
11 conn:auth ( params );
12
13 local keyval_store = {};
14 keyval_store.__index = keyval_store;
15
16 function keyval_store:get(username)
17 local host, store = module.host, self.store;
18
19 local namespace = params.dbname .. "." .. host;
20 local v = { _id = { store = store ; username = username } };
21
22 local cursor , err = conn:query ( namespace , v );
23 if not cursor then return nil , err end;
24
25 local r , err = cursor:next ( );
26 if not r then return nil , err end;
27 return r.data;
28 end
29
30 function keyval_store:set(username, data)
31 local host, store = module.host, self.store;
32 if not host then return nil , "mongodb cannot currently be used for host-less data" end;
33
34 local namespace = params.dbname .. "." .. host;
35 local v = { _id = { store = store ; username = username } };
36
37 if next(data) ~= nil then -- set data
38 v.data = data;
39 return conn:insert ( namespace , v );
40 else -- delete data
41 return conn:remove ( namespace , v );
42 end;
43 end
44
45 local driver = { name = "mongodb" };
46
47 function driver:open(store, typ)
48 if not typ then -- default key-value store
49 return setmetatable({ store = store }, keyval_store);
50 end;
51 return nil, "unsupported-store";
52 end
53
54 module:add_item("data-driver", driver);