-
Notifications
You must be signed in to change notification settings - Fork 1
/
mongo.lua
378 lines (325 loc) · 8.75 KB
/
mongo.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
local bson = require "bson"
local socket = ngx.socket.tcp
local driver = require "mongo.driver"
local rawget = rawget
local assert = assert
local bson_encode = bson.encode
local bson_encode_order = bson.encode_order
local bson_decode = bson.decode
local empty_bson = bson_encode {}
local mongo = {}
mongo.null = assert(bson.null)
mongo.maxkey = assert(bson.maxkey)
mongo.minkey = assert(bson.minkey)
mongo.type = assert(bson.type)
local mongo_cursor = {}
local cursor_meta = {
__index = mongo_cursor,
}
local mongo_client = {}
local client_meta = {
__index = function(self, key)
return rawget(mongo_client, key) or self:getDB(key)
end,
__tostring = function (self)
local port_string
if self.port then
port_string = ":" .. tostring(self.port)
else
port_string = ""
end
return "[mongo client : " .. self.host .. port_string .."]"
end,
__gc = function(self)
self:disconnect()
end
}
local mongo_db = {}
local db_meta = {
__index = function (self, key)
return rawget(mongo_db, key) or self:getCollection(key)
end,
__tostring = function (self)
return "[mongo db : " .. self.name .. "]"
end
}
local mongo_collection = {}
local collection_meta = {
__index = function(self, key)
return rawget(mongo_collection, key) or self:getCollection(key)
end ,
__tostring = function (self)
return "[mongo collection : " .. self.full_name .. "]"
end
}
function mongo.client( obj )
obj.port = obj.port or 27017
obj.__id = 0
obj.__sock = socket()
assert(obj.__sock:connect(obj.host, obj.port),"Connect failed")
return setmetatable(obj, client_meta)
end
function mongo_client:getDB(dbname)
local db = {
connection = self,
name = dbname,
full_name = dbname,
database = false,
__cmd = dbname .. "." .. "$cmd",
}
db.database = db
return setmetatable(db, db_meta)
end
function mongo_client:disconnect()
if self.__sock then
self.__sock:close()
self.__sock = nil
end
end
function mongo_client:set_keepalive(...)
local sock = self.__sock
if not sock then
return nil, "not initialized"
end
return sock:setkeepalive(...)
end
function mongo_client:get_reused_times()
local sock = self.__sock
if not sock then
return nil, "not initialized"
end
return sock:getreusedtimes()
end
function mongo_client:set_timeout(timeout)
local sock = self.__sock
if not sock then
return nil, "not initialized"
end
return sock:settimeout(timeout)
end
function mongo_client:genId()
local id = self.__id + 1
self.__id = id
return id
end
function mongo_client:runCommand(...)
if not self.admin then
self.admin = self:getDB "admin"
end
return self.admin:runCommand(...)
end
local function get_reply(sock, result)
local length = driver.length(sock:receive(4))
local reply = sock:receive(length)
return reply, driver.reply(reply, result)
end
local function pass_digest ( username , password )
return ngx.md5(username .. ":mongo:" .. password)
end
function mongo_db:auth(username, password)
local r, err = self:runCommand("getnonce")
if not r then
return nil, err
end
local _, nonce = cbson.type(r.nonce)
local digest = ngx.md5( nonce .. username .. pass_digest ( username , password ) )
r, err = self:runCommand(
"authenticate", true,
"user", username,
"nonce", nonce,
"key", digest)
if not r then
return nil, err
end
return 1
end
function mongo_db:runCommand(cmd,cmd_v,...)
local request_id = self.connection:genId()
local sock = self.connection.__sock
local bson_cmd
if not cmd_v then
if type(cmd) == "table" then
bson_cmd = bson_encode(cmd)
else
bson_cmd = bson_encode_order(cmd,1)
end
else
bson_cmd = bson_encode_order(cmd,cmd_v,...)
end
local pack = driver.query(request_id, 0, self.__cmd, 0, 1, bson_cmd)
-- todo: check send
sock:send(pack)
local _, succ, reply_id, doc = get_reply(sock)
assert(request_id == reply_id, "Reply from mongod error")
-- todo: check succ
return bson_decode(doc)
end
function mongo_db:getCollection(collection)
local col = {
connection = self.connection,
name = collection,
full_name = self.full_name .. "." .. collection,
database = self.database,
}
self[collection] = setmetatable(col, collection_meta)
return col
end
mongo_collection.getCollection = mongo_db.getCollection
function mongo_collection:insert(doc)
if doc._id == nil then
doc._id = bson.objectid()
end
local sock = self.connection.__sock
local pack = driver.insert(0, self.full_name, bson_encode(doc))
-- todo: check send
-- flags support 1: ContinueOnError
sock.send(pack)
end
function mongo_collection:batch_insert(docs)
for i=1,#docs do
if docs[i]._id == nil then
docs[i]._id = bson.objectid()
end
docs[i] = bson_encode(docs[i])
end
local sock = self.connection.__sock
local pack = driver.insert(0, self.full_name, docs)
-- todo: check send
sock:send(pack)
end
function mongo_collection:update(selector,update,upsert,multi)
local flags = (upsert and 1 or 0) + (multi and 2 or 0)
local sock = self.connection.__sock
local pack = driver.update(self.full_name, flags, bson_encode(selector), bson_encode(update))
-- todo: check send
sock:send(pack)
end
function mongo_collection:delete(selector, single)
local sock = self.connection.__sock
local pack = driver.delete(self.full_name, single, bson_encode(selector))
-- todo: check send
sock:send(pack)
end
function mongo_collection:findOne(query, selector)
-- selector: { field1 = true, ... }
local request_id = self.connection:genId()
local sock = self.connection.__sock
local pack = driver.query(request_id, 0, self.full_name, 0, 1, query and bson_encode(query) or empty_bson, selector and bson_encode(selector))
-- todo: check send
sock:send(pack)
local _, succ, reply_id, doc = get_reply(sock)
assert(request_id == reply_id, "Reply from mongod error")
-- todo: check succ
return bson_decode(doc)
end
function mongo_collection:count(query)
local r, err = self.database:runCommand("count", self.name, "query", query or {})
if not r then
return nil, err
end
return r.n
end
function mongo_collection:query(query, selector, skip, limit)
if query and type(query) == "table" then
query = bson_encode(query)
end
query = query or empty_bson
selector = selector and bson_encode(selector)
local conn = self.connection
local request_id = conn:genId()
local sock = conn.__sock
local pack = driver.query(request_id, 0, self.full_name, skip or 0, limit or -1, query, selector)
sock:send(pack)
local results = {}
local data, succ, reply_id, doc = get_reply(sock, results)
assert(request_id == reply_id, "Reply from mongod error")
for key, value in pairs(results) do
results[key] = bson_decode(value)
end
-- todo: check succ
return results
end
function mongo_collection:find(query, selector)
return setmetatable( {
__collection = self,
__query = query and bson_encode(query) or empty_bson,
__selector = selector and bson_encode(selector),
__ptr = nil,
__data = nil,
__cursor = nil,
__document = {},
__flags = 0,
} , cursor_meta)
end
function mongo_cursor:hasNext()
if self.__ptr == nil then
if self.__document == nil then
return false
end
local conn = self.__collection.connection
local request_id = conn:genId()
local sock = conn.__sock
local pack
if self.__data == nil then
pack = driver.query(request_id, self.__flags, self.__collection.full_name,0,0,self.__query,self.__selector)
else
if self.__cursor then
pack = driver.more(request_id, self.__collection.full_name,0,self.__cursor)
else
-- no more
self.__document = nil
self.__data = nil
return false
end
end
--todo: check send
sock:send(pack)
local data, succ, reply_id, doc, cursor = get_reply(sock, self.__document)
assert(request_id == reply_id, "Reply from mongod error")
if succ then
if doc then
self.__data = data
self.__ptr = 1
self.__cursor = cursor
return true
else
self.__document = nil
self.__data = nil
self.__cursor = nil
return false
end
else
self.__document = nil
self.__data = nil
self.__cursor = nil
if doc then
local err = bson_decode(doc)
error(err["$err"])
else
error("Reply from mongod error")
end
end
end
return true
end
function mongo_cursor:next()
if self.__ptr == nil then
error "Call hasNext first"
end
local r = bson_decode(self.__document[self.__ptr])
self.__ptr = self.__ptr + 1
if self.__ptr > #self.__document then
self.__ptr = nil
end
return r
end
function mongo_cursor:close()
-- todo: warning hasNext after close
if self.__cursor then
local sock = self.__collection.connection.__sock
local pack = driver.kill(self.__cursor)
-- todo: check send
sock:send(pack)
end
end
return mongo