Python django.db.transaction.savepoint_commit() Examples

The following are 8 code examples of django.db.transaction.savepoint_commit(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.transaction , or try the search function .
Example #1
Source File: geo_inheritance_manager.py    From urbanfootprint with GNU General Public License v3.0 6 votes vote down vote up
def update_or_add(self, **kwargs):
        assert kwargs, 'update_or_add() must be passed at least one keyword argument'
        defaults = kwargs.pop('defaults', {})
        obj = get_first(self.filter(**kwargs))
        result = (obj, False, True)
        create = False
        if not obj:
            obj = self.model()
            result = (obj, True, False)
            create = True
        try:
            params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
            params.update(defaults)
            for attr, val in params.items():
                if hasattr(obj, attr):
                    setattr(obj, attr, val)
            sid = transaction.savepoint()
            obj.save(force_update=not create)
            if not create:
                self.add(obj)
            transaction.savepoint_commit(sid)

            return result
        except IntegrityError, e:
            transaction.savepoint_rollback(sid) 
Example #2
Source File: models.py    From product-definition-center with MIT License 6 votes vote down vote up
def bulk_insert(cursor, variant_arch_id, rpm_id, content_category_id, sigkey_id, path_id):
        sql = add_returning("""INSERT INTO %s (variant_arch_id, rpm_id, sigkey_id, content_category_id, path_id)
                               VALUES (%%s, %%s, %%s, %%s, %%s)""" % ComposeRPM._meta.db_table)

        try:
            sid = transaction.savepoint()
            cursor.execute(sql, [variant_arch_id, rpm_id, sigkey_id, content_category_id, path_id])
            if connection.features.can_return_id_from_insert:
                insert_id = connection.ops.fetch_returned_insert_id(cursor)
            else:
                insert_id = connection.ops.last_insert_id(cursor, ComposeRPM._meta.db_table, "id")
        except IntegrityError:
            transaction.savepoint_rollback(sid)
            cursor.execute("SELECT %s FROM %s WHERE variant_arch_id=%%s AND rpm_id=%%s"
                           % ("id", ComposeRPM._meta.db_table),
                           [variant_arch_id, rpm_id])
            insert_id = int(cursor.fetchone()[0])
        transaction.savepoint_commit(sid)
        return insert_id 
Example #3
Source File: inventory.py    From KubeOperator with Apache License 2.0 5 votes vote down vote up
def create(self, validated_data):
        try:
            hosts = self.add_hosts()
            groups = self.add_groups()
            self.set_host_groups()
            self.set_group_children()
            self.set_group_hosts()
        except serializers.ValidationError as e:
            transaction.savepoint_rollback(self._save_point)
            raise e
        transaction.savepoint_commit(self._save_point)
        return Inventory(hosts=hosts, groups=groups) 
Example #4
Source File: geo_inheritance_manager.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def update_or_create(self, **kwargs):
        """
            updates, creates or gets based on the kwargs. Works like get_or_create but in addition will update
            the kwargs specified in defaults and returns a third value to indicate if an update happened
        :param kwargs:
        :return:
        """
        assert kwargs, 'update_or_create() must be passed at least one keyword argument'
        obj, created = self.get_or_create(**kwargs)
        defaults = kwargs.pop('defaults', {})
        if created:
            return obj, True, False
        else:
            try:
                needs_save = False
                params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
                params.update(defaults)
                for attr, val in params.items():
                    if hasattr(obj, attr):
                        setattr(obj, attr, val)
                # sid = transaction.savepoint()
                obj.save(force_update=True)
                # transaction.savepoint_commit(sid)
                return obj, False, True
            except IntegrityError, e:
                # transaction.savepoint_rollback(sid)
                try:
                    return self.get(**kwargs), False, False
                except self.model.DoesNotExist:
                    raise e

    # Update the related instance or add it. The toMany equivalent to update_or_create 
Example #5
Source File: query.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_or_create(self, **kwargs):
        """
        Looks up an object with the given kwargs, creating one if necessary.
        Returns a tuple of (object, created), where created is a boolean
        specifying whether an object was created.
        """
        assert kwargs, \
                'get_or_create() must be passed at least one keyword argument'
        defaults = kwargs.pop('defaults', {})
        lookup = kwargs.copy()
        for f in self.model._meta.fields:
            if f.attname in lookup:
                lookup[f.name] = lookup.pop(f.attname)
        try:
            self._for_write = True
            return self.get(**lookup), False
        except self.model.DoesNotExist:
            try:
                params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
                params.update(defaults)
                obj = self.model(**params)
                sid = transaction.savepoint(using=self.db)
                obj.save(force_insert=True, using=self.db)
                transaction.savepoint_commit(sid, using=self.db)
                return obj, True
            except IntegrityError as e:
                transaction.savepoint_rollback(sid, using=self.db)
                exc_info = sys.exc_info()
                try:
                    return self.get(**lookup), False
                except self.model.DoesNotExist:
                    # Re-raise the IntegrityError with its original traceback.
                    six.reraise(*exc_info) 
Example #6
Source File: actions.py    From mysite with Apache License 2.0 5 votes vote down vote up
def transfer_money(_from, _to, quota):

    if _from.money < 15:
        raise ValueError("連手續費都付不起,請回吧!!")

    _from.money = _from.money - 15
    _from.save()

    sid = transaction.savepoint()

    try:
        _from.money = _from.money - quota
        if _from.money < 0:
            raise ValueError("超額提領!")
        _from.save()
        _to.money = _to.money + quota
        if _to.money > 100000:
            raise ValueError("超額儲存!")
        _to.save()
        transaction.savepoint_commit(sid)
    except ValueError as e:
        logger.error("金額操作錯誤, 訊息:<{}>".format(e))
        transaction.savepoint_rollback(sid)
    except Exception as e:
        logger.error("其他錯誤,訊息:<{}>".format(e))
        transaction.savepoint_rollback(sid) 
Example #7
Source File: models.py    From product-definition-center with MIT License 5 votes vote down vote up
def bulk_insert(cursor, rpm_nevra, filename, srpm_nevra=None,
                    srpm_commit_hash=None, srpm_commit_branch=None):
        nvra = parse_nvra(rpm_nevra)
        if srpm_nevra:
            srpm_name = parse_nvra(srpm_nevra)["name"]
        else:
            srpm_name = nvra["name"]

        sql = add_returning("""INSERT INTO %s (name, epoch, version, release, arch, srpm_nevra, srpm_name, filename, srpm_commit_hash, srpm_commit_branch)
                               VALUES (%%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s)""" % RPM._meta.db_table)

        try:
            sid = transaction.savepoint()
            RPM.check_srpm_nevra(rpm_nevra, srpm_nevra)
            cursor.execute(sql, [nvra["name"], nvra["epoch"], nvra["version"], nvra["release"],
                                 nvra["arch"], srpm_nevra, srpm_name, filename, srpm_commit_hash,
                                 srpm_commit_branch])
            if connection.features.can_return_id_from_insert:
                insert_id = connection.ops.fetch_returned_insert_id(cursor)
            else:
                insert_id = connection.ops.last_insert_id(cursor, RPM._meta.db_table, "id")
        except (IntegrityError, ValidationError):
            transaction.savepoint_rollback(sid)
            cursor.execute("""SELECT %s FROM %s WHERE name=%%s AND epoch=%%s AND
                              version=%%s and release=%%s AND arch=%%s""" % ("id", RPM._meta.db_table),
                           [nvra["name"], nvra["epoch"], nvra["version"], nvra["release"], nvra["arch"]])
            insert_id = int(cursor.fetchone()[0])
        transaction.savepoint_commit(sid)
        return insert_id 
Example #8
Source File: compat.py    From votes with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def atomic(using=None):
        sid = transaction.savepoint(using=using)
        try:
            yield
        except IntegrityError:
            transaction.savepoint_rollback(sid, using=using)
            raise
        else:
            transaction.savepoint_commit(sid, using=using)