コード例 #1
0
ファイル: models.py プロジェクト: msimonin/rome
 def soft_delete(self, session=None):
     # <SOFT DELETE IMPLEMENTATION>
     self.deleted = 1
     object_converter_datetime = get_encoder()
     self.deleted_at = object_converter_datetime.simplify(datetime.datetime.utcnow())
     if session is not None:
         session.add(self)
         return
     else:
         self.save()
コード例 #2
0
ファイル: models.py プロジェクト: msimonin/rome
 def soft_delete(self, session=None):
     # <SOFT DELETE IMPLEMENTATION>
     self.deleted = 1
     object_converter_datetime = get_encoder()
     self.deleted_at = object_converter_datetime.simplify(
         datetime.datetime.utcnow())
     if session is not None:
         session.add(self)
         return
     else:
         self.save()
コード例 #3
0
    def test_creation(self):
        logging.getLogger().setLevel(logging.DEBUG)
        bobby = Dog()
        bobby.name = "Bobby"
        bobby.specy = "Griffon"
        bobby.save()
        specy = Specy()
        specy.name = "Griffon"
        specy.save()
        self.assertEqual(True, True)

        from lib.rome.core.dataformat import get_encoder
        from lib.rome.core.lazy import LazyValue
        converter = get_encoder()
        bobby_dict = converter.simplify(bobby)
        toto = converter.simplify(LazyValue(bobby_dict, None))
        print(toto)
コード例 #4
0
ファイル: models.py プロジェクト: msimonin/rome
    def save(self, session=None, request_uuid=uuid.uuid1(), force=False, no_nested_save=False, increase_version=True, session_saving=None):

        if session is not None and not force:
            session.add(self)
            session.flush()
            return

        object_key = "%s:%s" % (self.__tablename__, self.id)

        if session_saving and self.id and object_key in session_saving.already_saved:
            return

        # self.update_foreign_keys()

        target = self
        table_name = self.__tablename__

        self._set_default_values()

        """Check if the current object has an value associated with the "id"
        field. If this is not the case, following code will generate an unique
        value, and store it in the "id" field."""
        if not self.already_in_database():
            self.id = database_driver.get_driver().next_key(table_name)
            logging.debug("booking the id %s in table %s" % (self.id, self.__tablename__))

        """Before keeping the object in database, we simplify it: the object is
        converted into "JSON like" representation, and nested objects are
        extracted. It results in a list of object that will be stored in the
        database."""
        object_converter = get_encoder(request_uuid)
        object_converter.simplify(self)

        saving_candidates = object_converter.complex_cache

        if no_nested_save:
            key = object_converter.get_cache_key(self)
            saving_candidates = {
                key: saving_candidates[key]
            }

        for key in [key for key in saving_candidates if "x" in key]:

            candidate = saving_candidates[key]
            default_classname = "_".join(key.split("_")[0:-1])
            classname = candidate.get("_metadata_novabase_classname", default_classname)
            table_name = get_model_tablename_from_classname(classname)

            simplified_object = object_converter.simple_cache[key]
            complex_object = object_converter.complex_cache[key]
            target_object = object_converter.target_cache[key]

            if simplified_object["id"] is not None:
                continue

            """Find a new_id for this object"""
            new_id = database_driver.get_driver().next_key(table_name)

            """Assign this id to the object"""
            simplified_object["id"] = new_id
            complex_object["id"] = new_id
            target_object.id = new_id

            pass

        for key in saving_candidates:

            candidate = saving_candidates[key]
            default_classname = "_".join(key.split("_")[0:-1])
            classname = candidate.get("_metadata_novabase_classname", default_classname)
            table_name = get_model_tablename_from_classname(classname)

            current_object = object_converter.complex_cache[key]

            current_object["_nova_classname"] = table_name

            if not "id" in current_object or current_object["id"] is None:
                current_object["id"] = self.next_key(table_name)
            else:

                current_object_key = "%s:%s" % (table_name, current_object["id"])

                if session_saving and current_object_key in session_saving.already_saved:
                    continue

                model_class = get_model_class_from_name(classname)
                existing_object = database_driver.get_driver().get(table_name, current_object["id"])

                if not same_version(existing_object, current_object, model_class):
                    current_object = merge_dict(existing_object, current_object)
                else:
                    continue

            if current_object["id"] == -1:
                logging.debug("skipping the storage of object %s" % (current_object["id"]))
                # continue
                break

            object_converter_datetime = get_encoder(request_uuid)

            if (current_object.has_key("created_at") and current_object[
                "created_at"] is None) or not current_object.has_key("created_at"):
                current_object["created_at"] = object_converter_datetime.simplify(datetime.datetime.utcnow())
            current_object["updated_at"] = object_converter_datetime.simplify(datetime.datetime.utcnow())
            current_object["deleted_at"] = None

            logging.debug("starting the storage of %s" % (current_object))

            try:
                local_object_converter = get_encoder(request_uuid)
                corrected_object = local_object_converter.simplify(current_object)
                if target.__tablename__ == corrected_object["_nova_classname"] and target.id == corrected_object["id"]:
                    corrected_object["_session"] = getattr(target, "_session", None)
                if increase_version:
                    if "_rome_version_number" in corrected_object:
                        self._rome_version_number = corrected_object["_rome_version_number"]
                    if hasattr(self, "_rome_version_number"):
                        self._rome_version_number += 1
                    else:
                        self._rome_version_number = 0
                corrected_object["_rome_version_number"] = self._rome_version_number
                database_driver.get_driver().put(table_name, current_object["id"], corrected_object, secondary_indexes=getattr(model_class, "_secondary_indexes", []))
                database_driver.get_driver().add_key(table_name, current_object["id"])
            except Exception as e:
                import traceback
                traceback.print_exc()
                logging.error("Failed to store following object: %s because of %s, becoming %s" % (
                current_object, e, corrected_object))
                pass
            logging.debug("finished the storage of %s" % (current_object))

            if session_saving:
                session_saving.already_saved += [current_object_key]
        # self.load_relationships()

        candidates = []
        # Handle associated objects: they may be saved!
        for associated_object in self.get_associated_objects():
            candidates += [associated_object]

        # As every associated_object are going to be saved, associated_objects may be reset
        self.reset_associated_objects()

        for c in candidates:
            try:
                # object_converter.simplify(c)
                c.save(request_uuid=request_uuid, force=force, no_nested_save=no_nested_save, increase_version=increase_version, session_saving=session_saving)
            except:
                import traceback
                traceback.print_exc()
                pass

        return self
