1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2015 Alexandre Terrasa <alexandre@moz-code.org>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
19 # This is actually a wrapper around the [MongoDB C Driver](http://api.mongodb.org/c/1.1.4/index.html).
24 # # Opens the connexion with the Mongo server.
25 # var client = new MongoClient("mongodb://localhost:27017/")
27 # # Retrieve a collection.
28 # var col = client.database("test").collection("test")
30 # # Insert a document in the collection.
31 # var doc = new JsonObject
34 # doc["baz"] = new JsonArray
35 # assert col.insert(doc)
37 # # Retrieve a document from the collection.
38 # var query = new JsonObject
40 # var res = col.find(query)
41 # assert res["bar"] == "bar"
46 private import native_mongodb
52 # Everything inside MongoDB is manipulated as BSON Objects.
55 # * [Binary JSON spec](http://bsonspec.org/)
56 # * [Libbson](http://api.mongodb.org/libbson/1.1.4/)#
60 # Native instance pointer.
61 var native
: NativeBSON
63 # Returns a new BSON object initialized from the content of `json`.
66 # intrude import mongodb
67 # var obj = new JsonObject
69 # obj["name"] = "Rick"
70 # obj["ELS"] = new JsonArray
71 # var bson = new BSON.from_json(obj)
72 # assert bson.to_s == """{ "age" : 10, "name" : "Rick", "ELS" : [ ] }"""
74 init from_json
(json
: JsonObject) do
75 init(new NativeBSON.from_json_string
(json
.to_json
.to_cstring
))
78 # Returns a new BSON object parsed from `json_string`.
80 # If `json_string` is not a valid JSON string, this initializer returns NULL.
83 # intrude import mongodb
84 # var str = """{ "age" : 10, "name" : "Rick", "ELS" : [ ] }"""
85 # var bson = new BSON.from_json_string(str)
86 # assert bson.to_s == str
88 init from_json_string
(json_string
: String) do
89 init(new NativeBSON.from_json_string
(json_string
.to_cstring
))
93 var ns
= native
.to_native_string
94 var res
= ns
.to_s_with_copy
95 ns
.free
# manual free of gc allocated NativeString
99 # Returns a new JsonObject from `self`.
102 # intrude import mongodb
103 # var str = """{ "age" : 10, "name" : "Rick", "ELS" : [ ] }"""
104 # var bson = new BSON.from_json_string(str)
105 # var json = bson.to_json
106 # assert json["age"] == 10
107 # assert json["name"] == "Rick"
108 # assert json["ELS"].as(JsonArray).is_empty
110 fun to_json
: JsonObject do
111 var json
= to_s
.parse_json
112 if json
isa JsonParseError then
117 return json
.as(JsonObject)
120 redef fun finalize_once
do native
.destroy
123 redef class JsonObject
124 # Inits `self` from a BSON object.
125 private init from_bson
(bson
: BSON) do recover_with
(bson
.to_json
)
127 # Returns a new BSON object from `self`.
128 private fun to_bson
: BSON do return new BSON.from_json
(self)
131 # An error returned by the mongoc client.
133 # Within the client, if a method returns `false` or `null` it's more likely that
134 # an error occured during the execution.
136 # See `MongoClient::last_error`.
139 private var native
: BSONError
141 # Logical domain within a library that created the error.
142 fun domain
: Int do return native
.domain
144 # Domain specific error code.
145 fun code
: Int do return native
.code
147 # Human readable error message.
148 fun message
: String do
149 var ns
= native
.message
150 var res
= ns
.to_s_with_copy
155 redef fun to_s
do return "{message} (code: {code})"
158 # MongoDB Object ID representation.
160 # For ObjectIDs, MongoDB uses the `ObjectId("hash")` notation.
161 # This notation is replicated by the `to_s` service.
163 # Since the MongoDB notation is not JSON complient, the mongoc wrapper uses
164 # a JSON based notation like `{"$oid": "hash"}`.
165 # This is the notation returned by the `to_json` service.
166 private class MongoObjectId
168 var native
: BSONObjectId
170 # The unique ID as an MongoDB Object ID string.
171 fun id
: String do return native
.id
173 # Internal JSON representation of this Object ID.
175 # Something like `{"$oid": "5578e5dcf344225cc2378051"}`.
176 fun to_json
: JsonObject do
177 var obj
= new JsonObject
182 # Formatted as `ObjectId("5578e5dcf344225cc2378051")`
183 redef fun to_s
do return "ObjectId({id})"
186 # The MongoClient is used to connect to the mongo server and send queries.
191 # var uri = "mongodb://localhost:27017/"
192 # var client = new MongoClient(uri)
193 # assert client.server_uri == uri
196 super FinalizableOnce
199 var server_uri
: String
201 private var native
: NativeMongoClient is noinit
203 init do native
= new NativeMongoClient(server_uri
.to_cstring
)
207 # Returns `null` if an error occured. See `last_error`.
210 # var client = new MongoClient("mongodb://localhost:27017/")
211 # assert client.server_status["process"] == "mongod"
213 fun server_status
: nullable JsonObject do
214 var nbson
= native
.server_status
215 if nbson
== null then return null
216 var bson
= new BSON(nbson
)
217 var res
= new JsonObject.from_bson
(bson
)
221 # Lists available database names.
224 # var client = new MongoClient("mongodb://localhost:27017/")
225 # var db = client.database("test")
226 # db.collection("test").insert(new JsonObject)
227 # assert client.database_names.has("test")
229 fun database_names
: Array[String] do
230 var res
= new Array[String]
231 var nas
= native
.database_names
232 if nas
== null then return res
235 while not name
.address_is_null
do
236 res
.add name
.to_s_with_copy
244 # Loads or creates a database from its `name`.
246 # Database are automatically created on the MongoDB server upon insertion of
247 # the first document into a collection.
248 # There is no need to create a database manually.
251 # var client = new MongoClient("mongodb://localhost:27017/")
252 # assert client.database("test").name == "test"
254 fun database
(name
: String): MongoDb do return new MongoDb(self, name
)
256 # Close the connexion and destroy the instance.
258 # The reference should not be used beyond this point!
259 fun close
do finalize_once
261 redef fun finalize_once
do native
.destroy
263 # Last error raised by mongoc.
264 fun last_error
: nullable MongoError do
265 var last_error
= sys
.last_mongoc_error
266 if last_error
== null then return null
267 return new MongoError(last_error
)
270 # Last auto generated id.
271 private fun last_id
: nullable MongoObjectId do
272 var last_id
= sys
.last_mongoc_id
273 if last_id
== null then return null
274 return new MongoObjectId(last_id
)
277 # Set the last generated id or `null` to unset once used.
278 private fun last_id
=(id
: nullable MongoObjectId) do
280 sys
.last_mongoc_id
= null
282 sys
.last_mongoc_id
= id
.native
287 # A MongoDb database.
289 # Database are automatically created on the MongoDB server upon insertion of the
290 # first document into a collection.
291 # There is no need to create a database manually.
293 super FinalizableOnce
295 # `MongoClient` used to load this database.
296 var client
: MongoClient
301 private var native
: NativeMongoDb is noinit
303 init do native
= new NativeMongoDb(client
.native
, name
.to_cstring
)
305 # Lists available collection names.
307 # Returns `null` if an error occured. See `Sys::last_mongoc_error`.
310 # var client = new MongoClient("mongodb://localhost:27017/")
311 # var db = client.database("test")
312 # db.collection("test").insert(new JsonObject)
313 # assert db.collection_names.has("test")
315 fun collection_names
: Array[String] do
316 var res
= new Array[String]
317 var nas
= native
.collection_names
318 if nas
== null then return res
321 while not name
.address_is_null
do
322 res
.add name
.to_s_with_copy
330 # Loads or creates a collection by its `name`.
333 # var client = new MongoClient("mongodb://localhost:27017/")
334 # var db = client.database("test")
335 # var col = db.collection("test")
336 # assert col.name == "test"
338 fun collection
(name
: String): MongoCollection do
339 return new MongoCollection(self, name
)
342 # Checks if a collection named `name` exists.
345 # var client = new MongoClient("mongodb://localhost:27017/")
346 # var db = client.database("test")
347 # assert not db.has_collection("qwerty")
349 fun has_collection
(name
: String): Bool do
351 return native
.has_collection
(name
.to_cstring
)
354 # Drop `self`, returns false if an error occured.
355 fun drop
: Bool do return native
.drop
357 redef fun finalize_once
do native
.destroy
360 # A Mongo collection.
362 # Collections are automatically created on the MongoDB server upon insertion of
363 # the first document.
364 # There is no need to create a database manually.
365 class MongoCollection
366 super FinalizableOnce
368 # Database that collection belongs to.
369 var database
: MongoDb
371 # Name of this collection.
374 private var native
: NativeMongoCollection is noinit
376 # Loads a collection.
378 # Call `MongoDb::collection` instead.
380 native
= new NativeMongoCollection(
381 database
.client
.native
,
382 database
.name
.to_cstring
,
386 # Set the autogenerated last id if the `doc` does not contain one already.
387 private fun set_id
(doc
: JsonObject) do
388 var last_id
= database
.client
.last_id
389 if last_id
!= null then
390 doc
["_id"] = last_id
.to_json
391 database
.client
.last_id
= null
395 # Inserts a new document in the collection.
397 # If no _id element is found in document, then a new one be generated locally
398 # and added to the document.
400 # Returns `false` if an error occured. See `Sys::last_mongoc_error`.
403 # var client = new MongoClient("mongodb://localhost:27017/")
404 # var col = client.database("test").collection("test")
405 # var doc = new JsonObject
408 # doc["baz"] = new JsonArray
409 # assert col.insert(doc)
410 # assert doc.has_key("_id")
412 fun insert
(doc
: JsonObject): Bool do
413 var res
= native
.insert
(doc
.to_bson
.native
)
414 if res
then set_id
(doc
)
418 # Inserts multiple documents in the collection.
421 fun insert_all
(docs
: Collection[JsonObject]): Bool do
423 for doc
in docs
do res
= insert
(doc
) and res
427 # Saves a new document in the collection.
429 # If the document has an `_id` field it will be updated.
430 # Otherwise it will be inserted.
432 # Returns `false` if an error occured. See `Sys::last_mongoc_error`.
435 # var client = new MongoClient("mongodb://localhost:27017/")
436 # var col = client.database("test").collection("test")
438 # var doc = new JsonObject
441 # doc["baz"] = new JsonArray
443 # assert col.save(doc) # will be inserted
444 # assert doc.has_key("_id")
446 # var id = doc["_id"]
447 # assert col.save(doc) # will be updated
448 # assert doc["_id"] == id
450 fun save
(doc
: JsonObject): Bool do
451 var bson
= doc
.to_bson
452 var nat
= bson
.native
453 var res
= native
.save
(nat
)
454 if res
then set_id
(doc
)
455 assert nat
!= self #FIXME used to avoid GC crashes
456 assert bson
!= self #FIXME used to avoid GC crashes
460 # Removes the first document that matches `selector`.
462 # Returns `false` if an error occured. See `Sys::last_mongoc_error`.
465 # var client = new MongoClient("mongodb://localhost:27017/")
466 # var col = client.database("test").collection("test")
467 # var sel = new JsonObject
469 # assert col.remove(sel)
471 fun remove
(selector
: JsonObject): Bool do
472 return native
.remove
(selector
.to_bson
.native
)
475 # Removes all the document that match `selector`.
478 fun remove_all
(selector
: JsonObject): Bool do
479 return native
.remove_all
(selector
.to_bson
.native
)
482 # Updates a document already existing in the collection.
484 # No upsert is done, see `save` instead.
487 # var client = new MongoClient("mongodb://localhost:27017/")
488 # var col = client.database("test").collection("test")
489 # var sel = new JsonObject
491 # var upd = new JsonObject
493 # assert col.update(sel, upd)
495 fun update
(selector
: JsonObject, update
: JsonObject): Bool do
496 return native
.update
(
497 selector
.to_bson
.native
,
498 update
.to_bson
.native
)
501 # Updates all documents matching the `selector`.
504 fun update_all
(selector
: JsonObject, update
: JsonObject): Bool do
505 return native
.update_all
(
506 selector
.to_bson
.native
,
507 update
.to_bson
.native
)
510 # Counts the document matching `query`.
512 # Returns `-1` if an error occured. See `Sys::last_mongoc_error`.
515 # var client = new MongoClient("mongodb://localhost:27017/")
516 # var col = client.database("test").collection("test")
517 # var query = new JsonObject
519 # assert col.count(query) > 0
521 fun count
(query
: JsonObject): Int do
522 return native
.count
(query
.to_bson
.native
)
525 # Finds the first document that matches `query`.
527 # Returns `null` if an error occured. See `Sys::last_mongoc_error`.
530 # var client = new MongoClient("mongodb://localhost:27017/")
531 # var col = client.database("test").collection("test")
532 # var query = new JsonObject
534 # var doc = col.find(query)
535 # assert doc["foo"] == 10
537 fun find
(query
: JsonObject): nullable JsonObject do
538 var q
= new NativeBSON.from_json_string
(query
.to_json
.to_cstring
)
539 var c
= native
.find
(q
)
541 if c
== null then return null
542 var cursor
= new MongoCursor(c
)
543 if not cursor
.is_ok
then
546 var item
= cursor
.item
547 assert cursor
!= self
551 # Finds all the documents matching the `query`.
554 # var client = new MongoClient("mongodb://localhost:27017/")
555 # var col = client.database("test").collection("test")
556 # var query = new JsonObject
558 # assert col.find_all(query).length > 0
560 fun find_all
(query
: JsonObject): Array[JsonObject] do
561 var res
= new Array[JsonObject]
562 var c
= native
.find
(query
.to_bson
.native
)
563 if c
== null then return res
564 var cursor
= new MongoCursor(c
)
565 for item
in cursor
do res
.add item
569 # Retrieves statistics about the collection.
571 # Returns `null` if an error occured. See `Sys::last_mongoc_error`.
574 # var client = new MongoClient("mongodb://localhost:27017/")
575 # var col = client.database("test").collection("test")
576 # assert col.stats["ns"] == "test.test"
578 fun stats
: nullable JsonObject do
579 var bson
= native
.stats
580 if bson
== null then return null
581 return new JsonObject.from_bson
(new BSON(bson
))
584 # Drops `self`, returns false if an error occured.
585 fun drop
: Bool do return native
.drop
587 # Moves `self` to another `database`.
589 # The database will also be updated internally so it is safe to continue using
590 # this collection after the move.
591 # Additional operations will occur on moved collection.
592 fun move
(database
: MongoDb): Bool do
593 self.database
= database
594 return native
.rename
(database
.name
.to_cstring
, name
.to_cstring
)
599 # The name of the collection will also be updated internally so it is safe
600 # to continue using this collection after the rename.
601 # Additional operations will occur on renamed collection.
602 fun rename
(name
: String): Bool do
604 return native
.rename
(database
.name
.to_cstring
, name
.to_cstring
)
607 redef fun finalize_once
do native
.destroy
610 # A MongoDB query cursor.
612 # It wraps up the wire protocol negotation required to initiate a query and
613 # retreive an unknown number of documents.
615 super FinalizableOnce
616 super Iterator[JsonObject]
618 private var native
: NativeMongoCursor
622 redef fun is_ok
do return native
.more
624 redef fun next
do native
.next
627 return new JsonObject.from_bson
(new BSON(native
.current
))
630 redef fun finalize_once
do native
.destroy