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 # Is the native instance valid?
65 # This is set to false if the `native` is destroyed.
68 # Returns a new BSON object initialized from the content of `json`.
71 # intrude import mongodb
72 # var obj = new JsonObject
74 # obj["name"] = "Rick"
75 # obj["ELS"] = new JsonArray
76 # var bson = new BSON.from_json(obj)
77 # assert bson.to_s == """{ "age" : 10, "name" : "Rick", "ELS" : [ ] }"""
79 init from_json
(json
: JsonObject) do
80 init(new NativeBSON.from_json_string
(json
.to_json
.to_cstring
))
83 # Returns a new BSON object parsed from `json_string`.
85 # If `json_string` is not a valid JSON string, this initializer returns NULL.
88 # intrude import mongodb
89 # var str = """{ "age" : 10, "name" : "Rick", "ELS" : [ ] }"""
90 # var bson = new BSON.from_json_string(str)
91 # assert bson.to_s == str
93 init from_json_string
(json_string
: String) do
94 init(new NativeBSON.from_json_string
(json_string
.to_cstring
))
99 var ns
= native
.to_native_string
100 var res
= ns
.to_s_with_copy
101 ns
.free
# manual free of gc allocated NativeString
105 # Returns a new JsonObject from `self`.
108 # intrude import mongodb
109 # var str = """{ "age" : 10, "name" : "Rick", "ELS" : [ ] }"""
110 # var bson = new BSON.from_json_string(str)
111 # var json = bson.to_json
112 # assert json["age"] == 10
113 # assert json["name"] == "Rick"
114 # assert json["ELS"].as(JsonArray).is_empty
116 fun to_json
: JsonObject do
118 return to_s
.parse_json
.as(JsonObject)
121 redef fun finalize
do
129 redef class JsonObject
130 # Inits `self` from a BSON object.
131 private init from_bson
(bson
: BSON) do recover_with
(bson
.to_json
)
133 # Returns a new BSON object from `self`.
134 private fun to_bson
: BSON do return new BSON.from_json
(self)
137 # An error returned by the mongoc client.
139 # Within the client, if a method returns `false` or `null` it's more likely that
140 # an error occured during the execution.
142 # See `MongoClient::last_error`.
145 private var native
: BSONError
147 # Is the native instance valid?
149 # This is set to false if the `native` is destroyed.
150 private var is_alive
= true
152 # Logical domain within a library that created the error.
158 # Domain specific error code.
164 # Human readable error message.
165 fun message
: String do
167 var ns
= native
.message
168 var res
= ns
.to_s_with_copy
173 redef fun to_s
do return "{message} (code: {code})"
176 # MongoDB Object ID representation.
178 # For ObjectIDs, MongoDB uses the `ObjectId("hash")` notation.
179 # This notation is replicated by the `to_s` service.
181 # Since the MongoDB notation is not JSON complient, the mongoc wrapper uses
182 # a JSON based notation like `{"$oid": "hash"}`.
183 # This is the notation returned by the `to_json` service.
184 private class MongoObjectId
186 var native
: BSONObjectId
188 # The unique ID as an MongoDB Object ID string.
189 fun id
: String do return native
.id
191 # Internal JSON representation of this Object ID.
193 # Something like `{"$oid": "5578e5dcf344225cc2378051"}`.
194 fun to_json
: JsonObject do
195 var obj
= new JsonObject
200 # Formatted as `ObjectId("5578e5dcf344225cc2378051")`
201 redef fun to_s
do return "ObjectId({id})"
204 # The MongoClient is used to connect to the mongo server and send queries.
209 # var uri = "mongodb://localhost:27017/"
210 # var client = new MongoClient(uri)
211 # assert client.server_uri == uri
217 var server_uri
: String
219 private var native
: NativeMongoClient is noinit
221 # Is the native instance valid?
223 # This is set to false if the `native` is destroyed.
224 private var is_alive
= true
227 native
= new NativeMongoClient(server_uri
.to_cstring
)
232 # Returns `null` if an error occured. See `last_error`.
235 # var client = new MongoClient("mongodb://localhost:27017/")
236 # assert client.server_status["process"] == "mongod"
238 fun server_status
: nullable JsonObject do
240 var nbson
= native
.server_status
241 if nbson
== null then return null
242 var bson
= new BSON(nbson
)
243 var res
= new JsonObject.from_bson
(bson
)
247 # Lists available database names.
250 # var client = new MongoClient("mongodb://localhost:27017/")
251 # var db = client.database("test")
252 # db.collection("test").insert(new JsonObject)
253 # assert client.database_names.has("test")
255 fun database_names
: Array[String] do
257 var res
= new Array[String]
258 var nas
= native
.database_names
259 if nas
== null then return res
262 while not name
.address_is_null
do
263 res
.add name
.to_s_with_copy
271 # Loads or creates a database from its `name`.
273 # Database are automatically created on the MongoDB server upon insertion of
274 # the first document into a collection.
275 # There is no need to create a database manually.
278 # var client = new MongoClient("mongodb://localhost:27017/")
279 # assert client.database("test").name == "test"
281 fun database
(name
: String): MongoDb do
283 return new MongoDb(self, name
)
286 # Close the connexion and destroy the instance.
288 # The reference should not be used beyond this point!
294 redef fun finalize
do
301 # Last error raised by mongoc.
302 fun last_error
: nullable MongoError do
303 var last_error
= sys
.last_mongoc_error
304 if last_error
== null then return null
305 return new MongoError(last_error
)
308 # Last auto generated id.
309 private fun last_id
: nullable MongoObjectId do
310 var last_id
= sys
.last_mongoc_id
311 if last_id
== null then return null
312 return new MongoObjectId(last_id
)
315 # Set the last generated id or `null` to unset once used.
316 private fun last_id
=(id
: nullable MongoObjectId) do
318 sys
.last_mongoc_id
= null
320 sys
.last_mongoc_id
= id
.native
325 # A MongoDb database.
327 # Database are automatically created on the MongoDB server upon insertion of the
328 # first document into a collection.
329 # There is no need to create a database manually.
333 # `MongoClient` used to load this database.
334 var client
: MongoClient
339 private var native
: NativeMongoDb is noinit
341 # Is the native instance valid?
343 # This is set to false if the `native` is destroyed.
344 private var is_alive
= true
347 native
= new NativeMongoDb(client
.native
, name
.to_cstring
)
350 # Lists available collection names.
352 # Returns `null` if an error occured. See `Sys::last_mongoc_error`.
355 # var client = new MongoClient("mongodb://localhost:27017/")
356 # var db = client.database("test")
357 # db.collection("test").insert(new JsonObject)
358 # assert db.collection_names.has("test")
360 fun collection_names
: Array[String] do
362 var res
= new Array[String]
363 var nas
= native
.collection_names
364 if nas
== null then return res
367 while not name
.address_is_null
do
368 res
.add name
.to_s_with_copy
376 # Loads or creates a collection by its `name`.
379 # var client = new MongoClient("mongodb://localhost:27017/")
380 # var db = client.database("test")
381 # var col = db.collection("test")
382 # assert col.name == "test"
384 fun collection
(name
: String): MongoCollection do
386 return new MongoCollection(self, name
)
389 # Checks if a collection named `name` exists.
392 # var client = new MongoClient("mongodb://localhost:27017/")
393 # var db = client.database("test")
394 # assert not db.has_collection("qwerty")
396 fun has_collection
(name
: String): Bool do
399 return native
.has_collection
(name
.to_cstring
)
402 # Drop `self`, returns false if an error occured.
408 redef fun finalize
do
416 # A Mongo collection.
418 # Collections are automatically created on the MongoDB server upon insertion of
419 # the first document.
420 # There is no need to create a database manually.
421 class MongoCollection
424 # Database that collection belongs to.
425 var database
: MongoDb
427 # Name of this collection.
430 private var native
: NativeMongoCollection is noinit
432 # Is the native instance valid?
434 # This is set to false if the `native` is destroyed.
435 private var is_alive
= true
437 # Loads a collection.
439 # Call `MongoDb::collection` instead.
441 native
= new NativeMongoCollection(
442 database
.client
.native
,
443 database
.name
.to_cstring
,
447 # Set the autogenerated last id if the `doc` does not contain one already.
448 private fun set_id
(doc
: JsonObject) do
449 var last_id
= database
.client
.last_id
450 if last_id
!= null then
451 doc
["_id"] = last_id
.to_json
452 database
.client
.last_id
= null
456 # Inserts a new document in the collection.
458 # If no _id element is found in document, then a new one be generated locally
459 # and added to the document.
461 # Returns `false` if an error occured. See `Sys::last_mongoc_error`.
464 # var client = new MongoClient("mongodb://localhost:27017/")
465 # var col = client.database("test").collection("test")
466 # var doc = new JsonObject
469 # doc["baz"] = new JsonArray
470 # assert col.insert(doc)
471 # assert doc.has_key("_id")
473 fun insert
(doc
: JsonObject): Bool do
475 var res
= native
.insert
(doc
.to_bson
.native
)
476 if res
then set_id
(doc
)
480 # Inserts multiple documents in the collection.
483 fun insert_all
(docs
: Collection[JsonObject]): Bool do
486 for doc
in docs
do res
= insert
(doc
) and res
490 # Saves a new document in the collection.
492 # If the document has an `_id` field it will be updated.
493 # Otherwise it will be inserted.
495 # Returns `false` if an error occured. See `Sys::last_mongoc_error`.
498 # var client = new MongoClient("mongodb://localhost:27017/")
499 # var col = client.database("test").collection("test")
501 # var doc = new JsonObject
504 # doc["baz"] = new JsonArray
506 # assert col.save(doc) # will be inserted
507 # assert doc.has_key("_id")
509 # var id = doc["_id"]
510 # assert col.save(doc) # will be updated
511 # assert doc["_id"] == id
513 fun save
(doc
: JsonObject): Bool do
515 var res
= native
.save
(doc
.to_bson
.native
)
516 if res
then set_id
(doc
)
520 # Removes the first document that matches `selector`.
522 # Returns `false` if an error occured. See `Sys::last_mongoc_error`.
525 # var client = new MongoClient("mongodb://localhost:27017/")
526 # var col = client.database("test").collection("test")
527 # var sel = new JsonObject
529 # assert col.remove(sel)
531 fun remove
(selector
: JsonObject): Bool do
533 return native
.remove
(selector
.to_bson
.native
)
536 # Removes all the document that match `selector`.
539 fun remove_all
(selector
: JsonObject): Bool do
541 return native
.remove_all
(selector
.to_bson
.native
)
544 # Updates a document already existing in the collection.
546 # No upsert is done, see `save` instead.
549 # var client = new MongoClient("mongodb://localhost:27017/")
550 # var col = client.database("test").collection("test")
551 # var sel = new JsonObject
553 # var upd = new JsonObject
555 # assert col.update(sel, upd)
557 fun update
(selector
: JsonObject, update
: JsonObject): Bool do
559 return native
.update
(
560 selector
.to_bson
.native
,
561 update
.to_bson
.native
)
564 # Updates all documents matching the `selector`.
567 fun update_all
(selector
: JsonObject, update
: JsonObject): Bool do
568 return native
.update_all
(
569 selector
.to_bson
.native
,
570 update
.to_bson
.native
)
573 # Counts the document matching `query`.
575 # Returns `-1` if an error occured. See `Sys::last_mongoc_error`.
578 # var client = new MongoClient("mongodb://localhost:27017/")
579 # var col = client.database("test").collection("test")
580 # var query = new JsonObject
582 # assert col.count(query) > 0
584 fun count
(query
: JsonObject): Int do
586 return native
.count
(query
.to_bson
.native
)
589 # Finds the first document that matches `query`.
591 # Returns `null` if an error occured. See `Sys::last_mongoc_error`.
594 # var client = new MongoClient("mongodb://localhost:27017/")
595 # var col = client.database("test").collection("test")
596 # var query = new JsonObject
598 # var doc = col.find(query)
599 # assert doc["foo"] == 10
601 fun find
(query
: JsonObject): nullable JsonObject do
603 var c
= native
.find
(query
.to_bson
.native
)
604 assert is_alive
# FIXME used to avoid segfault (so `self` isn't garbage collected to soon)
605 if c
== null then return null
606 var cursor
= new MongoCursor(c
)
614 # Finds all the documents matching the `query`.
617 # var client = new MongoClient("mongodb://localhost:27017/")
618 # var col = client.database("test").collection("test")
619 # var query = new JsonObject
621 # assert col.find_all(query).length > 0
623 fun find_all
(query
: JsonObject): Array[JsonObject] do
625 var res
= new Array[JsonObject]
626 var c
= native
.find
(query
.to_bson
.native
)
627 if c
== null then return res
628 var cursor
= new MongoCursor(c
)
629 for item
in cursor
do res
.add item
633 # Retrieves statistics about the collection.
635 # Returns `null` if an error occured. See `Sys::last_mongoc_error`.
638 # var client = new MongoClient("mongodb://localhost:27017/")
639 # var col = client.database("test").collection("test")
640 # assert col.stats["ns"] == "test.test"
642 fun stats
: nullable JsonObject do
644 var bson
= native
.stats
645 if bson
== null then return null
646 return new JsonObject.from_bson
(new BSON(bson
))
649 # Drops `self`, returns false if an error occured.
655 # Moves `self` to another `database`.
657 # The database will also be updated internally so it is safe to continue using
658 # this collection after the move.
659 # Additional operations will occur on moved collection.
660 fun move
(database
: MongoDb): Bool do
662 self.database
= database
663 return native
.rename
(database
.name
.to_cstring
, name
.to_cstring
)
668 # The name of the collection will also be updated internally so it is safe
669 # to continue using this collection after the rename.
670 # Additional operations will occur on renamed collection.
671 fun rename
(name
: String): Bool do
674 return native
.rename
(database
.name
.to_cstring
, name
.to_cstring
)
677 redef fun finalize
do
685 # A MongoDB query cursor.
687 # It wraps up the wire protocol negotation required to initiate a query and
688 # retreive an unknown number of documents.
691 super Iterator[JsonObject]
693 private var native
: NativeMongoCursor
695 # Is the native instance valid?
697 # This is set to false if the `native` is destroyed.
698 private var is_alive
= true
714 return new JsonObject.from_bson
(new BSON(native
.current
))
717 redef fun finalize
do