Python django.db.transaction.savepoint() Examples
The following are 15
code examples of django.db.transaction.savepoint().
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: tests.py From prospector with GNU General Public License v3.0 | 6 votes |
def test_emptyfield(self): m = self._get_mailinglist() p = self._get_participant() values = { 'author': p, 'timestamp': datetime.datetime.utcnow(), 'subject': '', 'message_id': 'abc' } for key in values: kwargs = values.copy() kwargs[key] = None sid = transaction.savepoint() with self.assertRaises(ValueError if key == 'author' else IntegrityError): # ForeignKeys throw a ValueError instead of IntegrityError. Post.objects.create(**kwargs) transaction.savepoint_rollback(sid)
Example #2
Source File: geo_inheritance_manager.py From urbanfootprint with GNU General Public License v3.0 | 6 votes |
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 #3
Source File: models.py From product-definition-center with MIT License | 6 votes |
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 #4
Source File: base.py From django_migration_testcase with MIT License | 5 votes |
def idempotent_transaction(func): if django.VERSION < (1, 7,) or django.VERSION >= (2, 0) and settings.DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3': return func else: @functools.wraps(func) def func_wrapper(*args, **kwargs): with transaction.atomic(): sp = transaction.savepoint() try: func(*args, **kwargs) transaction.savepoint_rollback(sp) except BaseException: raise return func_wrapper
Example #5
Source File: inventory.py From KubeOperator with Apache License 2.0 | 5 votes |
def is_valid(self, raise_exception=False): if not self.initial_data: raise serializers.ValidationError({"inventory": "inventory empty"}) self._save_point = transaction.savepoint() try: current_project.clear_inventory() self.clean_inventory_data(self.initial_data) valid = super().is_valid(raise_exception=raise_exception) except serializers.ValidationError as e: transaction.savepoint_rollback(self._save_point) raise e if not valid: transaction.savepoint_rollback(self._save_point) return valid
Example #6
Source File: tests.py From prospector with GNU General Public License v3.0 | 5 votes |
def test_emptyfield(self): sid = transaction.savepoint() with self.assertRaises(IntegrityError): MailingList.objects.create(posting_address='test@example.com', archive_url=None) transaction.savepoint_rollback(sid) with self.assertRaises(IntegrityError): MailingList.objects.create(posting_address=None, archive_url='http://example.com')
Example #7
Source File: tests.py From prospector with GNU General Public License v3.0 | 5 votes |
def test_missingfields(self): b = BugTracker.objects.create(baseurl=self.baseurl, bt_type=self._get_type()) self.assertEqual(None, b.username) self.assertEqual(None, b.password) with self.assertRaises(IntegrityError): sid = transaction.savepoint() BugTracker.objects.create(baseurl=None, bt_type=self._get_type()) transaction.savepoint_rollback(sid) with self.assertRaises(IntegrityError): BugTracker.objects.create(baseurl=self.baseurl)
Example #8
Source File: ComplianceReport.py From tfrs with Apache License 2.0 | 5 votes |
def compute_totals(self, request, pk=None): """ This works much like a regular PATCH, but rolls back the transaction """ validation_deserializer = ComplianceReportValidationSerializer( data=request.data ) if not validation_deserializer.is_valid(): return Response(validation_deserializer.errors) sid = transaction.savepoint() obj = self.get_object() deserializer = ComplianceReportUpdateSerializer( obj, data=request.data, partial=True, context={'request': request} ) deserializer.strip_summary = True deserializer.disregard_status = True if not deserializer.is_valid(): transaction.savepoint_rollback(sid) return Response(deserializer.errors) patched_obj = deserializer.save() serializer = ComplianceReportDetailSerializer(patched_obj, context={'request': request}) result = serializer.data transaction.savepoint_rollback(sid) return Response(result)
Example #9
Source File: geo_inheritance_manager.py From urbanfootprint with GNU General Public License v3.0 | 5 votes |
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 #10
Source File: query.py From luscan-devel with GNU General Public License v2.0 | 5 votes |
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 #11
Source File: actions.py From mysite with Apache License 2.0 | 5 votes |
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 #12
Source File: test_tenants.py From django-pgschemas with MIT License | 5 votes |
def assertRaises(self, *args, **kwargs): """ Since we are expecting database errors, we must use savepoints in order to make sure multiple errors can be caught in the same test case. """ sid = transaction.savepoint() with super().assertRaises(*args, **kwargs): yield transaction.savepoint_rollback(sid)
Example #13
Source File: models.py From product-definition-center with MIT License | 5 votes |
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 #14
Source File: compat.py From votes with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #15
Source File: orm.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def rollback(): """Context manager that always rolls back to a savepoint. This is useful when using hypothesis (https://hypothesis.readthedocs.org/) which repeatedly runs tests to discover edge cases. """ sid = transaction.savepoint() try: yield finally: transaction.savepoint_rollback(sid)