monco.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. """Monco: a MongoDB database backend
  2. Classes and functions used to issue queries to a MongoDB database.
  3. Copyright 2016-2017 Davide Alberani <da@erlug.linux.it>
  4. RaspiBO <info@raspibo.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 http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. """
  14. import re
  15. import pymongo
  16. from bson.objectid import ObjectId
  17. re_objectid = re.compile(r'[0-9a-f]{24}')
  18. _force_conversion = {
  19. '_id': ObjectId,
  20. 'seq_hex': str,
  21. 'tickets.seq_hex': str
  22. }
  23. def convert_obj(obj):
  24. """Convert an object in a format suitable to be stored in MongoDB.
  25. :param obj: object to convert
  26. :returns: object that can be stored in MongoDB.
  27. """
  28. if obj is None:
  29. return None
  30. if isinstance(obj, bool):
  31. return obj
  32. try:
  33. if re_objectid.match(obj):
  34. return ObjectId(obj)
  35. except:
  36. pass
  37. return obj
  38. def convert(seq):
  39. """Convert an object to a format suitable to be stored in MongoDB,
  40. descending lists, tuples and dictionaries (a copy is returned).
  41. :param seq: sequence or object to convert
  42. :returns: object that can be stored in MongoDB.
  43. """
  44. if isinstance(seq, dict):
  45. d = {}
  46. for key, item in seq.items():
  47. if key in _force_conversion:
  48. try:
  49. d[key] = _force_conversion[key](item)
  50. except:
  51. d[key] = item
  52. else:
  53. d[key] = convert(item)
  54. return d
  55. if isinstance(seq, (list, tuple)):
  56. return [convert(x) for x in seq]
  57. return convert_obj(seq)
  58. class MoncoError(Exception):
  59. """Base class for Monco exceptions."""
  60. pass
  61. class MoncoConnectionError(MoncoError):
  62. """Monco exceptions raise when a connection problem occurs."""
  63. pass
  64. class Monco(object):
  65. """MongoDB connector."""
  66. db = None
  67. connection = None
  68. # map operations on lists of items.
  69. _operations = {
  70. 'update': '$set',
  71. 'append': '$push',
  72. 'appendUnique': '$addToSet',
  73. 'delete': '$pull',
  74. 'increment': '$inc'
  75. }
  76. def __init__(self, dbName, url=None):
  77. """Initialize the instance, connecting to the database.
  78. :param dbName: name of the database
  79. :type dbName: str (or None to use the dbName passed at initialization)
  80. :param url: URL of the database
  81. :type url: str (or None to connect to localhost)
  82. """
  83. self._url = url
  84. self._dbName = dbName
  85. self.connect(url)
  86. def connect(self, dbName=None, url=None):
  87. """Connect to the database.
  88. :param dbName: name of the database
  89. :type dbName: str (or None to use the dbName passed at initialization)
  90. :param url: URL of the database
  91. :type url: str (or None to connect to localhost)
  92. :returns: the database we're connected to
  93. :rtype: :class:`~pymongo.database.Database`
  94. """
  95. if self.db is not None:
  96. return self.db
  97. if url:
  98. self._url = url
  99. if dbName:
  100. self._dbName = dbName
  101. if not self._dbName:
  102. raise MoncoConnectionError('no database name specified')
  103. self.connection = pymongo.MongoClient(self._url)
  104. self.db = self.connection[self._dbName]
  105. return self.db
  106. def getOne(self, collection, query=None):
  107. """Get a single document with the specified `query`.
  108. :param collection: search the document in this collection
  109. :type collection: str
  110. :param query: query to filter the documents
  111. :type query: dict or None
  112. :returns: the first document matching the query
  113. :rtype: dict
  114. """
  115. results = self.query(collection, convert(query))
  116. return results and results[0] or {}
  117. def get(self, collection, _id):
  118. """Get a single document with the specified `_id`.
  119. :param collection: search the document in this collection
  120. :type collection: str
  121. :param _id: unique ID of the document
  122. :type _id: str or :class:`~bson.objectid.ObjectId`
  123. :returns: the document with the given `_id`
  124. :rtype: dict
  125. """
  126. return self.getOne(collection, {'_id': _id})
  127. def query(self, collection, query=None, condition='or'):
  128. """Get multiple documents matching a query.
  129. :param collection: search for documents in this collection
  130. :type collection: str
  131. :param query: search for documents with those attributes
  132. :type query: dict, list or None
  133. :returns: list of matching documents
  134. :rtype: list
  135. """
  136. db = self.connect()
  137. query = convert(query or {})
  138. if isinstance(query, (list, tuple)):
  139. query = {'$%s' % condition: query}
  140. return list(db[collection].find(query))
  141. def add(self, collection, data, _id=None):
  142. """Insert a new document.
  143. :param collection: insert the document in this collection
  144. :type collection: str
  145. :param data: the document to store
  146. :type data: dict
  147. :param _id: the _id of the document to store; if None, it's generated
  148. :type _id: object
  149. :returns: the document, as created in the database
  150. :rtype: dict
  151. """
  152. db = self.connect()
  153. data = convert(data)
  154. if _id is not None:
  155. data['_id'] = _id
  156. _id = db[collection].insert(data)
  157. return self.get(collection, _id)
  158. def insertOne(self, collection, data):
  159. """Insert a document, avoiding duplicates.
  160. :param collection: update a document in this collection
  161. :type collection: str
  162. :param data: the document information to store
  163. :type data: dict
  164. :returns: True if the document was already present
  165. :rtype: bool
  166. """
  167. db = self.connect()
  168. data = convert(data)
  169. ret = db[collection].update(data, {'$set': data}, upsert=True)
  170. return ret['updatedExisting']
  171. def _buildSearchPattern(self, data, searchBy):
  172. """Return an OR condition."""
  173. _or = []
  174. for searchPattern in searchBy:
  175. try:
  176. _or.append(dict([(k, data[k]) for k in searchPattern if k in data]))
  177. except KeyError:
  178. continue
  179. return _or
  180. def update(self, collection, _id_or_query, data, operation='update',
  181. updateList=None, create=True):
  182. """Update an existing document or create it, if requested.
  183. _id_or_query can be an ID, a dict representing a query or a list of tuples.
  184. In the latter case, the tuples are put in OR; a tuple match if all of its
  185. items from 'data' are contained in the document.
  186. :param collection: update a document in this collection
  187. :type collection: str
  188. :param _id_or_query: ID of the document to be updated, or a query or a list of attributes in the data that must match
  189. :type _id_or_query: str or :class:`~bson.objectid.ObjectId` or iterable
  190. :param data: the updated information to store
  191. :type data: dict
  192. :param operation: operation used to update the document or a portion of it, like a list (update, append, appendUnique, delete, increment)
  193. :type operation: str
  194. :param updateList: if set, it's considered the name of a list (the first matching element will be updated)
  195. :type updateList: str
  196. :param create: if True, the document is created if no document matches
  197. :type create: bool
  198. :returns: a boolean (True if an existing document was updated) and the document after the update
  199. :rtype: tuple of (bool, dict)
  200. """
  201. db = self.connect()
  202. data = convert(data or {})
  203. _id_or_query = convert(_id_or_query)
  204. if isinstance(_id_or_query, (list, tuple)):
  205. _id_or_query = {'$or': self._buildSearchPattern(data, _id_or_query)}
  206. elif not isinstance(_id_or_query, dict):
  207. _id_or_query = {'_id': _id_or_query}
  208. if '_id' in data:
  209. del data['_id']
  210. operator = self._operations.get(operation)
  211. if updateList:
  212. newData = {}
  213. for key, value in data.items():
  214. newData['%s.$.%s' % (updateList, key)] = value
  215. data = newData
  216. res = db[collection].find_and_modify(query=_id_or_query,
  217. update={operator: data}, full_response=True, new=True, upsert=create)
  218. lastErrorObject = res.get('lastErrorObject') or {}
  219. return lastErrorObject.get('updatedExisting', False), res.get('value') or {}
  220. def updateMany(self, collection, query, data):
  221. """Update multiple existing documents.
  222. query can be an ID or a dict representing a query.
  223. :param collection: update documents in this collection
  224. :type collection: str
  225. :param query: a query or a list of attributes in the data that must match
  226. :type query: str or :class:`~bson.objectid.ObjectId` or iterable
  227. :param data: the updated information to store
  228. :type data: dict
  229. :returns: a dict with the success state and number of updated items
  230. :rtype: dict
  231. """
  232. db = self.connect()
  233. data = convert(data or {})
  234. query = convert(query)
  235. if not isinstance(query, dict):
  236. query = {'_id': query}
  237. if '_id' in data:
  238. del data['_id']
  239. return db[collection].update(query, {'$set': data}, multi=True)
  240. def delete(self, collection, _id_or_query=None, force=False):
  241. """Remove one or more documents from a collection.
  242. :param collection: search the documents in this collection
  243. :type collection: str
  244. :param _id_or_query: unique ID of the document or query to match multiple documents
  245. :type _id_or_query: str or :class:`~bson.objectid.ObjectId` or dict
  246. :param force: force the deletion of all documents, when `_id_or_query` is empty
  247. :type force: bool
  248. :returns: dictionary with the number or removed documents
  249. :rtype: dict
  250. """
  251. if not _id_or_query and not force:
  252. return
  253. db = self.connect()
  254. if not isinstance(_id_or_query, dict):
  255. _id_or_query = {'_id': _id_or_query}
  256. _id_or_query = convert(_id_or_query)
  257. return db[collection].remove(_id_or_query)