django-pglocks-1.0.4/0000755000076600000240000000000013601210243014326 5ustar xofstaff00000000000000django-pglocks-1.0.4/PKG-INFO0000644000076600000240000001220013601210243015416 0ustar xofstaff00000000000000Metadata-Version: 1.1 Name: django-pglocks Version: 1.0.4 Summary: django_pglocks provides useful context managers for advisory locks for PostgreSQL. Home-page: https://github.com/Xof/django-pglocks Author: Christophe Pettus Author-email: xof@thebuild.com License: MIT Description: ============== django-pglocks ============== django-pglocks provides a useful context manager to manage PostgreSQL advisory locks. It requires Django (tested with 1.5), PostgreSQL, and (probably) psycopg2. Advisory Locks ============== Advisory locks are application-level locks that are acquired and released purely by the client of the database; PostgreSQL never acquires them on its own. They are very useful as a way of signalling to other sessions that a higher-level resource than a single row is in use, without having to lock an entire table or some other structure. It's entirely up to the application to correctly acquire the right lock. Advisory locks are either session locks or transaction locks. A session lock is held until the database session disconnects (or is reset); a transaction lock is held until the transaction terminates. Currently, the context manager only creates session locks, as the behavior of a lock persisting after the context body has been exited is surprising, and there's no way of releasing a transaction-scope advisory lock except to exit the transaction. Installing ========== Just use pip:: pip install django-pglocks Transactions ============ This assumes you are controlling transactions within the view; do not use this if you controlling transactions through the Django transation middleware. Usage ===== Usage example:: from django_pglocks import advisory_lock lock_id = 'some lock' with advisory_lock(lock_id) as acquired: # code that should be inside of the lock. The context manager attempts to take the lock, and then executes the code inside the context with the lock acquired. The lock is released when the context exits, either normally or via exception. The parameters are: * ``lock_id`` -- The ID of the lock to acquire. It can be a string, long, or a tuple of two ints. If it's a string, the hash of the string is used as the lock ID (PostgreSQL advisory lock IDs are 64 bit values). * ``shared`` (default False) -- If True, a shared lock is taken. Any number of sessions can hold a shared lock; if another session attempts to take an exclusive lock, it will wait until all shared locks are released; if a session is holding a shared lock, it will block attempts to take a shared lock. If False (the default), an exclusive lock is taken. * ``wait`` (default True) -- If True (the default), the context manager will wait until the lock has been acquired before executing the content; in that case, it always returns True (unless a deadlock occurs, in which case an exception is thrown). If False, the context manager will return immediately even if it cannot take the lock, in which case it returns false. Note that the context body is *always* executed; the only way to tell in the ``wait=False`` case whether or not the lock was acquired is to check the returned value. * ``using`` (default None) -- The database alias on which to attempt to acquire the lock. If None, the default connection is used. Contributing ============ To run the test suite, you must create a user and a database:: $ createuser -s -P django_pglocks Enter password for new role: django_pglocks Enter it again: django_pglocks $ createdb django_pglocks -O django_pglocks You can then run the tests with:: $ DJANGO_SETTINGS_MODULE=django_pglocks.test_settings PYTHONPATH=. django-admin.py test License ======= It's released under the `MIT License `_. Change History 1.0.2 ==================== Fixed bug where lock would not be released when acquired with wait=False. Many thanks to Aymeric Augustin for finding this! Change History 1.0.1 ==================== Removed transaction-level locks, as their behavior was somewhat surprising (having the lock persist after the context manager exited was unexpected behavior). Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Framework :: Django Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Topic :: Software Development Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 django-pglocks-1.0.4/django_pglocks/0000755000076600000240000000000013601210243017312 5ustar xofstaff00000000000000django-pglocks-1.0.4/django_pglocks/models.py0000644000076600000240000000000012263353455021155 0ustar xofstaff00000000000000django-pglocks-1.0.4/django_pglocks/__init__.py0000644000076600000240000000432713601210132021426 0ustar xofstaff00000000000000__version__ = '1.0.4' from contextlib import contextmanager from zlib import crc32 @contextmanager def advisory_lock(lock_id, shared=False, wait=True, using=None): import six from django.db import DEFAULT_DB_ALIAS, connections, transaction if using is None: using = DEFAULT_DB_ALIAS # Assemble the function name based on the options. function_name = 'pg_' if not wait: function_name += 'try_' function_name += 'advisory_lock' if shared: function_name += '_shared' release_function_name = 'pg_advisory_unlock' if shared: release_function_name += '_shared' # Format up the parameters. tuple_format = False if isinstance(lock_id, (list, tuple,)): if len(lock_id) != 2: raise ValueError("Tuples and lists as lock IDs must have exactly two entries.") if not isinstance(lock_id[0], six.integer_types) or not isinstance(lock_id[1], six.integer_types): raise ValueError("Both members of a tuple/list lock ID must be integers") tuple_format = True elif isinstance(lock_id, six.string_types): # Generates an id within postgres integer range (-2^31 to 2^31 - 1). # crc32 generates an unsigned integer in Py3, we convert it into # a signed integer using 2's complement (this is a noop in Py2) pos = crc32(lock_id.encode("utf-8")) lock_id = (2**31 - 1) & pos if pos & 2**31: lock_id -= 2**31 elif not isinstance(lock_id, six.integer_types): raise ValueError("Cannot use %s as a lock id" % lock_id) if tuple_format: base = "SELECT %s(%d, %d)" params = (lock_id[0], lock_id[1],) else: base = "SELECT %s(%d)" params = (lock_id,) acquire_params = ( function_name, ) + params command = base % acquire_params cursor = connections[using].cursor() cursor.execute(command) if not wait: acquired = cursor.fetchone()[0] else: acquired = True try: yield acquired finally: if acquired: release_params = ( release_function_name, ) + params command = base % release_params cursor.execute(command) cursor.close() django-pglocks-1.0.4/django_pglocks/tests.py0000644000076600000240000000416713601210051021033 0ustar xofstaff00000000000000from django.db import connection from django.test import TransactionTestCase from django_pglocks import advisory_lock class PgLocksTests(TransactionTestCase): @classmethod def setUpClass(cls): cursor = connection.cursor() cursor.execute( "SELECT oid FROM pg_database WHERE datname = %s", [connection.settings_dict['NAME']]) cls.db_oid = cursor.fetchall()[0][0] cursor.close() def assertNumLocks(self, expected): cursor = connection.cursor() cursor.execute( "SELECT COUNT(*) FROM pg_locks WHERE database = %s AND locktype = %s", [self.db_oid, 'advisory']) actual = cursor.fetchall()[0][0] cursor.close() self.assertEqual(actual, expected) def test_basic_lock_str(self): self.assertNumLocks(0) with advisory_lock('test') as acquired: self.assertTrue(acquired) self.assertNumLocks(1) self.assertNumLocks(0) def test_basic_lock_int(self): self.assertNumLocks(0) with advisory_lock(123) as acquired: self.assertTrue(acquired) self.assertNumLocks(1) self.assertNumLocks(0) def test_basic_lock_tuple(self): self.assertNumLocks(0) with advisory_lock((123, 456)) as acquired: self.assertTrue(acquired) self.assertNumLocks(1) self.assertNumLocks(0) def test_basic_lock_no_wait(self): self.assertNumLocks(0) with advisory_lock(123, wait=False) as acquired: self.assertTrue(acquired) self.assertNumLocks(1) self.assertNumLocks(0) def test_basic_lock_shared(self): self.assertNumLocks(0) with advisory_lock(123, shared=True) as acquired: self.assertTrue(acquired) self.assertNumLocks(1) self.assertNumLocks(0) def test_basic_lock_shared_no_wait(self): self.assertNumLocks(0) with advisory_lock(123, shared=True, wait=False) as acquired: self.assertTrue(acquired) self.assertNumLocks(1) self.assertNumLocks(0) django-pglocks-1.0.4/django_pglocks/test_settings.py0000644000076600000240000000050312263353455022601 0ustar xofstaff00000000000000# Django settings for django_pglocks tests. import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_pglocks', 'USER': 'django_pglocks', 'PASSWORD': 'django_pglocks', } } INSTALLED_APPS = ['django_pglocks'] SECRET_KEY = 'whatever' django-pglocks-1.0.4/CHANGES.txt0000644000076600000240000000014112164560212016142 0ustar xofstaff00000000000000v1.0.1, 2 July 2013 -- Removed transaction mode (see docs) v1.0, 2 July 2013 -- Initial release. django-pglocks-1.0.4/setup.py0000755000076600000240000000241013601210051016035 0ustar xofstaff00000000000000#!/usr/bin/env python from distutils.core import setup import django_pglocks def get_long_description(): """ Return the contents of the README file. """ try: return open('README.rst').read() except: pass # Required to install using pip (won't have README then) setup( name = 'django-pglocks', version = django_pglocks.__version__, description = "django_pglocks provides useful context managers for advisory locks for PostgreSQL.", long_description = get_long_description(), author = "Christophe Pettus", author_email = "xof@thebuild.com", license = "MIT", url = "https://github.com/Xof/django-pglocks", install_requires = ['six>=1.0.0'], packages = [ 'django_pglocks', ], package_data = { 'facetools': ['templates/facetools/facebook_redirect.html'], }, classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ] ) django-pglocks-1.0.4/LICENSE.txt0000644000076600000240000000010612164547661016172 0ustar xofstaff00000000000000Copyright (c) 2013 Christophe Pettus Licensed under the MIT License.