forked from SSPkrolik/nimongo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmongo.nim
338 lines (290 loc) · 10.2 KB
/
mongo.nim
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
import std/options
import std/md5
import std/net
import std/oids
import std/strutils
import mongo/bson except `()`
export bson
import mongo/auth
import mongo/clientbase
import mongo/errors
import mongo/reply
import mongo/writeconcern
when compileOption("threads"):
import mongo/threaded as sync
else:
import mongo/single as sync
export auth
export clientbase except nextRequestId, init, calcReturnSize, updateCount, makeQuery, prepareMore, prepareQuery
export errors
export reply
export writeconcern
export sync except acquire, release, refresh
# === Collection API === #
proc find*(c: Collection[Mongo]; filter: Bson; fields: seq[string] = @[];
maxTime = 0'i32): Cursor[Mongo] =
## Find query
c.makeQuery(%*{ "$query": filter }, fields, maxTime)
# === Find API === #
iterator items*(f: Cursor[Mongo]): Bson =
## Perform MongoDB query and return iterator for all matching documents
while not f.isClosed:
for doc in f.refresh:
yield doc
proc next*(f: Cursor[Mongo]): seq[Bson] =
## Perform MongoDB query and return sequence of all matching documents
for doc in f.refresh:
result.add doc
proc first*(f: Cursor[Mongo]): Bson =
## Perform MongoDB query and return first matching document
for doc in f.limit(1).items:
return doc
raise NotFound.newException "No documents matching query were found"
proc firstOrNone*(f: Cursor[Mongo]): Option[Bson] =
## Perform MongoDB query and return first matching document, if available.
try:
result = some f.first
except NotFound:
discard
proc isMaster*(sm: Mongo): bool =
## Perform query in order to check if connected Mongo instance is a master
let doc = sm["admin"]["$cmd"].makeQuery(%*{"isMaster": 1}).first
result = doc["ismaster"].toBool
iterator keys*(sm: Mongo): string =
## Iterate over databases on the server
let response = sm["admin"]["$cmd"].makeQuery(%*{"listDatabases": 1}).first
let status = response.toStatusReply
if status.ok:
for b in response["databases"].items:
yield b["name"].toString
else:
raise MongoError.newException:
"unable to fetch databases: " & status.err
iterator pairs*(sm: Mongo): tuple[name: string, database: Database[Mongo]] =
## Iterate over databases on the server
for name in sm.keys:
yield (name: name, database: sm[name])
iterator values*(sm: Mongo): Database[Mongo] =
## Iterate over databases on the server
for _, db in sm.pairs:
yield db
proc createCollection*(db: Database[Mongo]; name: string; capped = false;
autoIndexId = true; maxSize = 0;
maxDocs = 0): StatusReply {.deprecated.} =
## Create collection inside database via sync connection
var request = %*{"create": name}
if capped: request["capped"] = capped.toBson
if autoIndexId: request["autoIndexId"] = true.toBson
if maxSize > 0: request["size"] = maxSize.toBson
if maxDocs > 0: request["max"] = maxDocs.toBson
let response = db["$cmd"].makeQuery(request).first
return response.toStatusReply
iterator keys*(db: Database[Mongo]; filter: Bson = %*{}): string =
## List collections inside specified database
let response = db["$cmd"].makeQuery(%*{"listCollections": 1'i32}).first
let status = response.toStatusReply
if status.ok:
for col in response["cursor"]["firstBatch"]:
yield col["name"].toString
else:
raise MongoError.newException:
"unable to fetch collections: " & status.err
iterator pairs*(db: Database[Mongo]; filter: Bson = %*{}):
tuple[name: string, collection: Collection[Mongo]] =
## List collections inside specified database
for name in db.keys(filter = filter):
yield (name: name, collection: db[name])
iterator values*(db: Database[Mongo]; filter: Bson = %*{}): Collection[Mongo] =
## List collections inside specified database
for _, col in db.pairs(filter = filter):
yield col
proc rename*(c: Collection[Mongo]; name: string; dropTarget = false): StatusReply =
## Rename collection
let
request = %*{
"renameCollection": $c,
"to": "$#.$#" % [c.db.name, name],
"dropTarget": dropTarget
}
response = c.db.client["admin"]["$cmd"].makeQuery(request).first
c.name = name
result = response.toStatusReply
proc drop*(db: Database[Mongo]): bool =
## Drop database from server
db["$cmd"].makeQuery(%*{"dropDatabase": 1}).first.isReplyOk
proc drop*(c: Collection[Mongo]): bool =
## Drop collection from database; returns `true` if the database existed,
## `false` otherwise.
let status = c.db["$cmd"].makeQuery(%*{"drop": c.name}).first.toStatusReply
if not status.ok:
if "ns not found" in status.err:
result = false
else:
raise MongoError.newException "collection drop: " & status.err
else:
result = true
proc stats*(c: Collection[Mongo]): Bson =
c.db["$cmd"].makeQuery(%*{"collStats": c.name}).first
proc len*(c: Collection[Mongo]): int =
## Return number of documents in collection
c.db["$cmd"].makeQuery(%*{"count": c.name}).first.getReplyN
proc len*(f: Cursor[Mongo]): int =
## Return number of documents in find query result
f.collection.db["$cmd"].makeQuery(%*{"count": f.collection.name,
"query": f.filter}).first.getReplyN
proc sort*(f: Cursor[Mongo]; criteria: Bson) {.deprecated.} =
## Setup sorting criteria
f.sorting = criteria
proc unique*(f: Cursor[Mongo], key: string): seq[string] {.deprecated.} =
## Force cursor to return only distinct documents by specified field.
## Corresponds to '.distinct()' MongoDB command. If Nim we use 'unique'
## because 'distinct' is Nim's reserved keyword.
let
request = %*{
"distinct": f.collection.name,
"query": f.filter,
"key": key
}
response = f.collection.db["$cmd"].makeQuery(request).first
if response.isReplyOk:
for item in response["values"].items:
result.add item.toString
proc getLastError*(m: Mongo): StatusReply =
## Get last error happened in current connection
m["admin"]["$cmd"].makeQuery(%*{"getLastError": 1'i32}).first.toStatusReply
# ============= #
# Insert API #
# ============= #
proc insert*(c: Collection[Mongo]; documents: seq[Bson];
ordered = true; writeConcern: Bson = nil): StatusReply {.deprecated.} =
## Insert several new documents into MongoDB using one request
#
# insert any missing _id fields
#
var inserted_ids: seq[Bson] = @[]
for doc in documents.items:
if not doc.contains("_id"):
doc["_id"] = toBson(genOid())
inserted_ids.add(doc["_id"])
#
# build & send Mongo query
#
let
request = %*{
"insert": c.name,
"documents": documents,
"ordered": ordered,
"writeConcern":
if writeConcern == nil.Bson:
c.writeConcern
else:
writeConcern
}
response = c.db["$cmd"].makeQuery(request).first
result = response.toStatusReply(inserted_ids = inserted_ids)
proc insert*(c: Collection[Mongo]; document: Bson; ordered = true;
writeConcern: Bson = nil): StatusReply {.deprecated.} =
## Insert new document into MongoDB via sync connection
let wc =
if writeConcern == nil.Bson:
c.writeConcern
else:
writeConcern
result = c.insert(@[document], ordered, writeConcern = wc)
# =========== #
# Update API #
# =========== #
proc update*(c: Collection[Mongo]; selector, update: Bson;
multi, upsert: bool): StatusReply {.deprecated.} =
## Update MongoDB document[s]
let
request = %*{
"update": c.name,
"updates": [%*{
"q": selector,
"u": update,
"upsert": upsert,
"multi": multi,
}],
"ordered": true
}
result = c.db["$cmd"].makeQuery(request).first.toStatusReply
# ==================== #
# Find and modify API #
# ==================== #
proc findAndModify*(c: Collection[Mongo]; selector, sort, update: Bson;
afterUpdate, upsert: bool; writeConcern: Bson = nil;
remove = false): StatusReply {.deprecated.} =
## Finds and modifies MongoDB document
let request = %*{
"findAndModify": c.name,
"query": selector,
"new": afterUpdate,
"upsert": upsert,
"writeConcern":
if writeConcern == nil.Bson:
c.writeConcern
else:
writeConcern
}
if not sort.isNil:
request["sort"] = sort
if remove:
request["remove"] = remove.toBson()
else:
request["update"] = update
result = c.db["$cmd"].makeQuery(request).first.toStatusReply
# ============ #
# Remove API #
# ============ #
proc remove*(c: Collection[Mongo], selector: Bson, limit: int = 0, ordered: bool = true, writeConcern: Bson = nil): StatusReply {.deprecated.} =
## Delete document[s] from MongoDB
let
request = %*{
"delete": c.name,
"deletes": [%*{"q": selector, "limit": limit}],
"ordered": true,
"writeConcern": if writeConcern == nil.Bson: c.writeConcern else: writeConcern
}
result = c.db["$cmd"].makeQuery(request).first.toStatusReply
# =============== #
# User management
# =============== #
proc createUser*(db: DataBase[Mongo], username: string, pwd: string, customData: Bson = newBsonDocument(), roles: Bson = newBsonArray()): bool =
## Create new user for the specified database
let createUserRequest = %*{
"createUser": username,
"pwd": pwd,
"customData": customData,
"roles": roles,
"writeConcern": db.client.writeConcern
}
result = db["$cmd"].makeQuery(createUserRequest).first.isReplyOk
proc dropUser*(db: Database[Mongo], username: string): bool =
## Drop user from the db
let
dropUserRequest = %*{
"dropUser": username,
"writeConcern": db.client.writeConcern
}
result = db["$cmd"].makeQuery(dropUserRequest).first.isReplyOk
# ============== #
# Authentication #
# ============== #
proc authenticate*(db: Database[Mongo]; user, pass: string): bool =
## Authenticate connection (sync): using MONGODB-CR auth method
if user == "" or pass == "":
return false
let nonce =
db["$cmd"].makeQuery(%*{"getnonce": 1'i32}).first["nonce"].toString
let passwordDigest = $toMd5("$#:mongo:$#" % [user, pass])
let key = $toMd5("$#$#$#" % [nonce, user, passwordDigest])
let request = %*{
"authenticate": 1'i32,
"mechanism": "MONGODB-CR",
"user": user,
"nonce": nonce,
"key": key,
"autoAuthorize": 1'i32
}
result = db["$cmd"].makeQuery(request).first.isReplyOk