Skip to main content

Offline optimistic locking for Django

Project description

https://secure.travis-ci.org/gavinwahl/django-optimistic-lock.png?branch=master

Implements an offline optimistic lock [1] for Django models.

Usage

Add a VersionField and inherit from VersionedMixin.

from ool import VersionField, VersionedMixin

class MyModel(VersionedMixin, models.Model):
    version = VersionField()

Whenever MyModel is saved, the version will be checked to ensure the instance has not changed since it was last fetched. If there is a conflict, a ConcurrentUpdate exception will be raised.

Implementation

A VersionField is just an integer that increments itself every time its model is saved. VersionedMixin overrides _do_update (which is called by save to actually do the update) to add an extra condition to the update query – that the version in the database is the same as the model’s version. If they match, there have been no concurrent modifications. If they don’t match, the UPDATE statement will not update any rows, and we know that someone else saved first.

This produces SQL that looks something like:

UPDATE mymodel SET version = version + 1, ... WHERE id = %s AND version = %s

When no rows were updated, we know someone else won and we need to raise a ConcurrentUpdate.

Comparison to django-concurrency

django-concurrency before version 0.7 used SELECT FOR UPDATE to implement the version checking. I wanted to avoid database-level locking, so django-optimistic-lock adds a version filter to the update statement, as described by Martin Fowler [1].

Additionally, ool takes a more minimalistic approach than django-concurrency by only doing one thing – optimistic locking – without any monkey-patching, middleware, settings variables, admin classes, or form fields. django-concurrency would probably make more sense if you’re looking for something that will attempt to accommodate every situation out of the box. Use ool if you just want a straightforward model implementation and need to handle the UI and surrounding architecture yourself.

Running the tests

make test

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-optimistic-lock-0.1.tar.gz (8.1 kB view details)

Uploaded Source

File details

Details for the file django-optimistic-lock-0.1.tar.gz.

File metadata

File hashes

Hashes for django-optimistic-lock-0.1.tar.gz
Algorithm Hash digest
SHA256 85a055aaf7051d082a08f95c154c2f4b7f43462ca3a6a44a24bbd9e439fffe67
MD5 00eb2e14d5c4d732f84d1dfd0aa251b4
BLAKE2b-256 9c692a1f50786b52202ba5e3035596d9c2f5a02bd60c13bf9c119ad1fcb146ed

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page