コード例 #5
0
ファイル: models.py プロジェクト: msimonin/rome
    def save(self,
             session=None,
             request_uuid=uuid.uuid1(),
             force=False,
             no_nested_save=False,
             increase_version=True,
             session_saving=None):

        if session is not None and not force:
            session.add(self)
            session.flush()
            return

        object_key = "%s:%s" % (self.__tablename__, self.id)

        if session_saving and self.id and object_key in session_saving.already_saved:
            return

        # self.update_foreign_keys()

        target = self
        table_name = self.__tablename__

        self._set_default_values()
        """Check if the current object has an value associated with the "id"
        field. If this is not the case, following code will generate an unique
        value, and store it in the "id" field."""
        if not self.already_in_database():
            self.id = database_driver.get_driver().next_key(table_name)
            logging.debug("booking the id %s in table %s" %
                          (self.id, self.__tablename__))
        """Before keeping the object in database, we simplify it: the object is
        converted into "JSON like" representation, and nested objects are
        extracted. It results in a list of object that will be stored in the
        database."""
        object_converter = get_encoder(request_uuid)
        object_converter.simplify(self)

        saving_candidates = object_converter.complex_cache

        if no_nested_save:
            key = object_converter.get_cache_key(self)
            saving_candidates = {key: saving_candidates[key]}

        for key in [key for key in saving_candidates if "x" in key]:

            candidate = saving_candidates[key]
            default_classname = "_".join(key.split("_")[0:-1])
            classname = candidate.get("_metadata_novabase_classname",
                                      default_classname)
            table_name = get_model_tablename_from_classname(classname)

            simplified_object = object_converter.simple_cache[key]
            complex_object = object_converter.complex_cache[key]
            target_object = object_converter.target_cache[key]

            if simplified_object["id"] is not None:
                continue
            """Find a new_id for this object"""
            new_id = database_driver.get_driver().next_key(table_name)
            """Assign this id to the object"""
            simplified_object["id"] = new_id
            complex_object["id"] = new_id
            target_object.id = new_id

            pass

        for key in saving_candidates:

            candidate = saving_candidates[key]
            default_classname = "_".join(key.split("_")[0:-1])
            classname = candidate.get("_metadata_novabase_classname",
                                      default_classname)
            table_name = get_model_tablename_from_classname(classname)

            current_object = object_converter.complex_cache[key]

            current_object["_nova_classname"] = table_name

            if not "id" in current_object or current_object["id"] is None:
                current_object["id"] = self.next_key(table_name)
            else:

                current_object_key = "%s:%s" % (table_name,
                                                current_object["id"])

                if session_saving and current_object_key in session_saving.already_saved:
                    continue

                model_class = get_model_class_from_name(classname)
                existing_object = database_driver.get_driver().get(
                    table_name, current_object["id"])

                if not same_version(existing_object, current_object,
                                    model_class):
                    current_object = merge_dict(existing_object,
                                                current_object)
                else:
                    continue

            if current_object["id"] == -1:
                logging.debug("skipping the storage of object %s" %
                              (current_object["id"]))
                # continue
                break

            object_converter_datetime = get_encoder(request_uuid)

            if (current_object.has_key("created_at")
                    and current_object["created_at"] is None
                ) or not current_object.has_key("created_at"):
                current_object[
                    "created_at"] = object_converter_datetime.simplify(
                        datetime.datetime.utcnow())
            current_object["updated_at"] = object_converter_datetime.simplify(
                datetime.datetime.utcnow())
            current_object["deleted_at"] = None

            logging.debug("starting the storage of %s" % (current_object))

            try:
                local_object_converter = get_encoder(request_uuid)
                corrected_object = local_object_converter.simplify(
                    current_object)
                if target.__tablename__ == corrected_object[
                        "_nova_classname"] and target.id == corrected_object[
                            "id"]:
                    corrected_object["_session"] = getattr(
                        target, "_session", None)
                if increase_version:
                    if "_rome_version_number" in corrected_object:
                        self._rome_version_number = corrected_object[
                            "_rome_version_number"]
                    if hasattr(self, "_rome_version_number"):
                        self._rome_version_number += 1
                    else:
                        self._rome_version_number = 0
                corrected_object[
                    "_rome_version_number"] = self._rome_version_number
                database_driver.get_driver().put(table_name,
                                                 current_object["id"],
                                                 corrected_object,
                                                 secondary_indexes=getattr(
                                                     model_class,
                                                     "_secondary_indexes", []))
                database_driver.get_driver().add_key(table_name,
                                                     current_object["id"])
            except Exception as e:
                import traceback
                traceback.print_exc()
                logging.error(
                    "Failed to store following object: %s because of %s, becoming %s"
                    % (current_object, e, corrected_object))
                pass
            logging.debug("finished the storage of %s" % (current_object))

            if session_saving:
                session_saving.already_saved += [current_object_key]
        # self.load_relationships()

        candidates = []
        # Handle associated objects: they may be saved!
        for associated_object in self.get_associated_objects():
            candidates += [associated_object]

        # As every associated_object are going to be saved, associated_objects may be reset
        self.reset_associated_objects()

        for c in candidates:
            try:
                # object_converter.simplify(c)
                c.save(request_uuid=request_uuid,
                       force=force,
                       no_nested_save=no_nested_save,
                       increase_version=increase_version,
                       session_saving=session_saving)
            except:
                import traceback
                traceback.print_exc()
                pass

        return self