예제 #1
0
    def __init__(self, id=None, save=True):
        """ Constructor. Note: the object is being saved
        during the creation process.
        :param id: the id of the object to load
        :param save: if the object has to be saved, use only for temporary
            objects (you'll not be able to save it after the instantiation)
        :raise: IrmaDatabaseError, IrmaLockError, IrmaValueError
        """
        if type(self) is NoSQLDatabaseObject:
            reason = "The NoSQLDatabaseObject class has to be overloaded"
            raise IrmaValueError(reason)
        # transient (see _transient_attributes and to_dict)
        self._is_instance_transient = not save

        # create a new object or load an existing one with id
        # raise IrmaDatabaseError on loading invalid id
        self._id = None
        self._temp_id = None
        if id:
            try:
                self._id = ObjectId(id)
                # transient (see _transient_attributes and to_dict)
                self._temp_id = self._id
                self.load(self._id)
            except InvalidId as e:
                raise IrmaDatabaseError("{0}".format(e))
        elif save:
            self._save()
예제 #2
0
 def _connect(self):
     if self._db_conn:
         log.warn("Already connected to database")
     try:
         self._db_conn = MongoClient(self._db_uri)
     except Exception as e:
         raise IrmaDatabaseError("{0}".format(e))
예제 #3
0
 def remove(self, db_name, collection_name, _id):
     """ Delete entry in collection according to the given id"""
     collection = self._table(db_name, collection_name)
     try:
         collection.remove({'_id': _id})
     except Exception as e:
         raise IrmaDatabaseError("{0}".format(e))
예제 #4
0
 def _database(self, db_name):
     if db_name not in self._db_cache:
         try:
             self._db_cache[db_name] = self._db_conn[db_name]
         except Exception as e:
             raise IrmaDatabaseError("{0}".format(e))
     return self._db_cache[db_name]
예제 #5
0
 def get_session(cls):
     """Return a session
     :rtype: scoped_session
     :raise IrmaDatabaseError: if the engine is None
     """
     if cls.__engine is None:
         raise IrmaDatabaseError('the engine has to be connected first')
     return cls.__Session()
예제 #6
0
 def save(self, db_name, collection_name, dict_object):
     """ save entry in collection"""
     collection = self._table(db_name, collection_name)
     try:
         _id = collection.save(dict_object)
         return _id
     except Exception as e:
         raise IrmaDatabaseError("{0}".format(e))
예제 #7
0
 def get_engine(cls):
     """Return the engine
     :rtype: engine
     :raise IrmaDatabaseError: if the engine is None
     """
     if cls.__engine is None:
         raise IrmaDatabaseError('the engine has to be connected first')
     return cls.__engine
예제 #8
0
 def delete_file(self, db_name, collection_name, file_oid):
     """ delete from gridfs by file object-id """
     fsdbh = gridfs.GridFS(self._database(db_name),
                           collection=collection_name)
     try:
         return fsdbh.delete(file_oid)
     except Exception as e:
         raise IrmaDatabaseError("{0}".format(e))
예제 #9
0
 def exists(self, db_name, collection_name, _id):
     """ check if entry with _id is in collection"""
     collection = self._table(db_name, collection_name)
     try:
         res = collection.find_one({'_id': _id})
         return res is not None
     except Exception as e:
         raise IrmaDatabaseError("{0}".format(e))
예제 #10
0
 def load(self, db_name, collection_name, _id):
     """ load entry _id in collection"""
     collection = self._table(db_name, collection_name)
     try:
         res = collection.find_one({'_id': _id})
         return res
     except Exception as e:
         raise IrmaDatabaseError("{0}".format(e))
예제 #11
0
 def _disconnect(self):
     if not self._db_conn:
         return
     try:
         self._db_conn.close()
         self._db_conn = None
         self._db_cache = dict()
         self._coll_cache = dict()
     except Exception as e:
         raise IrmaDatabaseError("{0}".format(e))
예제 #12
0
 def put_file(self, db_name, collection_name, data, name):
     """ put data into gridfs """
     fsdbh = gridfs.GridFS(self._database(db_name),
                           collection=collection_name)
     # create a new record
     try:
         file_oid = fsdbh.put(data, filename=name)
         return file_oid
     except Exception as e:
         raise IrmaDatabaseError("{0}".format(e))
예제 #13
0
 def update(self, db_name, collection_name, _id, update_dict):
     """
     Update entries in collection according to
     the dictionnary specified
     """
     collection = self._table(db_name, collection_name)
     try:
         collection.update({"_id": _id}, {"$set": update_dict})
     except Exception as e:
         raise IrmaDatabaseError("{0}".format(e))
예제 #14
0
 def _table(self, db_name, coll_name):
     database = self._database(db_name)
     # TODO: Fix collision if two tables
     # from different databases have the same name
     if coll_name not in self._coll_cache:
         try:
             self._coll_cache[coll_name] = database[coll_name]
         except Exception as e:
             raise IrmaDatabaseError("{0}".format(e))
     return self._coll_cache[coll_name]
예제 #15
0
 def load(self, _id):
     self._id = _id
     db = NoSQLDatabase(self._dbname, self._uri)
     dict_object = db.load(self._dbname, self._collection, self._id)
     # dict_object could be empty if we init a dbobject with a given id
     if dict_object:
         self.from_dict(dict_object)
         self._temp_id = self._id
     else:
         raise IrmaDatabaseError("id not present in collection")
     return
예제 #16
0
 def find_by_id(cls, id, session):
     """Find the object in the database
     :param id: the id to look for
     :param session: the session to use
     :rtype: cls
     :return: the object that corresponds to the id
     :raise IrmaDatabaseResultNotFound, IrmaDatabaseError
     """
     try:
         return session.query(cls).filter(cls.id == id).one()
     except NoResultFound as e:
         raise IrmaDatabaseResultNotFound(e)
     except MultipleResultsFound as e:
         raise IrmaDatabaseError(e)
예제 #17
0
    def find(self, db_name, collection_name, *args, **kwargs):
        """ Returns elements from the collection according to the given query

        :param db_name: The database
        :param collection_name: The name of the collection
        :param *args **kwargs: see
            http://api.mongodb.org/python/current/api/pymongo/collection.html#\
            pymongo.collection.Collection.find
            and http://docs.mongodb.org/manual/tutorial/query-documents/
        :rtype: cursor, see http://api.mongodb.org/python/current/api/pymongo/\
        cursor.html#pymongo.cursor.Cursor
                and http://docs.mongodb.org/manual/core/cursors/
        :return: the result of the query
        """
        collection = self._table(db_name, collection_name)
        try:
            return collection.find(*args, **kwargs)
        except Exception as e:
            raise IrmaDatabaseError("{0}".format(e))
예제 #18
0
 def data(self):
     """Get the data"""
     if self._dbfile is None:
         raise IrmaDatabaseError("File has no data")
     return self._dbfile.read()