backend.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. """Event Man(ager) database backend
  2. Classes and functions used to manage events and attendees database.
  3. Copyright 2015 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 pymongo
  15. from bson.objectid import ObjectId
  16. class EventManDB(object):
  17. """MongoDB connector."""
  18. db = None
  19. connection = None
  20. def __init__(self, url=None, dbName='eventman'):
  21. """Initialize the instance, connecting to the database.
  22. :param url: URL of the database
  23. :type url: str (or None to connect to localhost)
  24. """
  25. self._url = url
  26. self._dbName = dbName
  27. self.connect(url)
  28. def connect(self, url=None, dbName=None):
  29. """Connect to the database.
  30. :param url: URL of the database
  31. :type url: str (or None to connect to localhost)
  32. :return: the database we're connected to
  33. :rtype: :class:`~pymongo.database.Database`
  34. """
  35. if self.db is not None:
  36. return self.db
  37. if url:
  38. self._url = url
  39. if dbName:
  40. self._dbName = dbName
  41. self.connection = pymongo.MongoClient(self._url)
  42. self.db = self.connection[self._dbName]
  43. return self.db
  44. def toID(self, _id):
  45. """Convert a string to a MongoDB ID.
  46. :param _id: string to convert to :class:`~bson.objectid.ObjectId`
  47. :type _id: str
  48. :return: MongoDB ID
  49. :rtype: :class:`~bson.objectid.ObjectId`
  50. """
  51. if not isinstance(_id, ObjectId):
  52. _id = ObjectId(_id)
  53. return _id
  54. def get(self, collection, _id):
  55. """Get a single document with the specified `_id`.
  56. :param collection: search the document in this collection
  57. :type collection: str
  58. :param _id: unique ID of the document
  59. :type _id: str or :class:`~bson.objectid.ObjectId`
  60. :return: the document with the given `_id`
  61. :rtype: dict
  62. """
  63. _id = self.toID(_id)
  64. results = self.query(collection, {'_id': _id})
  65. return results and results[0] or {}
  66. def query(self, collection, query=None):
  67. """Get multiple documents matching a query.
  68. :param collection: search for documents in this collection
  69. :type collection: str
  70. :param query: search for documents with those attributes
  71. :type query: dict or None
  72. :return: list of matching documents
  73. :rtype: list
  74. """
  75. db = self.connect()
  76. query = query or {}
  77. if'_id' in query:
  78. query['_id'] = self.toID(query['_id'])
  79. results = list(db[collection].find(query))
  80. for result in results:
  81. result['_id'] = str(result['_id'])
  82. return results
  83. def add(self, collection, data):
  84. """Insert a new document.
  85. :param collection: insert the document in this collection
  86. :type collection: str
  87. :param data: the document to store
  88. :type data: dict
  89. :return: the document, as created in the database
  90. :rtype: dict
  91. """
  92. db = self.connect()
  93. _id = db[collection].insert(data)
  94. return self.get(collection, _id)
  95. def insertOne(self, collection, data):
  96. """Insert a document, avoiding duplicates.
  97. :param collection: update a document in this collection
  98. :type collection: str
  99. :param data: the document information to store
  100. :type data: dict
  101. :return: True if the document was already present
  102. :rtype: bool
  103. """
  104. db = self.connect()
  105. ret = db[collection].update(data, {'$set': data}, upsert=True)
  106. return ret['updatedExisting']
  107. def update(self, collection, _id_or_query, data, operator='$set', create=True):
  108. """Update an existing document.
  109. :param collection: update a document in this collection
  110. :type collection: str
  111. :param _id: unique ID of the document to be updated
  112. :type _id: str or :class:`~bson.objectid.ObjectId`
  113. :param data: the updated information to store
  114. :type data: dict
  115. :return: the document, after the update
  116. :rtype: dict
  117. """
  118. db = self.connect()
  119. data = data or {}
  120. if _id_or_query is None:
  121. _id_or_query = {'_id': None}
  122. elif isinstance(_id_or_query, (list, tuple)):
  123. _id_or_query = {'$or': self.buildSearchPattern(data, _id_or_query)}
  124. elif not isinstance(_id_or_query, dict):
  125. _id_or_query = {'_id': self.toID(_id_or_query)}
  126. if '_id' in data:
  127. del data['_id']
  128. res = db[collection].find_and_modify(query=_id_or_query,
  129. update={operator: data}, full_response=True, new=True, upsert=create)
  130. lastErrorObject = res.get('lastErrorObject') or {}
  131. return lastErrorObject.get('updatedExisting', False), res.get('value') or {}
  132. def buildSearchPattern(self, data, searchBy):
  133. _or = []
  134. for searchPattern in searchBy:
  135. try:
  136. _or.append(dict([(k, data[k]) for k in searchPattern]))
  137. except KeyError:
  138. continue
  139. return _or
  140. def merge(self, collection, data, searchBy, operator='$set'):
  141. """Update an existing document.
  142. :param collection: update a document in this collection
  143. :type collection: str
  144. :param data: the document to store or merge with an existing one
  145. :type data: dict
  146. :return: a tuple with a boolean (True if an existing document was updated, and the _id of the document)
  147. :rtype: tuple
  148. """
  149. db = self.connect()
  150. _or = []
  151. for searchPattern in searchBy:
  152. try:
  153. _or.append(dict([(k, data[k]) for k in searchPattern]))
  154. except KeyError:
  155. continue
  156. if not _or:
  157. return False, None
  158. # Two-steps merge/find to count the number of merged documents
  159. ret = db[collection].update({'$or': _or}, {operator: data}, upsert=True)
  160. _id = ret.get('upserted')
  161. if _id is None:
  162. newDoc = db[collection].find_one(data)
  163. if newDoc:
  164. _id = newDoc['_id']
  165. return ret['updatedExisting'], _id
  166. def delete(self, collection, _id_or_query=None, force=False):
  167. """Remove one or more documents from a collection.
  168. :param collection: search the documents in this collection
  169. :type collection: str
  170. :param _id_or_query: unique ID of the document or query to match multiple documents
  171. :type _id_or_query: str or :class:`~bson.objectid.ObjectId` or dict
  172. :param force: force the deletion of all documents, when `_id_or_query` is empty
  173. :type force: bool
  174. """
  175. if not _id_or_query and not force:
  176. return
  177. db = self.connect()
  178. if not isinstance(_id_or_query, dict):
  179. _id_or_query = self.toID(_id_or_query)
  180. db[collection].remove(_id_or_query)