Search is not available for this dataset
id
stringlengths
1
8
text
stringlengths
72
9.81M
addition_count
int64
0
10k
commit_subject
stringlengths
0
3.7k
deletion_count
int64
0
8.43k
file_extension
stringlengths
0
32
lang
stringlengths
1
94
license
stringclasses
10 values
repo_name
stringlengths
9
59
1600
<NME> pool.py <BEF> """ Connection Pooling """ import datetime import logging import os import threading import time import weakref import psycopg2 LOGGER = logging.getLogger(__name__) DEFAULT_IDLE_TTL = 60 DEFAULT_MAX_SIZE = int(os.environ.get('QUERIES_MAX_POOL_SIZE', 1)) class Connection(object): """Contains the handle to the connection, the current state of the connection and methods for manipulating the state of the connection. """ _lock = threading.Lock() def __init__(self, handle): self.handle = handle self.used_by = None self.executions = 0 self.exceptions = 0 def close(self): """Close the connection :raises: ConnectionBusyError """ LOGGER.debug('Connection %s closing', self.id) if self.busy and not self.closed: raise ConnectionBusyError(self) with self._lock: if not self.handle.closed: try: self.handle.close() except psycopg2.InterfaceError as error: LOGGER.error('Error closing socket: %s', error) @property def closed(self): """Return if the psycopg2 connection is closed. :rtype: bool """ return self.handle.closed != 0 @property def busy(self): """Return if the connection is currently executing a query or is locked by a session that still exists. :rtype: bool """ if self.handle.isexecuting(): return True elif self.used_by is None: return False return not self.used_by() is None @property def executing(self): """Return if the connection is currently executing a query :rtype: bool """ return self.handle.isexecuting() def free(self): """Remove the lock on the connection if the connection is not active :raises: ConnectionBusyError """ LOGGER.debug('Connection %s freeing', self.id) if self.handle.isexecuting(): raise ConnectionBusyError(self) with self._lock: self.used_by = None LOGGER.debug('Connection %s freed', self.id) @property def id(self): """Return id of the psycopg2 connection object :rtype: int """ return id(self.handle) def lock(self, session): """Lock the connection, ensuring that it is not busy and storing a weakref for the session. :param queries.Session session: The session to lock the connection with :raises: ConnectionBusyError """ if self.busy: raise ConnectionBusyError(self) with self._lock: self.used_by = weakref.ref(session) LOGGER.debug('Connection %s locked', self.id) @property def locked(self): """Return if the connection is currently exclusively locked :rtype: bool """ return self.used_by is not None class Pool(object): """A connection pool for gaining access to and managing connections""" _lock = threading.Lock() idle_start = None idle_ttl = DEFAULT_IDLE_TTL max_size = DEFAULT_MAX_SIZE def __init__(self, pool_id, idle_ttl=DEFAULT_IDLE_TTL, max_size=DEFAULT_MAX_SIZE, time_method=None): self.connections = {} self._id = pool_id self.idle_ttl = idle_ttl self.max_size = max_size self.time_method = time_method or time.time def __contains__(self, connection): """Return True if the pool contains the connection""" return id(connection) in self.connections def __len__(self): """Return the number of connections in the pool""" return len(self.connections) def add(self, connection): """Add a new connection to the pool def close(self): """Close the pool by closing and removing all of the connections""" for cid in self.connections: self.remove(self.connections[cid].handle) LOGGER.debug('Pool %s closed', self.id) raise ValueError('Connection already exists in pool') if len(self.connections) == self.max_size: LOGGER.warning('Race condition found when adding new connection') try: connection.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.error('Error closing the conn that cant be used: %s', error) raise PoolFullError(self) with self._lock: self.connections[id(connection)] = Connection(connection) LOGGER.debug('Pool %s added connection %s', self.id, id(connection)) @property def busy_connections(self): """Return a list of active/busy connections :rtype: list """ return [c for c in self.connections.values() if c.busy and not c.closed] def clean(self): """Clean the pool by removing any closed connections and if the pool's idle has exceeded its idle TTL, remove all connections. """ LOGGER.debug('Cleaning the pool') for connection in [self.connections[k] for k in self.connections if self.connections[k].closed]: LOGGER.debug('Removing %s', connection.id) self.remove(connection.handle) if self.idle_duration > self.idle_ttl: self.close() LOGGER.debug('Pool %s cleaned', self.id) def close(self): """Close the pool by closing and removing all of the connections""" for cid in list(self.connections.keys()): self.remove(self.connections[cid].handle) LOGGER.debug('Pool %s closed', self.id) @property def closed_connections(self): """Return a list of closed connections :rtype: list """ return [c for c in self.connections.values() if c.closed] def connection_handle(self, connection): """Return a connection object for the given psycopg2 connection :param connection: The connection to return a parent for :type connection: psycopg2.extensions.connection :rtype: Connection """ return self.connections[id(connection)] @property def executing_connections(self): """Return a list of connections actively executing queries :rtype: list """ return [c for c in self.connections.values() if c.executing] def free(self, connection): """Free the connection from use by the session that was using it. :param connection: The connection to free :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError """ LOGGER.debug('Pool %s freeing connection %s', self.id, id(connection)) try: self.connection_handle(connection).free() except KeyError: raise ConnectionNotFoundError(self.id, id(connection)) if self.idle_connections == list(self.connections.values()): with self._lock: self.idle_start = self.time_method() LOGGER.debug('Pool %s freed connection %s', self.id, id(connection)) def get(self, session): """Return an idle connection and assign the session to the connection :param queries.Session session: The session to assign :rtype: psycopg2.extensions.connection :raises: NoIdleConnectionsError """ idle = self.idle_connections if idle: connection = idle.pop(0) connection.lock(session) if self.idle_start: with self._lock: self.idle_start = None return connection.handle raise NoIdleConnectionsError(self.id) @property def id(self): """Return the ID for this pool :rtype: str """ return self._id @property def idle_connections(self): """Return a list of idle connections :rtype: list """ return [c for c in self.connections.values() if not c.busy and not c.closed] @property def idle_duration(self): """Return the number of seconds that the pool has had no active connections. :rtype: float """ if self.idle_start is None: return 0 return self.time_method() - self.idle_start @property def is_full(self): """Return True if there are no more open slots for connections. :rtype: bool """ return len(self.connections) >= self.max_size def lock(self, connection, session): """Explicitly lock the specified connection :type connection: psycopg2.extensions.connection :param connection: The connection to lock :param queries.Session session: The session to hold the lock """ cid = id(connection) try: self.connection_handle(connection).lock(session) except KeyError: raise ConnectionNotFoundError(self.id, cid) else: if self.idle_start: with self._lock: self.idle_start = None LOGGER.debug('Pool %s locked connection %s', self.id, cid) @property def locked_connections(self): """Return a list of all locked connections :rtype: list """ return [c for c in self.connections.values() if c.locked] def remove(self, connection): """Remove the connection from the pool :param connection: The connection to remove :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError :raises: ConnectionBusyError """ cid = id(connection) if cid not in self.connections: raise ConnectionNotFoundError(self.id, cid) self.connection_handle(connection).close() with self._lock: del self.connections[cid] LOGGER.debug('Pool %s removed connection %s', self.id, cid) def report(self): """Return a report about the pool state and configuration. :rtype: dict """ return { 'connections': { 'busy': len(self.busy_connections), 'closed': len(self.closed_connections), 'executing': len(self.executing_connections), 'idle': len(self.idle_connections), 'locked': len(self.busy_connections) }, 'exceptions': sum([c.exceptions for c in self.connections.values()]), 'executions': sum([c.executions for c in self.connections.values()]), 'full': self.is_full, 'idle': { 'duration': self.idle_duration, 'ttl': self.idle_ttl }, 'max_size': self.max_size } def shutdown(self): """Forcefully shutdown the entire pool, closing all non-executing connections. :raises: ConnectionBusyError """ with self._lock: for cid in list(self.connections.keys()): if self.connections[cid].executing: raise ConnectionBusyError(cid) if self.connections[cid].locked: self.connections[cid].free() self.connections[cid].close() del self.connections[cid] def set_idle_ttl(self, ttl): """Set the idle ttl :param int ttl: The TTL when idle """ with self._lock: self.idle_ttl = ttl def set_max_size(self, size): """Set the maximum number of connections :param int size: The maximum number of connections """ with self._lock: self.max_size = size class PoolManager(object): """The connection pool object implements behavior around connections and their use in queries.Session objects. We carry a pool id instead of the connection URI so that we will not be carrying the URI in memory, creating a possible security issue. """ _lock = threading.Lock() _pools = {} def __contains__(self, pid): """Returns True if the pool exists :param str pid: The pool id to check for :rtype: bool """ return pid in self.__class__._pools @classmethod def instance(cls): """Only allow a single PoolManager instance to exist, returning the handle for it. :rtype: PoolManager """ if not hasattr(cls, '_instance'): with cls._lock: cls._instance = cls() return cls._instance @classmethod def add(cls, pid, connection): """Add a new connection and session to a pool. :param str pid: The pool id :type connection: psycopg2.extensions.connection :param connection: The connection to add to the pool """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].add(connection) @classmethod def clean(cls, pid): """Clean the specified pool, removing any closed connections or stale locks. :param str pid: The pool id to clean """ with cls._lock: try: cls._ensure_pool_exists(pid) except KeyError: LOGGER.debug('Pool clean invoked against missing pool %s', pid) return cls._pools[pid].clean() cls._maybe_remove_pool(pid) @classmethod def create(cls, pid, idle_ttl=DEFAULT_IDLE_TTL, max_size=DEFAULT_MAX_SIZE, time_method=None): """Create a new pool, with the ability to pass in values to override the default idle TTL and the default maximum size. A pool's idle TTL defines the amount of time that a pool can be open without any sessions before it is removed. A pool's max size defines the maximum number of connections that can be added to the pool to prevent unbounded open connections. :param str pid: The pool ID :param int idle_ttl: Time in seconds for the idle TTL :param int max_size: The maximum pool size :param callable time_method: Override the use of :py:meth:`time.time` method for time values. :raises: KeyError """ if pid in cls._pools: raise KeyError('Pool %s already exists' % pid) with cls._lock: LOGGER.debug("Creating Pool: %s (%i/%i)", pid, idle_ttl, max_size) cls._pools[pid] = Pool(pid, idle_ttl, max_size, time_method) @classmethod def free(cls, pid, connection): """Free a connection that was locked by a session :param str pid: The pool ID :param connection: The connection to remove :type connection: psycopg2.extensions.connection """ with cls._lock: LOGGER.debug('Freeing %s from pool %s', id(connection), pid) cls._ensure_pool_exists(pid) cls._pools[pid].free(connection) @classmethod def get(cls, pid, session): """Get an idle, unused connection from the pool. Once a connection has been retrieved, it will be marked as in-use until it is freed. :param str pid: The pool ID :param queries.Session session: The session to assign to the connection :rtype: psycopg2.extensions.connection """ with cls._lock: cls._ensure_pool_exists(pid) return cls._pools[pid].get(session) @classmethod def get_connection(cls, pid, connection): """Return the specified :class:`~queries.pool.Connection` from the pool. :param str pid: The pool ID :param connection: The connection to return for :type connection: psycopg2.extensions.connection :rtype: queries.pool.Connection """ with cls._lock: return cls._pools[pid].connection_handle(connection) @classmethod def has_connection(cls, pid, connection): """Check to see if a pool has the specified connection :param str pid: The pool ID :param connection: The connection to check for :type connection: psycopg2.extensions.connection :rtype: bool """ with cls._lock: cls._ensure_pool_exists(pid) return connection in cls._pools[pid] @classmethod def has_idle_connection(cls, pid): """Check to see if a pool has an idle connection :param str pid: The pool ID :rtype: bool """ with cls._lock: cls._ensure_pool_exists(pid) return bool(cls._pools[pid].idle_connections) @classmethod def is_full(cls, pid): """Return a bool indicating if the specified pool is full :param str pid: The pool id :rtype: bool """ with cls._lock: cls._ensure_pool_exists(pid) return cls._pools[pid].is_full @classmethod def lock(cls, pid, connection, session): """Explicitly lock the specified connection in the pool :param str pid: The pool id :type connection: psycopg2.extensions.connection :param connection: The connection to add to the pool :param queries.Session session: The session to hold the lock """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].lock(connection, session) @classmethod def remove(cls, pid): """Remove a pool, closing all connections :param str pid: The pool ID """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].close() del cls._pools[pid] @classmethod def remove_connection(cls, pid, connection): """Remove a connection from the pool, closing it if is open. :param str pid: The pool ID :param connection: The connection to remove :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError """ cls._ensure_pool_exists(pid) cls._pools[pid].remove(connection) @classmethod def set_idle_ttl(cls, pid, ttl): """Set the idle TTL for a pool, after which it will be destroyed. :param str pid: The pool id :param int ttl: The TTL for an idle pool """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].set_idle_ttl(ttl) @classmethod def set_max_size(cls, pid, size): """Set the maximum number of connections for the specified pool :param str pid: The pool to set the size for :param int size: The maximum number of connections """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].set_max_size(size) @classmethod def shutdown(cls): """Close all connections on in all pools""" for pid in list(cls._pools.keys()): cls._pools[pid].shutdown() LOGGER.info('Shutdown complete, all pooled connections closed') @classmethod def size(cls, pid): """Return the number of connections in the pool :param str pid: The pool id :rtype int """ with cls._lock: cls._ensure_pool_exists(pid) return len(cls._pools[pid]) @classmethod def report(cls): """Return the state of the all of the registered pools. :rtype: dict """ return { 'timestamp': datetime.datetime.utcnow().isoformat(), 'process': os.getpid(), 'pools': dict([(i, p.report()) for i, p in cls._pools.items()]) } @classmethod def _ensure_pool_exists(cls, pid): """Raise an exception if the pool has yet to be created or has been removed. :param str pid: The pool ID to check for :raises: KeyError """ if pid not in cls._pools: raise KeyError('Pool %s has not been created' % pid) @classmethod def _maybe_remove_pool(cls, pid): """If the pool has no open connections, remove it :param str pid: The pool id to clean """ if not len(cls._pools[pid]): del cls._pools[pid] class QueriesException(Exception): """Base Exception for all other Queries exceptions""" pass class ConnectionException(QueriesException): def __init__(self, cid): self.cid = cid class PoolException(QueriesException): def __init__(self, pid): self.pid = pid class PoolConnectionException(PoolException): def __init__(self, pid, cid): self.pid = pid self.cid = cid class ActivePoolError(PoolException): """Raised when removing a pool that has active connections""" def __str__(self): return 'Pool %s has at least one active connection' % self.pid class ConnectionBusyError(ConnectionException): """Raised when trying to lock a connection that is already busy""" def __str__(self): return 'Connection %s is busy' % self.cid class ConnectionNotFoundError(PoolConnectionException): """Raised if a specific connection is not found in the pool""" def __str__(self): return 'Connection %s not found in pool %s' % (self.cid, self.pid) class NoIdleConnectionsError(PoolException): """Raised if a pool does not have any idle, open connections""" def __str__(self): return 'Pool %s has no idle connections' % self.pid class PoolFullError(PoolException): """Raised when adding a connection to a pool that has hit max-size""" def __str__(self): return 'Pool %s is at its maximum capacity' % self.pid <MSG> queries.pool: Iterate over connection.keys() in close method. This commit alters pool.close() so that it iterates over connection.keys() rather than connection. This is to address an issue where the call to pool.remove() deletes from connections, which causes a RuntimeError for deleting while iterating over the dictionary. <DFF> @@ -156,7 +156,7 @@ class Pool(object): def close(self): """Close the pool by closing and removing all of the connections""" - for cid in self.connections: + for cid in self.connections.keys(): self.remove(self.connections[cid].handle) LOGGER.debug('Pool %s closed', self.id)
1
queries.pool: Iterate over connection.keys() in close method.
1
.py
py
bsd-3-clause
gmr/queries
1601
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<3'] else: install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setuptools.setup( name='queries', version='2.1.0', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy', maintainer_email='[email protected]', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Topic :: Software Development :: Libraries'] setup(name='queries', version='1.7.3', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]", 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Bump the version <DFF> @@ -30,7 +30,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.7.3', + version='1.7.4', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]",
1
Bump the version
1
.py
py
bsd-3-clause
gmr/queries
1602
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<3'] else: install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setuptools.setup( name='queries', version='2.1.0', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy', maintainer_email='[email protected]', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Topic :: Software Development :: Libraries'] setup(name='queries', version='1.7.3', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]", 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Bump the version <DFF> @@ -30,7 +30,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.7.3', + version='1.7.4', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]",
1
Bump the version
1
.py
py
bsd-3-clause
gmr/queries
1603
<NME> tests.py <BEF> ADDFILE <MSG> Initial tests adding coverage of connection caching <DFF> @@ -0,0 +1,84 @@ +""" +Tests for the pgsql_wrapper module + +""" +import mock +import time + +try: + import unittest2 +except ImportError: + import unittest + +import pgsql_wrapper + + +class ConnectionCachingTests(unittest.TestCase): + + def setUp(self): + pgsql_wrapper._add_cached_connection('cc0', self.__class__) + + def tearDown(self): + for key in ['cc0', 'cc1', 'cc2', 'cc3', 'cc4']: + if key in pgsql_wrapper.CONNECTIONS: + del pgsql_wrapper.CONNECTIONS[key] + + def test_generate_hash(self): + """DSN hash generation yields expected value""" + value = 'host=localhost;port=5432;user=postgres;dbname=postgres' + expectation = 'e73e565b90b37655fdccad5006339f608a1f7482' + self.assertEqual(pgsql_wrapper._generate_connection_hash(value), + expectation) + + def test_add_cached_connection_adds_value(self): + """Cconnection should already exist in the connection cache""" + self.assertIn('cc0', pgsql_wrapper.CONNECTIONS) + + def test_get_cached_connection_returns_proper_value(self): + """Fetching cached connection returns proper value""" + self.assertEqual(pgsql_wrapper._get_cached_connection('cc0'), + self.__class__) + + def test_get_cached_connection_increments_counter(self): + """Fetching cached connection increments client counter""" + value = pgsql_wrapper.CONNECTIONS.get('cc0', {}).get('clients', 0) + pgsql_wrapper._get_cached_connection('cc0') + self.assertEqual(pgsql_wrapper.CONNECTIONS['cc0']['clients'], + value + 1) + + def test_add_cached_connection_new(self): + """Adding a new connection to module cache returns True""" + self.assertTrue(pgsql_wrapper._add_cached_connection('cc1', True)) + + def test_add_cached_connection_existing(self): + """Adding an existing connection to module cache returns False""" + pgsql_wrapper._add_cached_connection('cc2', True) + self.assertFalse(pgsql_wrapper._add_cached_connection('cc2', True)) + + def test_new_then_freed_cached_connection_has_no_clients(self): + """Freeing connection with one client should decrement counter""" + pgsql_wrapper._add_cached_connection('cc3', True) + pgsql_wrapper._free_cached_connection('cc3') + self.assertEqual(pgsql_wrapper.CONNECTIONS['cc3']['clients'], 0) + + def test_free_cached_connection(self): + """Freeing connection should update last timestamp""" + pgsql_wrapper._add_cached_connection('cc4', True) + pgsql_wrapper._free_cached_connection('cc4') + self.assertAlmostEqual(pgsql_wrapper.CONNECTIONS['cc4']['last_client'], + int(time.time())) + + +class ConnectionCacheExpirationTests(unittest.TestCase): + + def setUp(self): + pgsql_wrapper._add_cached_connection('cce_test', self.__class__) + + def test_cache_expiration(self): + """Check that unused connection expires""" + return_value = time.time() - pgsql_wrapper.CACHE_TTL - 1 + with mock.patch('time.time') as ptime: + ptime.return_value = return_value + pgsql_wrapper._free_cached_connection('cce_test') + pgsql_wrapper._check_for_unused_expired_connections() + self.assertNotIn('cce_test', pgsql_wrapper.CONNECTIONS)
84
Initial tests adding coverage of connection caching
0
.py
py
bsd-3-clause
gmr/queries
1604
<NME> tests.py <BEF> ADDFILE <MSG> Initial tests adding coverage of connection caching <DFF> @@ -0,0 +1,84 @@ +""" +Tests for the pgsql_wrapper module + +""" +import mock +import time + +try: + import unittest2 +except ImportError: + import unittest + +import pgsql_wrapper + + +class ConnectionCachingTests(unittest.TestCase): + + def setUp(self): + pgsql_wrapper._add_cached_connection('cc0', self.__class__) + + def tearDown(self): + for key in ['cc0', 'cc1', 'cc2', 'cc3', 'cc4']: + if key in pgsql_wrapper.CONNECTIONS: + del pgsql_wrapper.CONNECTIONS[key] + + def test_generate_hash(self): + """DSN hash generation yields expected value""" + value = 'host=localhost;port=5432;user=postgres;dbname=postgres' + expectation = 'e73e565b90b37655fdccad5006339f608a1f7482' + self.assertEqual(pgsql_wrapper._generate_connection_hash(value), + expectation) + + def test_add_cached_connection_adds_value(self): + """Cconnection should already exist in the connection cache""" + self.assertIn('cc0', pgsql_wrapper.CONNECTIONS) + + def test_get_cached_connection_returns_proper_value(self): + """Fetching cached connection returns proper value""" + self.assertEqual(pgsql_wrapper._get_cached_connection('cc0'), + self.__class__) + + def test_get_cached_connection_increments_counter(self): + """Fetching cached connection increments client counter""" + value = pgsql_wrapper.CONNECTIONS.get('cc0', {}).get('clients', 0) + pgsql_wrapper._get_cached_connection('cc0') + self.assertEqual(pgsql_wrapper.CONNECTIONS['cc0']['clients'], + value + 1) + + def test_add_cached_connection_new(self): + """Adding a new connection to module cache returns True""" + self.assertTrue(pgsql_wrapper._add_cached_connection('cc1', True)) + + def test_add_cached_connection_existing(self): + """Adding an existing connection to module cache returns False""" + pgsql_wrapper._add_cached_connection('cc2', True) + self.assertFalse(pgsql_wrapper._add_cached_connection('cc2', True)) + + def test_new_then_freed_cached_connection_has_no_clients(self): + """Freeing connection with one client should decrement counter""" + pgsql_wrapper._add_cached_connection('cc3', True) + pgsql_wrapper._free_cached_connection('cc3') + self.assertEqual(pgsql_wrapper.CONNECTIONS['cc3']['clients'], 0) + + def test_free_cached_connection(self): + """Freeing connection should update last timestamp""" + pgsql_wrapper._add_cached_connection('cc4', True) + pgsql_wrapper._free_cached_connection('cc4') + self.assertAlmostEqual(pgsql_wrapper.CONNECTIONS['cc4']['last_client'], + int(time.time())) + + +class ConnectionCacheExpirationTests(unittest.TestCase): + + def setUp(self): + pgsql_wrapper._add_cached_connection('cce_test', self.__class__) + + def test_cache_expiration(self): + """Check that unused connection expires""" + return_value = time.time() - pgsql_wrapper.CACHE_TTL - 1 + with mock.patch('time.time') as ptime: + ptime.return_value = return_value + pgsql_wrapper._free_cached_connection('cce_test') + pgsql_wrapper._check_for_unused_expired_connections() + self.assertNotIn('cce_test', pgsql_wrapper.CONNECTIONS)
84
Initial tests adding coverage of connection caching
0
.py
py
bsd-3-clause
gmr/queries
1605
<NME> tornado_session.py <BEF> """ Tornado Session Adapter Use Queries asynchronously within the Tornado framework. Example Use: .. code:: python class NameListHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession(pool_max_size=60) @gen.coroutine def get(self): data = yield self.session.query('SELECT * FROM names') if data: self.finish({'names': data.items()}) data.free() else: self.set_status(500, 'Error querying the data') """ import logging import socket import warnings from tornado import concurrent, ioloop from psycopg2 import extras, extensions import psycopg2 from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) DEFAULT_MAX_POOL_SIZE = 25 class Results(results.Results): """A TornadoSession specific :py:class:`queries.Results` class that adds the :py:meth:`Results.free <queries.tornado_session.Results.free>` method. The :py:meth:`Results.free <queries.tornado_session.Results.free>` method **must** be called to free the connection that the results were generated on. `Results` objects that are not freed will cause the connections to remain locked and your application will eventually run out of connections in the pool. The following examples illustrate the various behaviors that the ::py:class:`queries.Results <queries.tornado_session.Requests>` class implements: **Using Results as an Iterator** .. code:: python results = yield session.query('SELECT * FROM foo') for row in results print row results.free() **Accessing an individual row by index** .. code:: python results = yield session.query('SELECT * FROM foo') print results[1] # Access the second row of the results results.free() **Casting single row results as a dict** .. code:: python results = yield session.query('SELECT * FROM foo LIMIT 1') print results.as_dict() results.free() **Checking to see if a query was successful** .. code:: python sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'" results = yield session.query(sql) if results: print 'Success' results.free() **Checking the number of rows by using len(Results)** .. code:: python results = yield session.query('SELECT * FROM foo') print '%i rows' % len(results) results.free() """ def __init__(self, cursor, cleanup, fd): self.cursor = cursor self._cleanup = cleanup self._fd = fd self._freed = False def free(self): """Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or the connection will not be able to be reused by other asynchronous requests. """ self._freed = True self._cleanup(self.cursor, self._fd) def __del__(self): if not self._freed: LOGGER.warning('Auto-freeing result on deletion') self.free() class TornadoSession(session.Session): """Session class for Tornado asynchronous applications. Uses :py:func:`tornado.gen.coroutine` to wrap API methods for use in Tornado. Utilizes connection pooling to ensure that multiple concurrent asynchronous queries do not block each other. Heavily trafficked services will require a higher ``max_pool_size`` to allow for greater connection concurrency. :py:meth:`TornadoSession.query <queries.TornadoSession.query>` and :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` must call :py:meth:`Results.free <queries.tornado_session.Results.free>` :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use """ def __init__(self, uri=session.DEFAULT_URI, cursor_factory=extras.RealDictCursor, pool_idle_ttl=pool.DEFAULT_IDLE_TTL, pool_max_size=DEFAULT_MAX_POOL_SIZE, io_loop=None): """Connect to a PostgreSQL server using the module wide connection and set the isolation level. :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use :param tornado.ioloop.IOLoop io_loop: IOLoop instance to use """ self._connections = dict() self._cleanup_callback = None self._cursor_factory = cursor_factory self._futures = dict() self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() self._pool_max_size = pool_max_size self._pool_idle_ttl = pool_idle_ttl self._uri = uri self._ensure_pool_exists() def _ensure_pool_exists(self): """Create the pool in the pool manager if it does not exist.""" if self.pid not in self._pool_manager: self._pool_manager.create(self.pid, self._pool_idle_ttl, self._pool_max_size, self._ioloop.time) @property def connection(self): """Do not use this directly with Tornado applications :return: """ return None @property def cursor(self): return None def callproc(self, name, args=None): """Call a stored procedure asynchronously on the server, passing in the arguments to be passed to the stored procedure, yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str name: The stored procedure name :param list args: An optional list of procedure arguments :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('callproc', name, args) def query(self, sql, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('execute', sql, parameters) def validate(self): """Validate the session can connect or has open connections to PostgreSQL. As of ``1.10.3`` .. deprecated:: 1.10.3 As of 1.10.3, this method only warns about Deprecation :rtype: bool """ warnings.warn( 'All functionality removed from this method', DeprecationWarning) def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool if possible, or by creating the new connection. :rtype: psycopg2.extensions.connection :raises: pool.NoIdleConnectionsError """ future = concurrent.Future() # Attempt to get a cached connection from the connection pool try: connection = self._pool_manager.get(self.pid, self) self._connections[connection.fileno()] = connection future.set_result(connection) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) except pool.NoIdleConnectionsError: self._create_connection(future) return future def _create_connection(self, future): """Create a new PostgreSQL connection :param tornado.concurrent.Future future: future for new conn result """ LOGGER.debug('Creating a new connection for %s', self.pid) # Create a new PostgreSQL connection kwargs = utils.uri_to_kwargs(self._uri) try: connection = self._psycopg2_connect(kwargs) except (psycopg2.Error, OSError, socket.error) as error: future.set_exception(error) return # Add the connection for use in _poll_connection fd = connection.fileno() self._connections[fd] = connection def on_connected(cf): """Invoked by the IOLoop when the future is complete for the connection :param Future cf: The future for the initial connection """ if cf.exception(): self._cleanup_fd(fd, True) future.set_exception(cf.exception()) else: try: # Add the connection to the pool LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) except (ValueError, pool.PoolException) as err: LOGGER.exception('Failed to add %r to the pool', self.pid) self._cleanup_fd(fd) future.set_exception(err) return self._pool_manager.lock(self.pid, connection, self) # Added in because psycopg2cffi connects and leaves the # connection in a weird state: consts.STATUS_DATESTYLE, # returning from Connection._setup without setting the state # as const.STATUS_OK if utils.PYPY: connection.status = extensions.STATUS_READY # Register the custom data types self._register_unicode(connection) self._register_uuid(connection) # Set the future result future.set_result(connection) # Add a future that fires once connected self._futures[fd] = concurrent.Future() self._ioloop.add_future(self._futures[fd], on_connected) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) def _execute(self, method, query, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. This function reduces duplicate code for callproc and query by getting the class attribute for the method passed in as the function to call. :param str method: The method attribute to use :param str query: The SQL statement or Stored Procedure name :param list|dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ future = concurrent.Future() def on_connected(cf): """Invoked by the future returned by self._connect""" if cf.exception(): future.set_exception(cf.exception()) return # Get the psycopg2 connection object and cursor conn = cf.result() cursor = self._get_cursor(conn) def completed(qf): """Invoked by the IOLoop when the future has completed""" if qf.exception(): self._incr_exceptions(conn) err = qf.exception() LOGGER.debug('Cleaning cursor due to exception: %r', err) self._exec_cleanup(cursor, conn.fileno()) future.set_exception(err) else: self._incr_executions(conn) value = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(value) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.Future() # Add the future to the IOLoop self._ioloop.add_future(self._futures[conn.fileno()], completed) # Get the cursor, execute the query func = getattr(cursor, method) try: func(query, parameters) except Exception as error: future.set_exception(error) # Ensure the pool exists for the connection self._ensure_pool_exists() # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. :param psycopg2.extensions.cursor cursor: The cursor to close :param int fd: The connection file descriptor """ LOGGER.debug('Closing cursor and cleaning %s', fd) try: cursor.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.debug('Error closing the cursor: %s', error) # Return the future for the query result return future @gen.engine def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. # Create a new cleanup callback to clean the pool of idle connections self._cleanup_callback = self._ioloop.add_timeout( self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) def _cleanup_fd(self, fd, close=False): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. :param int fd: The fd # to cleanup del self._futures[fd] self._ioloop.remove_handler(fd) raise gen.Return() @gen.coroutine def _on_io_events(self, fd=None, events=None): except pool.ConnectionNotFoundError: pass if close: self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd] def _incr_exceptions(self, conn): """Increment the number of exceptions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).exceptions += 1 def _incr_executions(self, conn): """Increment the number of executions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).executions += 1 def _on_io_events(self, fd=None, _events=None): """Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised """ if fd not in self._connections: LOGGER.warning('Received IO event for non-existing connection') return self._poll_connection(fd) def _poll_connection(self, fd): """Check with psycopg2 to see what action to take. If the state is POLL_OK, we should have a pending callback for that fd. :param int fd: The socket fd for the postgresql connection """ try: state = self._connections[fd].poll() except (OSError, socket.error) as error: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.OperationalError('Connection error (%s)' % error) ) except (psycopg2.Error, psycopg2.Warning) as error: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception(error) else: if state == extensions.POLL_OK: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_result(True) elif state == extensions.POLL_WRITE: self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE) elif state == extensions.POLL_READ: self._ioloop.update_handler(fd, ioloop.IOLoop.READ) elif state == extensions.POLL_ERROR: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.Error('Poll Error')) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. :param dict kwargs: Keyword connection args :rtype: psycopg2.extensions.connection """ kwargs['async'] = True return psycopg2.connect(**kwargs) <MSG> No need to wrap _exec_cleanup with @gen.engine <DFF> @@ -421,7 +421,6 @@ class TornadoSession(session.Session): # Return the future for the query result return future - @gen.engine def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. @@ -439,7 +438,6 @@ class TornadoSession(session.Session): del self._futures[fd] self._ioloop.remove_handler(fd) - raise gen.Return() @gen.coroutine def _on_io_events(self, fd=None, events=None):
0
No need to wrap _exec_cleanup with @gen.engine
2
.py
py
bsd-3-clause
gmr/queries
1606
<NME> tornado_session.py <BEF> """ Tornado Session Adapter Use Queries asynchronously within the Tornado framework. Example Use: .. code:: python class NameListHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession(pool_max_size=60) @gen.coroutine def get(self): data = yield self.session.query('SELECT * FROM names') if data: self.finish({'names': data.items()}) data.free() else: self.set_status(500, 'Error querying the data') """ import logging import socket import warnings from tornado import concurrent, ioloop from psycopg2 import extras, extensions import psycopg2 from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) DEFAULT_MAX_POOL_SIZE = 25 class Results(results.Results): """A TornadoSession specific :py:class:`queries.Results` class that adds the :py:meth:`Results.free <queries.tornado_session.Results.free>` method. The :py:meth:`Results.free <queries.tornado_session.Results.free>` method **must** be called to free the connection that the results were generated on. `Results` objects that are not freed will cause the connections to remain locked and your application will eventually run out of connections in the pool. The following examples illustrate the various behaviors that the ::py:class:`queries.Results <queries.tornado_session.Requests>` class implements: **Using Results as an Iterator** .. code:: python results = yield session.query('SELECT * FROM foo') for row in results print row results.free() **Accessing an individual row by index** .. code:: python results = yield session.query('SELECT * FROM foo') print results[1] # Access the second row of the results results.free() **Casting single row results as a dict** .. code:: python results = yield session.query('SELECT * FROM foo LIMIT 1') print results.as_dict() results.free() **Checking to see if a query was successful** .. code:: python sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'" results = yield session.query(sql) if results: print 'Success' results.free() **Checking the number of rows by using len(Results)** .. code:: python results = yield session.query('SELECT * FROM foo') print '%i rows' % len(results) results.free() """ def __init__(self, cursor, cleanup, fd): self.cursor = cursor self._cleanup = cleanup self._fd = fd self._freed = False def free(self): """Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or the connection will not be able to be reused by other asynchronous requests. """ self._freed = True self._cleanup(self.cursor, self._fd) def __del__(self): if not self._freed: LOGGER.warning('Auto-freeing result on deletion') self.free() class TornadoSession(session.Session): """Session class for Tornado asynchronous applications. Uses :py:func:`tornado.gen.coroutine` to wrap API methods for use in Tornado. Utilizes connection pooling to ensure that multiple concurrent asynchronous queries do not block each other. Heavily trafficked services will require a higher ``max_pool_size`` to allow for greater connection concurrency. :py:meth:`TornadoSession.query <queries.TornadoSession.query>` and :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` must call :py:meth:`Results.free <queries.tornado_session.Results.free>` :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use """ def __init__(self, uri=session.DEFAULT_URI, cursor_factory=extras.RealDictCursor, pool_idle_ttl=pool.DEFAULT_IDLE_TTL, pool_max_size=DEFAULT_MAX_POOL_SIZE, io_loop=None): """Connect to a PostgreSQL server using the module wide connection and set the isolation level. :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use :param tornado.ioloop.IOLoop io_loop: IOLoop instance to use """ self._connections = dict() self._cleanup_callback = None self._cursor_factory = cursor_factory self._futures = dict() self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() self._pool_max_size = pool_max_size self._pool_idle_ttl = pool_idle_ttl self._uri = uri self._ensure_pool_exists() def _ensure_pool_exists(self): """Create the pool in the pool manager if it does not exist.""" if self.pid not in self._pool_manager: self._pool_manager.create(self.pid, self._pool_idle_ttl, self._pool_max_size, self._ioloop.time) @property def connection(self): """Do not use this directly with Tornado applications :return: """ return None @property def cursor(self): return None def callproc(self, name, args=None): """Call a stored procedure asynchronously on the server, passing in the arguments to be passed to the stored procedure, yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str name: The stored procedure name :param list args: An optional list of procedure arguments :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('callproc', name, args) def query(self, sql, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('execute', sql, parameters) def validate(self): """Validate the session can connect or has open connections to PostgreSQL. As of ``1.10.3`` .. deprecated:: 1.10.3 As of 1.10.3, this method only warns about Deprecation :rtype: bool """ warnings.warn( 'All functionality removed from this method', DeprecationWarning) def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool if possible, or by creating the new connection. :rtype: psycopg2.extensions.connection :raises: pool.NoIdleConnectionsError """ future = concurrent.Future() # Attempt to get a cached connection from the connection pool try: connection = self._pool_manager.get(self.pid, self) self._connections[connection.fileno()] = connection future.set_result(connection) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) except pool.NoIdleConnectionsError: self._create_connection(future) return future def _create_connection(self, future): """Create a new PostgreSQL connection :param tornado.concurrent.Future future: future for new conn result """ LOGGER.debug('Creating a new connection for %s', self.pid) # Create a new PostgreSQL connection kwargs = utils.uri_to_kwargs(self._uri) try: connection = self._psycopg2_connect(kwargs) except (psycopg2.Error, OSError, socket.error) as error: future.set_exception(error) return # Add the connection for use in _poll_connection fd = connection.fileno() self._connections[fd] = connection def on_connected(cf): """Invoked by the IOLoop when the future is complete for the connection :param Future cf: The future for the initial connection """ if cf.exception(): self._cleanup_fd(fd, True) future.set_exception(cf.exception()) else: try: # Add the connection to the pool LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) except (ValueError, pool.PoolException) as err: LOGGER.exception('Failed to add %r to the pool', self.pid) self._cleanup_fd(fd) future.set_exception(err) return self._pool_manager.lock(self.pid, connection, self) # Added in because psycopg2cffi connects and leaves the # connection in a weird state: consts.STATUS_DATESTYLE, # returning from Connection._setup without setting the state # as const.STATUS_OK if utils.PYPY: connection.status = extensions.STATUS_READY # Register the custom data types self._register_unicode(connection) self._register_uuid(connection) # Set the future result future.set_result(connection) # Add a future that fires once connected self._futures[fd] = concurrent.Future() self._ioloop.add_future(self._futures[fd], on_connected) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) def _execute(self, method, query, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. This function reduces duplicate code for callproc and query by getting the class attribute for the method passed in as the function to call. :param str method: The method attribute to use :param str query: The SQL statement or Stored Procedure name :param list|dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ future = concurrent.Future() def on_connected(cf): """Invoked by the future returned by self._connect""" if cf.exception(): future.set_exception(cf.exception()) return # Get the psycopg2 connection object and cursor conn = cf.result() cursor = self._get_cursor(conn) def completed(qf): """Invoked by the IOLoop when the future has completed""" if qf.exception(): self._incr_exceptions(conn) err = qf.exception() LOGGER.debug('Cleaning cursor due to exception: %r', err) self._exec_cleanup(cursor, conn.fileno()) future.set_exception(err) else: self._incr_executions(conn) value = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(value) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.Future() # Add the future to the IOLoop self._ioloop.add_future(self._futures[conn.fileno()], completed) # Get the cursor, execute the query func = getattr(cursor, method) try: func(query, parameters) except Exception as error: future.set_exception(error) # Ensure the pool exists for the connection self._ensure_pool_exists() # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. :param psycopg2.extensions.cursor cursor: The cursor to close :param int fd: The connection file descriptor """ LOGGER.debug('Closing cursor and cleaning %s', fd) try: cursor.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.debug('Error closing the cursor: %s', error) # Return the future for the query result return future @gen.engine def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. # Create a new cleanup callback to clean the pool of idle connections self._cleanup_callback = self._ioloop.add_timeout( self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) def _cleanup_fd(self, fd, close=False): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. :param int fd: The fd # to cleanup del self._futures[fd] self._ioloop.remove_handler(fd) raise gen.Return() @gen.coroutine def _on_io_events(self, fd=None, events=None): except pool.ConnectionNotFoundError: pass if close: self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd] def _incr_exceptions(self, conn): """Increment the number of exceptions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).exceptions += 1 def _incr_executions(self, conn): """Increment the number of executions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).executions += 1 def _on_io_events(self, fd=None, _events=None): """Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised """ if fd not in self._connections: LOGGER.warning('Received IO event for non-existing connection') return self._poll_connection(fd) def _poll_connection(self, fd): """Check with psycopg2 to see what action to take. If the state is POLL_OK, we should have a pending callback for that fd. :param int fd: The socket fd for the postgresql connection """ try: state = self._connections[fd].poll() except (OSError, socket.error) as error: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.OperationalError('Connection error (%s)' % error) ) except (psycopg2.Error, psycopg2.Warning) as error: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception(error) else: if state == extensions.POLL_OK: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_result(True) elif state == extensions.POLL_WRITE: self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE) elif state == extensions.POLL_READ: self._ioloop.update_handler(fd, ioloop.IOLoop.READ) elif state == extensions.POLL_ERROR: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.Error('Poll Error')) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. :param dict kwargs: Keyword connection args :rtype: psycopg2.extensions.connection """ kwargs['async'] = True return psycopg2.connect(**kwargs) <MSG> No need to wrap _exec_cleanup with @gen.engine <DFF> @@ -421,7 +421,6 @@ class TornadoSession(session.Session): # Return the future for the query result return future - @gen.engine def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. @@ -439,7 +438,6 @@ class TornadoSession(session.Session): del self._futures[fd] self._ioloop.remove_handler(fd) - raise gen.Return() @gen.coroutine def _on_io_events(self, fd=None, events=None):
0
No need to wrap _exec_cleanup with @gen.engine
2
.py
py
bsd-3-clause
gmr/queries
1607
<NME> README.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. Check out the `Usage`_ section below to see how easy it can be. Key features include: - Simplified API - Support of Python 2.7+ and 3.4+ - PyPy support via psycopg2cffi_ - Asynchronous support for Tornado_ - Connection information provided by URI ------------ queries is available via pypi and can be installed with easy_install or pip: ..code:: bash pip install queries Documentation ------------- Documentation is available at https://queries.readthedocs.org Installation ------------ Queries is available via pypi_ and can be installed with easy_install or pip: .. code:: bash pip install queries Usage ----- Queries provides a session based API for interacting with PostgreSQL. Simply pass in the URI_ of the PostgreSQL server to connect to when creating a session: .. code:: python session = queries.Session("postgresql://postgres@localhost:5432/postgres") Queries built-in connection pooling will re-use connections when possible, lowering the overhead of connecting and reconnecting. When specifying a URI, if you omit the username and database name to connect with, Queries will use the current OS username for both. You can also omit the URI when connecting to connect to localhost on port 5432 as the current OS user, connecting to a database named for the current user. For example, if your username is ``fred`` and you omit the URI when issuing ``queries.query`` the URI that is constructed would be ``postgresql://fred@localhost:5432/fred``. If you'd rather use individual values for the connection, the queries.uri() method provides a quick and easy way to create a URI to pass into the various methods. .. code:: python >>> queries.uri("server-name", 5432, "dbname", "user", "pass") 'postgresql://user:pass@server-name:5432/dbname' Environment Variables ^^^^^^^^^^^^^^^^^^^^^ Currently Queries uses the following environment variables for tweaking various configuration values. The supported ones are: * ``QUERIES_MAX_POOL_SIZE`` - Modify the maximum size of the connection pool (default: 1) Using the queries.Session class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To execute queries or call stored procedures, you start by creating an instance of the ``queries.Session`` class. It can act as a context manager, meaning you can use it with the ``with`` keyword and it will take care of cleaning up after itself. For more information on the ``with`` keyword and context managers, see PEP343_. In addition to both the ``queries.Session.query`` and ``queries.Session.callproc`` methods that are similar to the simple API methods, the ``queries.Session`` class provides access to the psycopg2 connection and cursor objects. **Using queries.Session.query** The following example shows how a ``queries.Session`` object can be used as a context manager to query the database table: .. code:: python >>> import pprint >>> import queries >>> >>> with queries.Session() as session: ... for row in session.query('SELECT * FROM names'): ... pprint.pprint(row) ... {'id': 1, 'name': u'Jacob'} {'id': 2, 'name': u'Mason'} {'id': 3, 'name': u'Ethan'} **Using queries.Session.callproc** This example uses ``queries.Session.callproc`` to execute a stored procedure and then pretty-prints the single row results as a dictionary: .. code:: python >>> import pprint >>> import queries >>> with queries.Session() as session: ... results = session.callproc('chr', [65]) ... pprint.pprint(results.as_dict()) ... {'chr': u'A'} **Asynchronous Queries with Tornado** In addition to providing a Pythonic, synchronous client API for PostgreSQL, Queries provides a very similar asynchronous API for use with Tornado. The only major difference API difference between ``queries.TornadoSession`` and ``queries.Session`` is the ``TornadoSession.query`` and ``TornadoSession.callproc`` methods return the entire result set instead of acting as an iterator over the results. The following example uses ``TornadoSession.query`` in an asynchronous Tornado_ web application to send a JSON payload with the query result set. .. code:: python from tornado import gen, ioloop, web import queries class MainHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession() @gen.coroutine def get(self): results = yield self.session.query('SELECT * FROM names') self.finish({'data': results.items()}) results.free() application = web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) ioloop.IOLoop.instance().start() Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. History ------- Queries is a fork and enhancement of pgsql_wrapper_, which can be found in the main GitHub repository of Queries as tags prior to version 1.2.0. .. _pypi: https://pypi.python.org/pypi/queries .. _psycopg2: https://pypi.python.org/pypi/psycopg2 .. _documentation: https://queries.readthedocs.org .. _URI: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING .. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper .. _Tornado: http://tornadoweb.org .. _PEP343: http://legacy.python.org/dev/peps/pep-0343/ .. _psycopg2cffi: https://pypi.python.org/pypi/psycopg2cffi .. |Version| image:: https://img.shields.io/pypi/v/queries.svg? :target: https://pypi.python.org/pypi/queries .. |Status| image:: https://img.shields.io/travis/gmr/queries.svg? :target: https://travis-ci.org/gmr/queries .. |Coverage| image:: https://img.shields.io/codecov/c/github/gmr/queries.svg? :target: https://codecov.io/github/gmr/queries?branch=master .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries <MSG> Fix the code block [ci skip] <DFF> @@ -19,7 +19,7 @@ Installation ------------ queries is available via pypi and can be installed with easy_install or pip: -..code:: bash +.. code:: bash pip install queries
1
Fix the code block
1
.rst
rst
bsd-3-clause
gmr/queries
1608
<NME> README.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. Check out the `Usage`_ section below to see how easy it can be. Key features include: - Simplified API - Support of Python 2.7+ and 3.4+ - PyPy support via psycopg2cffi_ - Asynchronous support for Tornado_ - Connection information provided by URI ------------ queries is available via pypi and can be installed with easy_install or pip: ..code:: bash pip install queries Documentation ------------- Documentation is available at https://queries.readthedocs.org Installation ------------ Queries is available via pypi_ and can be installed with easy_install or pip: .. code:: bash pip install queries Usage ----- Queries provides a session based API for interacting with PostgreSQL. Simply pass in the URI_ of the PostgreSQL server to connect to when creating a session: .. code:: python session = queries.Session("postgresql://postgres@localhost:5432/postgres") Queries built-in connection pooling will re-use connections when possible, lowering the overhead of connecting and reconnecting. When specifying a URI, if you omit the username and database name to connect with, Queries will use the current OS username for both. You can also omit the URI when connecting to connect to localhost on port 5432 as the current OS user, connecting to a database named for the current user. For example, if your username is ``fred`` and you omit the URI when issuing ``queries.query`` the URI that is constructed would be ``postgresql://fred@localhost:5432/fred``. If you'd rather use individual values for the connection, the queries.uri() method provides a quick and easy way to create a URI to pass into the various methods. .. code:: python >>> queries.uri("server-name", 5432, "dbname", "user", "pass") 'postgresql://user:pass@server-name:5432/dbname' Environment Variables ^^^^^^^^^^^^^^^^^^^^^ Currently Queries uses the following environment variables for tweaking various configuration values. The supported ones are: * ``QUERIES_MAX_POOL_SIZE`` - Modify the maximum size of the connection pool (default: 1) Using the queries.Session class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To execute queries or call stored procedures, you start by creating an instance of the ``queries.Session`` class. It can act as a context manager, meaning you can use it with the ``with`` keyword and it will take care of cleaning up after itself. For more information on the ``with`` keyword and context managers, see PEP343_. In addition to both the ``queries.Session.query`` and ``queries.Session.callproc`` methods that are similar to the simple API methods, the ``queries.Session`` class provides access to the psycopg2 connection and cursor objects. **Using queries.Session.query** The following example shows how a ``queries.Session`` object can be used as a context manager to query the database table: .. code:: python >>> import pprint >>> import queries >>> >>> with queries.Session() as session: ... for row in session.query('SELECT * FROM names'): ... pprint.pprint(row) ... {'id': 1, 'name': u'Jacob'} {'id': 2, 'name': u'Mason'} {'id': 3, 'name': u'Ethan'} **Using queries.Session.callproc** This example uses ``queries.Session.callproc`` to execute a stored procedure and then pretty-prints the single row results as a dictionary: .. code:: python >>> import pprint >>> import queries >>> with queries.Session() as session: ... results = session.callproc('chr', [65]) ... pprint.pprint(results.as_dict()) ... {'chr': u'A'} **Asynchronous Queries with Tornado** In addition to providing a Pythonic, synchronous client API for PostgreSQL, Queries provides a very similar asynchronous API for use with Tornado. The only major difference API difference between ``queries.TornadoSession`` and ``queries.Session`` is the ``TornadoSession.query`` and ``TornadoSession.callproc`` methods return the entire result set instead of acting as an iterator over the results. The following example uses ``TornadoSession.query`` in an asynchronous Tornado_ web application to send a JSON payload with the query result set. .. code:: python from tornado import gen, ioloop, web import queries class MainHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession() @gen.coroutine def get(self): results = yield self.session.query('SELECT * FROM names') self.finish({'data': results.items()}) results.free() application = web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) ioloop.IOLoop.instance().start() Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. History ------- Queries is a fork and enhancement of pgsql_wrapper_, which can be found in the main GitHub repository of Queries as tags prior to version 1.2.0. .. _pypi: https://pypi.python.org/pypi/queries .. _psycopg2: https://pypi.python.org/pypi/psycopg2 .. _documentation: https://queries.readthedocs.org .. _URI: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING .. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper .. _Tornado: http://tornadoweb.org .. _PEP343: http://legacy.python.org/dev/peps/pep-0343/ .. _psycopg2cffi: https://pypi.python.org/pypi/psycopg2cffi .. |Version| image:: https://img.shields.io/pypi/v/queries.svg? :target: https://pypi.python.org/pypi/queries .. |Status| image:: https://img.shields.io/travis/gmr/queries.svg? :target: https://travis-ci.org/gmr/queries .. |Coverage| image:: https://img.shields.io/codecov/c/github/gmr/queries.svg? :target: https://codecov.io/github/gmr/queries?branch=master .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries <MSG> Fix the code block [ci skip] <DFF> @@ -19,7 +19,7 @@ Installation ------------ queries is available via pypi and can be installed with easy_install or pip: -..code:: bash +.. code:: bash pip install queries
1
Fix the code block
1
.rst
rst
bsd-3-clause
gmr/queries
1609
<NME> index.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. |Version| |Downloads| The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. *Key features include*: - Simplified API - Support of Python 2.6+ and 3.2+ - PyPy support via psycopg2ct - Asynchronous support for Tornado_ - Connection information provided by URI - Query results delivered as a generator based iterators - Automatically registered data-type support for UUIDs, Unicode and Unicode Arrays - Ability to directly access psycopg2_ :py:class:`~psycopg2.extensions.connection` and :py:class:`~psycopg2.extensions.cursor` objects - Internal connection pooling Installation ------------ Queries can be installed via the `Python Package Index <https://pypi.python.org/pypi/queries>`_ and can be installed by running :command:`easy_install queries` or :command:`pip install queries` When installing Queries, ``pip`` or ``easy_install`` will automatically install the proper dependencies for your platform. Contents -------- .. toctree:: :maxdepth: 1 usage session results tornado_session pool examples/index.rst history Issues ------ Please report any issues to the Github repo at `https://github.com/gmr/queries/issues <https://github.com/gmr/queries/issues>`_ Source ------ Queries source is available on Github at `https://github.com/gmr/queries <https://github.com/gmr/queries>`_ Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. _pypi: https://pypi.python.org/pypi/queries .. _pypi: https://pypi.python.org/pypi/queries .. _psycopg2: https://pypi.python.org/pypi/psycopg2 .. _URIs: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING .. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper .. _Tornado: http://tornadoweb.org .. |Version| image:: https://badge.fury.io/py/queries.svg? :target: http://badge.fury.io/py/queries .. |Status| image:: https://travis-ci.org/gmr/queries.svg?branch=master :target: https://travis-ci.org/gmr/queries .. |Downloads| image:: https://pypip.in/d/queries/badge.svg? :target: https://pypi.python.org/pypi/queries <MSG> Update docs and badges with new info <DFF> @@ -3,7 +3,7 @@ Queries: PostgreSQL Simplified *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. -|Version| |Downloads| +|Version| |Downloads| |License| |PythonVersions| The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your @@ -15,7 +15,7 @@ both fast and easy. - Simplified API - Support of Python 2.6+ and 3.2+ -- PyPy support via psycopg2ct +- PyPy support via psycopg2cffi_ - Asynchronous support for Tornado_ - Connection information provided by URI - Query results delivered as a generator based iterators @@ -69,15 +69,21 @@ Indices and tables .. _pypi: https://pypi.python.org/pypi/queries .. _psycopg2: https://pypi.python.org/pypi/psycopg2 -.. _URIs: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING +.. _documentation: https://queries.readthedocs.org +.. _URI: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING .. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper .. _Tornado: http://tornadoweb.org +.. _PEP343: http://legacy.python.org/dev/peps/pep-0343/ +.. _psycopg2cffi: https://pypi.python.org/pypi/psycopg2cffi -.. |Version| image:: https://badge.fury.io/py/queries.svg? - :target: http://badge.fury.io/py/queries - -.. |Status| image:: https://travis-ci.org/gmr/queries.svg?branch=master - :target: https://travis-ci.org/gmr/queries +.. |Version| image:: https://img.shields.io/pypi/v/queries.svg? + :target: https://pypi.python.org/pypi/queries -.. |Downloads| image:: https://pypip.in/d/queries/badge.svg? +.. |Downloads| image:: https://img.shields.io/pypi/dm/queries.svg? :target: https://pypi.python.org/pypi/queries + +.. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? + :target: https://github.com/gmr/queries + +.. |PythonVersions| image:: https://img.shields.io/pypi/pyversions/queries.svg? + :target: https://github.com/gmr/queries
15
Update docs and badges with new info
9
.rst
rst
bsd-3-clause
gmr/queries
1610
<NME> index.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. |Version| |Downloads| The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. *Key features include*: - Simplified API - Support of Python 2.6+ and 3.2+ - PyPy support via psycopg2ct - Asynchronous support for Tornado_ - Connection information provided by URI - Query results delivered as a generator based iterators - Automatically registered data-type support for UUIDs, Unicode and Unicode Arrays - Ability to directly access psycopg2_ :py:class:`~psycopg2.extensions.connection` and :py:class:`~psycopg2.extensions.cursor` objects - Internal connection pooling Installation ------------ Queries can be installed via the `Python Package Index <https://pypi.python.org/pypi/queries>`_ and can be installed by running :command:`easy_install queries` or :command:`pip install queries` When installing Queries, ``pip`` or ``easy_install`` will automatically install the proper dependencies for your platform. Contents -------- .. toctree:: :maxdepth: 1 usage session results tornado_session pool examples/index.rst history Issues ------ Please report any issues to the Github repo at `https://github.com/gmr/queries/issues <https://github.com/gmr/queries/issues>`_ Source ------ Queries source is available on Github at `https://github.com/gmr/queries <https://github.com/gmr/queries>`_ Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. _pypi: https://pypi.python.org/pypi/queries .. _pypi: https://pypi.python.org/pypi/queries .. _psycopg2: https://pypi.python.org/pypi/psycopg2 .. _URIs: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING .. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper .. _Tornado: http://tornadoweb.org .. |Version| image:: https://badge.fury.io/py/queries.svg? :target: http://badge.fury.io/py/queries .. |Status| image:: https://travis-ci.org/gmr/queries.svg?branch=master :target: https://travis-ci.org/gmr/queries .. |Downloads| image:: https://pypip.in/d/queries/badge.svg? :target: https://pypi.python.org/pypi/queries <MSG> Update docs and badges with new info <DFF> @@ -3,7 +3,7 @@ Queries: PostgreSQL Simplified *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. -|Version| |Downloads| +|Version| |Downloads| |License| |PythonVersions| The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your @@ -15,7 +15,7 @@ both fast and easy. - Simplified API - Support of Python 2.6+ and 3.2+ -- PyPy support via psycopg2ct +- PyPy support via psycopg2cffi_ - Asynchronous support for Tornado_ - Connection information provided by URI - Query results delivered as a generator based iterators @@ -69,15 +69,21 @@ Indices and tables .. _pypi: https://pypi.python.org/pypi/queries .. _psycopg2: https://pypi.python.org/pypi/psycopg2 -.. _URIs: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING +.. _documentation: https://queries.readthedocs.org +.. _URI: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING .. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper .. _Tornado: http://tornadoweb.org +.. _PEP343: http://legacy.python.org/dev/peps/pep-0343/ +.. _psycopg2cffi: https://pypi.python.org/pypi/psycopg2cffi -.. |Version| image:: https://badge.fury.io/py/queries.svg? - :target: http://badge.fury.io/py/queries - -.. |Status| image:: https://travis-ci.org/gmr/queries.svg?branch=master - :target: https://travis-ci.org/gmr/queries +.. |Version| image:: https://img.shields.io/pypi/v/queries.svg? + :target: https://pypi.python.org/pypi/queries -.. |Downloads| image:: https://pypip.in/d/queries/badge.svg? +.. |Downloads| image:: https://img.shields.io/pypi/dm/queries.svg? :target: https://pypi.python.org/pypi/queries + +.. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? + :target: https://github.com/gmr/queries + +.. |PythonVersions| image:: https://img.shields.io/pypi/pyversions/queries.svg? + :target: https://github.com/gmr/queries
15
Update docs and badges with new info
9
.rst
rst
bsd-3-clause
gmr/queries
1611
<NME> utils_tests.py <BEF> """ Tests for functionality in the utils module """ import platform import unittest import mock import queries from queries import utils class GetCurrentUserTests(unittest.TestCase): @mock.patch('pwd.getpwuid') def test_get_current_user(self, getpwuid): """get_current_user returns value from pwd.getpwuid""" getpwuid.return_value = ['mocky'] self.assertEqual(utils.get_current_user(), 'mocky') class PYPYDetectionTests(unittest.TestCase): def test_pypy_flag(self): """PYPY flag is set properly""" self.assertEqual(queries.utils.PYPY, platform.python_implementation() == 'PyPy') class URICreationTests(unittest.TestCase): def test_uri_with_password(self): expectation = 'postgresql://foo:bar@baz:5433/qux' self.assertEqual(queries.uri('baz', 5433, 'qux', 'foo', 'bar'), expectation) def test_uri_without_password(self): expectation = 'postgresql://foo@baz:5433/qux' self.assertEqual(queries.uri('baz', 5433, 'qux', 'foo'), expectation) def test_default_uri(self): expectation = 'postgresql://postgres@localhost:5432/postgres' self.assertEqual(queries.uri(), expectation) class URIToKWargsTestCase(unittest.TestCase): URI = ('postgresql://foo:bar@baz:5444/qux?options=foo&options=bar' '&keepalives=1&invalid=true') def test_uri_to_kwargs_host(self): """hostname should match expectation""" def test_urlparse_port(self): """port should match expectation""" self.assertEqual(utils.urlparse(self.URI).port, 5444) def test_urlparse_path(self): """path should match expectation""" self.assertEqual(utils.urlparse(self.URI).path, '/qux') def test_urlparse_username(self): """username should match expectation""" self.assertEqual(utils.urlparse(self.URI).username, 'foo') def test_uri_to_kwargs_password(self): """password should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['password'], 'bar') def test_uri_to_kwargs_options(self): """options should match expectation""" 'options=foo&options=bar&keepalives=1&invalid=true') def test_uri_to_kwargs_host(self): """hostname should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['host'], 'baz') def test_uri_to_kwargs_port(self): """port should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['port'], 5444) def test_uri_to_kwargs_dbname(self): """dbname should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['dbname'], 'qux') def test_uri_to_kwargs_username(self): """user should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['user'], 'foo') def test_uri_to_kwargs_password(self): """password should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['password'], 'c#^%#\'$@:') def test_uri_to_kwargs_options(self): """options should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['options'], ['foo', 'bar']) def test_uri_to_kwargs_keepalive(self): """keepalive should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['keepalives'], 1) def test_uri_to_kwargs_invalid(self): """invalid query argument should not be in kwargs""" self.assertNotIn('invaid', utils.uri_to_kwargs(self.URI)) def test_unix_socket_path_format_one(self): socket_path = 'postgresql://%2Fvar%2Flib%2Fpostgresql/dbname' result = utils.uri_to_kwargs(socket_path) self.assertEqual(result['host'], '/var/lib/postgresql') def test_unix_socket_path_format2(self): socket_path = 'postgresql:///postgres?host=/tmp/' result = utils.uri_to_kwargs(socket_path) self.assertEqual(result['host'], '/tmp/') <MSG> Add unquoting of URL characters in the password This is not done by urllib by default but is required for special characters in a password. - Update tests to use funky characters in the password - Remove wheel distribution until I can figure out how to make a pypy specific wheel <DFF> @@ -47,8 +47,8 @@ class URLParseTestCase(unittest.TestCase): class URIToKWargsTestCase(unittest.TestCase): - URI = ('postgresql://foo:bar@baz:5444/qux?options=foo&options=bar' - '&keepalives=1&invalid=true') + URI = ('postgresql://foo:c%23%5E%25%23%27%24%40%3A@baz:5444/qux?' + 'options=foo&options=bar&keepalives=1&invalid=true') def test_uri_to_kwargs_host(self): """hostname should match expectation""" @@ -68,7 +68,8 @@ class URIToKWargsTestCase(unittest.TestCase): def test_uri_to_kwargs_password(self): """password should match expectation""" - self.assertEqual(utils.uri_to_kwargs(self.URI)['password'], 'bar') + self.assertEqual(utils.uri_to_kwargs(self.URI)['password'], + 'c#^%#\'$@:') def test_uri_to_kwargs_options(self): """options should match expectation"""
4
Add unquoting of URL characters in the password
3
.py
py
bsd-3-clause
gmr/queries
1612
<NME> utils_tests.py <BEF> """ Tests for functionality in the utils module """ import platform import unittest import mock import queries from queries import utils class GetCurrentUserTests(unittest.TestCase): @mock.patch('pwd.getpwuid') def test_get_current_user(self, getpwuid): """get_current_user returns value from pwd.getpwuid""" getpwuid.return_value = ['mocky'] self.assertEqual(utils.get_current_user(), 'mocky') class PYPYDetectionTests(unittest.TestCase): def test_pypy_flag(self): """PYPY flag is set properly""" self.assertEqual(queries.utils.PYPY, platform.python_implementation() == 'PyPy') class URICreationTests(unittest.TestCase): def test_uri_with_password(self): expectation = 'postgresql://foo:bar@baz:5433/qux' self.assertEqual(queries.uri('baz', 5433, 'qux', 'foo', 'bar'), expectation) def test_uri_without_password(self): expectation = 'postgresql://foo@baz:5433/qux' self.assertEqual(queries.uri('baz', 5433, 'qux', 'foo'), expectation) def test_default_uri(self): expectation = 'postgresql://postgres@localhost:5432/postgres' self.assertEqual(queries.uri(), expectation) class URIToKWargsTestCase(unittest.TestCase): URI = ('postgresql://foo:bar@baz:5444/qux?options=foo&options=bar' '&keepalives=1&invalid=true') def test_uri_to_kwargs_host(self): """hostname should match expectation""" def test_urlparse_port(self): """port should match expectation""" self.assertEqual(utils.urlparse(self.URI).port, 5444) def test_urlparse_path(self): """path should match expectation""" self.assertEqual(utils.urlparse(self.URI).path, '/qux') def test_urlparse_username(self): """username should match expectation""" self.assertEqual(utils.urlparse(self.URI).username, 'foo') def test_uri_to_kwargs_password(self): """password should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['password'], 'bar') def test_uri_to_kwargs_options(self): """options should match expectation""" 'options=foo&options=bar&keepalives=1&invalid=true') def test_uri_to_kwargs_host(self): """hostname should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['host'], 'baz') def test_uri_to_kwargs_port(self): """port should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['port'], 5444) def test_uri_to_kwargs_dbname(self): """dbname should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['dbname'], 'qux') def test_uri_to_kwargs_username(self): """user should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['user'], 'foo') def test_uri_to_kwargs_password(self): """password should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['password'], 'c#^%#\'$@:') def test_uri_to_kwargs_options(self): """options should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['options'], ['foo', 'bar']) def test_uri_to_kwargs_keepalive(self): """keepalive should match expectation""" self.assertEqual(utils.uri_to_kwargs(self.URI)['keepalives'], 1) def test_uri_to_kwargs_invalid(self): """invalid query argument should not be in kwargs""" self.assertNotIn('invaid', utils.uri_to_kwargs(self.URI)) def test_unix_socket_path_format_one(self): socket_path = 'postgresql://%2Fvar%2Flib%2Fpostgresql/dbname' result = utils.uri_to_kwargs(socket_path) self.assertEqual(result['host'], '/var/lib/postgresql') def test_unix_socket_path_format2(self): socket_path = 'postgresql:///postgres?host=/tmp/' result = utils.uri_to_kwargs(socket_path) self.assertEqual(result['host'], '/tmp/') <MSG> Add unquoting of URL characters in the password This is not done by urllib by default but is required for special characters in a password. - Update tests to use funky characters in the password - Remove wheel distribution until I can figure out how to make a pypy specific wheel <DFF> @@ -47,8 +47,8 @@ class URLParseTestCase(unittest.TestCase): class URIToKWargsTestCase(unittest.TestCase): - URI = ('postgresql://foo:bar@baz:5444/qux?options=foo&options=bar' - '&keepalives=1&invalid=true') + URI = ('postgresql://foo:c%23%5E%25%23%27%24%40%3A@baz:5444/qux?' + 'options=foo&options=bar&keepalives=1&invalid=true') def test_uri_to_kwargs_host(self): """hostname should match expectation""" @@ -68,7 +68,8 @@ class URIToKWargsTestCase(unittest.TestCase): def test_uri_to_kwargs_password(self): """password should match expectation""" - self.assertEqual(utils.uri_to_kwargs(self.URI)['password'], 'bar') + self.assertEqual(utils.uri_to_kwargs(self.URI)['password'], + 'c#^%#\'$@:') def test_uri_to_kwargs_options(self): """options should match expectation"""
4
Add unquoting of URL characters in the password
3
.py
py
bsd-3-clause
gmr/queries
1613
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<2.9'] else: install_requires = ['psycopg2>=2.5.1,<2.9'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setuptools.setup( name='queries', version='2.1.0', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy', maintainer_email='[email protected]', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Adjust psycopg2 constraint to allow 2.9.x <DFF> @@ -5,9 +5,9 @@ import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': - install_requires = ['psycopg2cffi>=2.7.2,<2.9'] + install_requires = ['psycopg2cffi>=2.7.2,<3'] else: - install_requires = ['psycopg2>=2.5.1,<2.9'] + install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True':
2
Adjust psycopg2 constraint to allow 2.9.x
2
.py
py
bsd-3-clause
gmr/queries
1614
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<2.9'] else: install_requires = ['psycopg2>=2.5.1,<2.9'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setuptools.setup( name='queries', version='2.1.0', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy', maintainer_email='[email protected]', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Adjust psycopg2 constraint to allow 2.9.x <DFF> @@ -5,9 +5,9 @@ import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': - install_requires = ['psycopg2cffi>=2.7.2,<2.9'] + install_requires = ['psycopg2cffi>=2.7.2,<3'] else: - install_requires = ['psycopg2>=2.5.1,<2.9'] + install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True':
2
Adjust psycopg2 constraint to allow 2.9.x
2
.py
py
bsd-3-clause
gmr/queries
1615
<NME> session_tests.py <BEF> """ Tests for functionality in the session module """ import hashlib import logging import unittest import mock from psycopg2 import extras import psycopg2 # Out of order import to ensure psycopg2cffi is registered from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) class SessionTestCase(unittest.TestCase): URI = 'postgresql://foo:bar@localhost:5432/foo' @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') def setUp(self, register_uuid, register_json, register_type, connect): self._connect = connect self._connect.reset = mock.Mock() self._reg_json = register_json self._reg_type = register_type self._reg_uuid = register_uuid self.uri = 'pgsql://[email protected]:5432/queries' self.conn.reset = mock.Mock() self.conn.status = psycopg2.extensions.STATUS_BEGIN self.psycopg2_connect = connect self.psycopg2_connect.return_value = self.conn self.psycopg2_register_type = register_type self.psycopg2_register_uuid = register_uuid self.uri_to_kwargs = uri_to_kwargs self.uri_to_kwargs.return_value = {'host': 'localhost', 'port': 5432, 'user': 'foo', 'password': None} self._connect.assert_called_once_with(**expectation) @unittest.skipIf(PYPY, "Not supported in PyPy") def test_psycopg2_register_json(self): """Ensure that the JSON extension was registered""" self._reg_json.assert_called_once_with(conn_or_curs=self.client._conn) def test_psycopg2_register_uuid(self): """Ensure that the UUID extension was registered""" self._reg_uuid.assert_called_once_with(conn_or_curs=self.client._conn) self.assertEqual(self.obj._uri, self.URI) def test_init_creates_new_pool(self): self.assertIn(self.obj.pid, self.obj._pool_manager) def test_init_creates_connection(self): conns = \ [value.handle for key, value in self.obj._pool_manager._pools[self.obj.pid].connections.items()] self.assertIn(self.conn, conns) def test_init_sets_cursorfactory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_init_gets_cursor(self): self.conn.cursor.assert_called_once_with( name=None, cursor_factory=extras.RealDictCursor) def test_init_sets_autocommit(self): self.assertTrue(self.conn.autocommit) def test_backend_pid_invokes_conn_backend_pid(self): self.conn.get_backend_pid = get_backend_pid = mock.Mock() LOGGER.debug('ValueL %s', self.obj.backend_pid) get_backend_pid.assert_called_once_with() def test_callproc_invokes_cursor_callproc(self): self.obj._cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.obj.callproc(*args) self.obj._cursor.callproc.assert_called_once_with(*args) def test_callproc_returns_results(self): self.obj._cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.assertIsInstance(self.obj.callproc(*args), results.Results) def test_close_raises_exception(self): self.obj._conn = None self.assertRaises(psycopg2.InterfaceError, self.obj.close) def test_close_removes_connection(self): cleanup.assert_called_once_with() @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') @mock.patch('psycopg2.extensions.register_type') def test_context_manager_creation(self, _uuid, _json, _type, _connect): """Ensure context manager returns self""" with session.Session(self.uri) as conn: self.assertIsInstance(conn, session.Session) @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') def test_context_manager_cleanup(self, _uuid, _json, _type, _connect): """Ensure context manager cleans up after self""" with mock.patch('queries.session.Session._cleanup') as cleanup: with session.Session(self.uri): def test_encoding_property_value(self): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') def test_close_removes_from_cache(self, _uuid, _json, _type, _connect): """Ensure connection removed from cache on close""" conn = self.client._conn self.client.close() expectation = hashlib.md5( @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') def test_close_invokes_connection_close(self, _uuid, _json, _type, connect): """Ensure close calls connection.close""" sess = session.Session('pgsql://foo@bar:9999/baz') close_mock = mock.Mock() self.obj._cursor.execute.assert_called_once_with(*args) def test_set_encoding_sets_encoding_if_different(self): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') def test_close_sets_conn_to_none(self, _uuid, _json, _type, connect): """Ensure Session._conn is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() self.obj.set_encoding('UTF-8') @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') def test_close_sets_cursor_to_none(self, _uuid, _json, _type, connect): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() self.assertIsNone(sess._cursor) @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_close_raises_when_closed(self, _uuid, _json, _type, _conn): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() with mock.patch.multiple('queries.session.Session', _cleanup=cleanup, _connect=mock.Mock(), _get_cursor=mock.Mock(), _autocommit=mock.Mock()): with session.Session(self.URI): pass self.assertTrue(cleanup.called) def test_autocommit_sets_attribute(self): self.conn.autocommit = False self.obj._autocommit(True) self.assertTrue(self.conn.autocommit) def test_cleanup_closes_cursor(self): self.obj._cursor.close = closeit = mock.Mock() self.conn = None self.obj._cleanup() closeit.assert_called_once_with() def test_cleanup_sets_cursor_to_none(self): self.obj._cursor.close = mock.Mock() self.conn = None self.obj._cleanup() self.assertIsNone(self.obj._cursor) def test_cleanup_frees_connection(self): with mock.patch.object(self.obj._pool_manager, 'free') as free: conn = self.obj._conn self.obj._cleanup() free.assert_called_once_with(self.obj.pid, conn) def test_cleanup_sets_connect_to_none(self): self.obj._cleanup() self.assertIsNone(self.obj._conn) def test_connect_invokes_pool_manager_get(self): with mock.patch.object(self.obj._pool_manager, 'get') as get: self.obj._connect() get.assert_called_once_with(self.obj.pid, self.obj) def test_connect_raises_noidleconnectionserror(self): with mock.patch.object(self.obj._pool_manager, 'get') as get: with mock.patch.object(self.obj._pool_manager, 'is_full') as full: get.side_effect = pool.NoIdleConnectionsError(self.obj.pid) full.return_value = True self.assertRaises(pool.NoIdleConnectionsError, self.obj._connect) def test_connect_invokes_uri_to_kwargs(self): self.uri_to_kwargs.assert_called_once_with(self.URI) def test_connect_returned_the_proper_value(self): self.assertEqual(self.obj.connection, self.conn) def test_status_is_ready_by_default(self): self.assertEqual(self.obj._status, self.obj.READY) def test_status_when_not_ready(self): self.conn.status = self.obj.SETUP self.assertEqual(self.obj._status, self.obj.SETUP) def test_get_named_cursor_sets_scrollable(self): result = self.obj._get_cursor(self.obj._conn, 'test1') self.assertTrue(result.scrollable) def test_get_named_cursor_sets_withhold(self): result = self.obj._get_cursor(self.obj._conn, 'test2') self.assertTrue(result.withhhold) @unittest.skipUnless(utils.PYPY, 'connection.reset is PYPY only behavior') def test_connection_reset_in_pypy(self): self.conn.reset.assert_called_once_with() <MSG> Remove JSON support due to psycopg2ct not supporting it, update tests - Also don't perform the weakref cleanup test in pypy since it's not immediate in pypy <DFF> @@ -23,12 +23,10 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def setUp(self, register_uuid, register_json, register_type, connect): + def setUp(self, register_uuid, register_type, connect): self._connect = connect self._connect.reset = mock.Mock() - self._reg_json = register_json self._reg_type = register_type self._reg_uuid = register_uuid self.uri = 'pgsql://[email protected]:5432/queries' @@ -46,11 +44,6 @@ class SessionTests(unittest.TestCase): 'password': None} self._connect.assert_called_once_with(**expectation) - @unittest.skipIf(PYPY, "Not supported in PyPy") - def test_psycopg2_register_json(self): - """Ensure that the JSON extension was registered""" - self._reg_json.assert_called_once_with(conn_or_curs=self.client._conn) - def test_psycopg2_register_uuid(self): """Ensure that the UUID extension was registered""" self._reg_uuid.assert_called_once_with(conn_or_curs=self.client._conn) @@ -99,19 +92,17 @@ class SessionTests(unittest.TestCase): cleanup.assert_called_once_with() @mock.patch('psycopg2.connect') - @mock.patch('psycopg2.extras.register_json') - @mock.patch('psycopg2.extras.register_uuid') @mock.patch('psycopg2.extensions.register_type') - def test_context_manager_creation(self, _uuid, _json, _type, _connect): + @mock.patch('psycopg2.extras.register_uuid') + def test_context_manager_creation(self, _uuid, _type, _connect): """Ensure context manager returns self""" with session.Session(self.uri) as conn: self.assertIsInstance(conn, session.Session) @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_context_manager_cleanup(self, _uuid, _json, _type, _connect): + def test_context_manager_cleanup(self, _uuid, _type, _connect): """Ensure context manager cleans up after self""" with mock.patch('queries.session.Session._cleanup') as cleanup: with session.Session(self.uri): @@ -120,9 +111,8 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_removes_from_cache(self, _uuid, _json, _type, _connect): + def test_close_removes_from_cache(self, _uuid, _type, _connect): """Ensure connection removed from cache on close""" conn = self.client._conn self.client.close() @@ -130,9 +120,8 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_invokes_connection_close(self, _uuid, _json, _type, connect): + def test_close_invokes_connection_close(self, _uuid, _type, connect): """Ensure close calls connection.close""" sess = session.Session('pgsql://foo@bar:9999/baz') close_mock = mock.Mock() @@ -142,9 +131,8 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_sets_conn_to_none(self, _uuid, _json, _type, connect): + def test_close_sets_conn_to_none(self, _uuid, _type, connect): """Ensure Session._conn is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() @@ -152,19 +140,17 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_sets_cursor_to_none(self, _uuid, _json, _type, connect): + def test_close_sets_cursor_to_none(self, _uuid, _type, connect): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() self.assertIsNone(sess._cursor) @mock.patch('psycopg2.connect') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') - def test_close_raises_when_closed(self, _uuid, _json, _type, _conn): + def test_close_raises_when_closed(self, _uuid, _type, _conn): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close()
9
Remove JSON support due to psycopg2ct not supporting it, update tests
23
.py
py
bsd-3-clause
gmr/queries
1616
<NME> session_tests.py <BEF> """ Tests for functionality in the session module """ import hashlib import logging import unittest import mock from psycopg2 import extras import psycopg2 # Out of order import to ensure psycopg2cffi is registered from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) class SessionTestCase(unittest.TestCase): URI = 'postgresql://foo:bar@localhost:5432/foo' @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') def setUp(self, register_uuid, register_json, register_type, connect): self._connect = connect self._connect.reset = mock.Mock() self._reg_json = register_json self._reg_type = register_type self._reg_uuid = register_uuid self.uri = 'pgsql://[email protected]:5432/queries' self.conn.reset = mock.Mock() self.conn.status = psycopg2.extensions.STATUS_BEGIN self.psycopg2_connect = connect self.psycopg2_connect.return_value = self.conn self.psycopg2_register_type = register_type self.psycopg2_register_uuid = register_uuid self.uri_to_kwargs = uri_to_kwargs self.uri_to_kwargs.return_value = {'host': 'localhost', 'port': 5432, 'user': 'foo', 'password': None} self._connect.assert_called_once_with(**expectation) @unittest.skipIf(PYPY, "Not supported in PyPy") def test_psycopg2_register_json(self): """Ensure that the JSON extension was registered""" self._reg_json.assert_called_once_with(conn_or_curs=self.client._conn) def test_psycopg2_register_uuid(self): """Ensure that the UUID extension was registered""" self._reg_uuid.assert_called_once_with(conn_or_curs=self.client._conn) self.assertEqual(self.obj._uri, self.URI) def test_init_creates_new_pool(self): self.assertIn(self.obj.pid, self.obj._pool_manager) def test_init_creates_connection(self): conns = \ [value.handle for key, value in self.obj._pool_manager._pools[self.obj.pid].connections.items()] self.assertIn(self.conn, conns) def test_init_sets_cursorfactory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_init_gets_cursor(self): self.conn.cursor.assert_called_once_with( name=None, cursor_factory=extras.RealDictCursor) def test_init_sets_autocommit(self): self.assertTrue(self.conn.autocommit) def test_backend_pid_invokes_conn_backend_pid(self): self.conn.get_backend_pid = get_backend_pid = mock.Mock() LOGGER.debug('ValueL %s', self.obj.backend_pid) get_backend_pid.assert_called_once_with() def test_callproc_invokes_cursor_callproc(self): self.obj._cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.obj.callproc(*args) self.obj._cursor.callproc.assert_called_once_with(*args) def test_callproc_returns_results(self): self.obj._cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.assertIsInstance(self.obj.callproc(*args), results.Results) def test_close_raises_exception(self): self.obj._conn = None self.assertRaises(psycopg2.InterfaceError, self.obj.close) def test_close_removes_connection(self): cleanup.assert_called_once_with() @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') @mock.patch('psycopg2.extensions.register_type') def test_context_manager_creation(self, _uuid, _json, _type, _connect): """Ensure context manager returns self""" with session.Session(self.uri) as conn: self.assertIsInstance(conn, session.Session) @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') def test_context_manager_cleanup(self, _uuid, _json, _type, _connect): """Ensure context manager cleans up after self""" with mock.patch('queries.session.Session._cleanup') as cleanup: with session.Session(self.uri): def test_encoding_property_value(self): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') def test_close_removes_from_cache(self, _uuid, _json, _type, _connect): """Ensure connection removed from cache on close""" conn = self.client._conn self.client.close() expectation = hashlib.md5( @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') def test_close_invokes_connection_close(self, _uuid, _json, _type, connect): """Ensure close calls connection.close""" sess = session.Session('pgsql://foo@bar:9999/baz') close_mock = mock.Mock() self.obj._cursor.execute.assert_called_once_with(*args) def test_set_encoding_sets_encoding_if_different(self): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') def test_close_sets_conn_to_none(self, _uuid, _json, _type, connect): """Ensure Session._conn is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() self.obj.set_encoding('UTF-8') @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') def test_close_sets_cursor_to_none(self, _uuid, _json, _type, connect): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() self.assertIsNone(sess._cursor) @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_close_raises_when_closed(self, _uuid, _json, _type, _conn): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() with mock.patch.multiple('queries.session.Session', _cleanup=cleanup, _connect=mock.Mock(), _get_cursor=mock.Mock(), _autocommit=mock.Mock()): with session.Session(self.URI): pass self.assertTrue(cleanup.called) def test_autocommit_sets_attribute(self): self.conn.autocommit = False self.obj._autocommit(True) self.assertTrue(self.conn.autocommit) def test_cleanup_closes_cursor(self): self.obj._cursor.close = closeit = mock.Mock() self.conn = None self.obj._cleanup() closeit.assert_called_once_with() def test_cleanup_sets_cursor_to_none(self): self.obj._cursor.close = mock.Mock() self.conn = None self.obj._cleanup() self.assertIsNone(self.obj._cursor) def test_cleanup_frees_connection(self): with mock.patch.object(self.obj._pool_manager, 'free') as free: conn = self.obj._conn self.obj._cleanup() free.assert_called_once_with(self.obj.pid, conn) def test_cleanup_sets_connect_to_none(self): self.obj._cleanup() self.assertIsNone(self.obj._conn) def test_connect_invokes_pool_manager_get(self): with mock.patch.object(self.obj._pool_manager, 'get') as get: self.obj._connect() get.assert_called_once_with(self.obj.pid, self.obj) def test_connect_raises_noidleconnectionserror(self): with mock.patch.object(self.obj._pool_manager, 'get') as get: with mock.patch.object(self.obj._pool_manager, 'is_full') as full: get.side_effect = pool.NoIdleConnectionsError(self.obj.pid) full.return_value = True self.assertRaises(pool.NoIdleConnectionsError, self.obj._connect) def test_connect_invokes_uri_to_kwargs(self): self.uri_to_kwargs.assert_called_once_with(self.URI) def test_connect_returned_the_proper_value(self): self.assertEqual(self.obj.connection, self.conn) def test_status_is_ready_by_default(self): self.assertEqual(self.obj._status, self.obj.READY) def test_status_when_not_ready(self): self.conn.status = self.obj.SETUP self.assertEqual(self.obj._status, self.obj.SETUP) def test_get_named_cursor_sets_scrollable(self): result = self.obj._get_cursor(self.obj._conn, 'test1') self.assertTrue(result.scrollable) def test_get_named_cursor_sets_withhold(self): result = self.obj._get_cursor(self.obj._conn, 'test2') self.assertTrue(result.withhhold) @unittest.skipUnless(utils.PYPY, 'connection.reset is PYPY only behavior') def test_connection_reset_in_pypy(self): self.conn.reset.assert_called_once_with() <MSG> Remove JSON support due to psycopg2ct not supporting it, update tests - Also don't perform the weakref cleanup test in pypy since it's not immediate in pypy <DFF> @@ -23,12 +23,10 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def setUp(self, register_uuid, register_json, register_type, connect): + def setUp(self, register_uuid, register_type, connect): self._connect = connect self._connect.reset = mock.Mock() - self._reg_json = register_json self._reg_type = register_type self._reg_uuid = register_uuid self.uri = 'pgsql://[email protected]:5432/queries' @@ -46,11 +44,6 @@ class SessionTests(unittest.TestCase): 'password': None} self._connect.assert_called_once_with(**expectation) - @unittest.skipIf(PYPY, "Not supported in PyPy") - def test_psycopg2_register_json(self): - """Ensure that the JSON extension was registered""" - self._reg_json.assert_called_once_with(conn_or_curs=self.client._conn) - def test_psycopg2_register_uuid(self): """Ensure that the UUID extension was registered""" self._reg_uuid.assert_called_once_with(conn_or_curs=self.client._conn) @@ -99,19 +92,17 @@ class SessionTests(unittest.TestCase): cleanup.assert_called_once_with() @mock.patch('psycopg2.connect') - @mock.patch('psycopg2.extras.register_json') - @mock.patch('psycopg2.extras.register_uuid') @mock.patch('psycopg2.extensions.register_type') - def test_context_manager_creation(self, _uuid, _json, _type, _connect): + @mock.patch('psycopg2.extras.register_uuid') + def test_context_manager_creation(self, _uuid, _type, _connect): """Ensure context manager returns self""" with session.Session(self.uri) as conn: self.assertIsInstance(conn, session.Session) @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_context_manager_cleanup(self, _uuid, _json, _type, _connect): + def test_context_manager_cleanup(self, _uuid, _type, _connect): """Ensure context manager cleans up after self""" with mock.patch('queries.session.Session._cleanup') as cleanup: with session.Session(self.uri): @@ -120,9 +111,8 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_removes_from_cache(self, _uuid, _json, _type, _connect): + def test_close_removes_from_cache(self, _uuid, _type, _connect): """Ensure connection removed from cache on close""" conn = self.client._conn self.client.close() @@ -130,9 +120,8 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_invokes_connection_close(self, _uuid, _json, _type, connect): + def test_close_invokes_connection_close(self, _uuid, _type, connect): """Ensure close calls connection.close""" sess = session.Session('pgsql://foo@bar:9999/baz') close_mock = mock.Mock() @@ -142,9 +131,8 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_sets_conn_to_none(self, _uuid, _json, _type, connect): + def test_close_sets_conn_to_none(self, _uuid, _type, connect): """Ensure Session._conn is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() @@ -152,19 +140,17 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_sets_cursor_to_none(self, _uuid, _json, _type, connect): + def test_close_sets_cursor_to_none(self, _uuid, _type, connect): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() self.assertIsNone(sess._cursor) @mock.patch('psycopg2.connect') - @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') - def test_close_raises_when_closed(self, _uuid, _json, _type, _conn): + def test_close_raises_when_closed(self, _uuid, _type, _conn): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close()
9
Remove JSON support due to psycopg2ct not supporting it, update tests
23
.py
py
bsd-3-clause
gmr/queries
1617
<NME> .travis.yml <BEF> sudo: false language: python python: - 2.6 - 2.7 - pypy - 3.3 - 3.4 - 3.5 services: - postgresql install: - pip install -r test-requirements.txt - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi - python setup.py develop script: nosetests after_success: - codecov deploy: distributions: sdist provider: pypi on: python: 2.7 tags: true all_branches: true user: crad password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= user: crad on: tags: true all_branches: true password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= <MSG> Setup combined coverage in travis <DFF> @@ -1,28 +1,64 @@ sudo: false language: python python: - - 2.6 - - 2.7 - - pypy - - 3.3 - - 3.4 - - 3.5 -services: - - postgresql + - 2.7 + - 3.4 + - 3.5 + - 3.6 + - pypy + - pypy3 + +env: + global: + - PATH=$HOME/.local/bin:$PATH + - AWS_DEFAULT_REGION=us-east-1 + - secure: "inURdx4ldkJqQXL1TyvKImC3EnL5TixC1DlNMBYi5ttygwAk+mSSSw8Yc7klB6D1m6q79xUlHRk06vbz23CsXTM4AClC5Emrk6XN2GlUKl5WI+z+A2skI59buEhLWe7e2KzhB/AVx2E3TfKa0oY7raM0UUnaOkpV1Cj+mHKPIT0=" + - secure: "H32DV3713a6UUuEJujrG7SfUX4/5WrwQy/3DxeptC6L7YPlTYxHBdEsccTfN5z806EheIl4BdIoxoDtq7PU/tWQoG1Lp2ze60mpwrniHajhFnjk7zP6pHvkhGLr8flhSmAb6CQBreNFOHTLWBMGPfi7k1Q9Td9MHbRo/FsTxqsM=" + install: - - pip install -r test-requirements.txt - - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi - - python setup.py develop + - pip install awscli + - pip install -r requires/testing.txt + +stages: + - test + - name: upload_coverage + if: branch = master + - name: deploy + if: tag IS present + script: nosetests + after_success: - - codecov -deploy: - distributions: sdist - provider: pypi - on: - python: 2.7 - tags: true - all_branches: true - user: crad - password: - secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= + - aws s3 cp .coverage "s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/.coverage.${TRAVIS_PYTHON_VERSION}" + +jobs: + include: + - stage: test + services: + - postgres + script: nosetests + - stage: upload coverage + python: 3.6 + install: + - pip install awscli coverage codecov + script: + - mkdir coverage + - aws s3 cp --recursive s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/ + coverage + - cd coverage + - coverage combine + - cd .. + - mv coverage/.coverage . + - coverage report + after_success: codecov + - stage: deploy + python: 3.6 + deploy: + distributions: sdist bdist_wheel + provider: pypi + user: crad + on: + tags: true + all_branches: true + password: + secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI=
58
Setup combined coverage in travis
22
.yml
travis
bsd-3-clause
gmr/queries
1618
<NME> .travis.yml <BEF> sudo: false language: python python: - 2.6 - 2.7 - pypy - 3.3 - 3.4 - 3.5 services: - postgresql install: - pip install -r test-requirements.txt - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi - python setup.py develop script: nosetests after_success: - codecov deploy: distributions: sdist provider: pypi on: python: 2.7 tags: true all_branches: true user: crad password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= user: crad on: tags: true all_branches: true password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= <MSG> Setup combined coverage in travis <DFF> @@ -1,28 +1,64 @@ sudo: false language: python python: - - 2.6 - - 2.7 - - pypy - - 3.3 - - 3.4 - - 3.5 -services: - - postgresql + - 2.7 + - 3.4 + - 3.5 + - 3.6 + - pypy + - pypy3 + +env: + global: + - PATH=$HOME/.local/bin:$PATH + - AWS_DEFAULT_REGION=us-east-1 + - secure: "inURdx4ldkJqQXL1TyvKImC3EnL5TixC1DlNMBYi5ttygwAk+mSSSw8Yc7klB6D1m6q79xUlHRk06vbz23CsXTM4AClC5Emrk6XN2GlUKl5WI+z+A2skI59buEhLWe7e2KzhB/AVx2E3TfKa0oY7raM0UUnaOkpV1Cj+mHKPIT0=" + - secure: "H32DV3713a6UUuEJujrG7SfUX4/5WrwQy/3DxeptC6L7YPlTYxHBdEsccTfN5z806EheIl4BdIoxoDtq7PU/tWQoG1Lp2ze60mpwrniHajhFnjk7zP6pHvkhGLr8flhSmAb6CQBreNFOHTLWBMGPfi7k1Q9Td9MHbRo/FsTxqsM=" + install: - - pip install -r test-requirements.txt - - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi - - python setup.py develop + - pip install awscli + - pip install -r requires/testing.txt + +stages: + - test + - name: upload_coverage + if: branch = master + - name: deploy + if: tag IS present + script: nosetests + after_success: - - codecov -deploy: - distributions: sdist - provider: pypi - on: - python: 2.7 - tags: true - all_branches: true - user: crad - password: - secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= + - aws s3 cp .coverage "s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/.coverage.${TRAVIS_PYTHON_VERSION}" + +jobs: + include: + - stage: test + services: + - postgres + script: nosetests + - stage: upload coverage + python: 3.6 + install: + - pip install awscli coverage codecov + script: + - mkdir coverage + - aws s3 cp --recursive s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/ + coverage + - cd coverage + - coverage combine + - cd .. + - mv coverage/.coverage . + - coverage report + after_success: codecov + - stage: deploy + python: 3.6 + deploy: + distributions: sdist bdist_wheel + provider: pypi + user: crad + on: + tags: true + all_branches: true + password: + secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI=
58
Setup combined coverage in travis
22
.yml
travis
bsd-3-clause
gmr/queries
1619
<NME> tornado_session.py <BEF> """ Tornado Session Adapter Use Queries asynchronously within the Tornado framework. Example Use: .. code:: python class NameListHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession(pool_max_size=60) @gen.coroutine def get(self): data = yield self.session.query('SELECT * FROM names') if data: self.finish({'names': data.items()}) data.free() else: self.set_status(500, 'Error querying the data') """ import logging import socket import warnings from tornado import concurrent, ioloop from psycopg2 import extras, extensions import psycopg2 from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) DEFAULT_MAX_POOL_SIZE = 25 class Results(results.Results): """A TornadoSession specific :py:class:`queries.Results` class that adds the :py:meth:`Results.free <queries.tornado_session.Results.free>` method. The :py:meth:`Results.free <queries.tornado_session.Results.free>` method **must** be called to free the connection that the results were generated on. `Results` objects that are not freed will cause the connections to remain locked and your application will eventually run out of connections in the pool. The following examples illustrate the various behaviors that the ::py:class:`queries.Results <queries.tornado_session.Requests>` class implements: **Using Results as an Iterator** .. code:: python results = yield session.query('SELECT * FROM foo') for row in results print row results.free() **Accessing an individual row by index** .. code:: python results = yield session.query('SELECT * FROM foo') print results[1] # Access the second row of the results results.free() **Casting single row results as a dict** .. code:: python results = yield session.query('SELECT * FROM foo LIMIT 1') print results.as_dict() results.free() **Checking to see if a query was successful** .. code:: python sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'" results = yield session.query(sql) if results: print 'Success' results.free() **Checking the number of rows by using len(Results)** .. code:: python results = yield session.query('SELECT * FROM foo') print '%i rows' % len(results) results.free() """ def __init__(self, cursor, cleanup, fd): self.cursor = cursor self._cleanup = cleanup self._fd = fd self._freed = False def free(self): """Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or self.cursor = cursor self._cleanup = cleanup self._fd = fd @gen.coroutine def free(self): def __del__(self): if not self._freed: LOGGER.warning('Auto-freeing result on deletion') self.free() requests. """ self._cleanup(self.cursor, self._fd) class TornadoSession(session.Session): """Session class for Tornado asynchronous applications. Uses :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use """ def __init__(self, uri=session.DEFAULT_URI, cursor_factory=extras.RealDictCursor, pool_idle_ttl=pool.DEFAULT_IDLE_TTL, pool_max_size=DEFAULT_MAX_POOL_SIZE, io_loop=None): """Connect to a PostgreSQL server using the module wide connection and set the isolation level. :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use :param tornado.ioloop.IOLoop io_loop: IOLoop instance to use """ self._connections = dict() self._cleanup_callback = None self._cursor_factory = cursor_factory self._futures = dict() self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() self._pool_max_size = pool_max_size self._pool_idle_ttl = pool_idle_ttl self._uri = uri self._ensure_pool_exists() def _ensure_pool_exists(self): """Create the pool in the pool manager if it does not exist.""" if self.pid not in self._pool_manager: self._pool_manager.create(self.pid, self._pool_idle_ttl, self._pool_max_size, self._ioloop.time) @property def connection(self): """Do not use this directly with Tornado applications :return: """ return None @property def cursor(self): return None def callproc(self, name, args=None): """Call a stored procedure asynchronously on the server, passing in the arguments to be passed to the stored procedure, yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str name: The stored procedure name :param list args: An optional list of procedure arguments :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('callproc', name, args) def query(self, sql, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('execute', sql, parameters) def validate(self): """Validate the session can connect or has open connections to PostgreSQL. As of ``1.10.3`` .. deprecated:: 1.10.3 As of 1.10.3, this method only warns about Deprecation :rtype: bool """ warnings.warn( 'All functionality removed from this method', DeprecationWarning) def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool if possible, or by creating the new connection. :rtype: psycopg2.extensions.connection :raises: pool.NoIdleConnectionsError """ future = concurrent.Future() # Attempt to get a cached connection from the connection pool try: connection = self._pool_manager.get(self.pid, self) self._connections[connection.fileno()] = connection future.set_result(connection) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) except pool.NoIdleConnectionsError: self._create_connection(future) return future def _create_connection(self, future): """Create a new PostgreSQL connection :param tornado.concurrent.Future future: future for new conn result """ LOGGER.debug('Creating a new connection for %s', self.pid) # Create a new PostgreSQL connection kwargs = utils.uri_to_kwargs(self._uri) try: connection = self._psycopg2_connect(kwargs) except (psycopg2.Error, OSError, socket.error) as error: future.set_exception(error) return # Add the connection for use in _poll_connection fd = connection.fileno() self._connections[fd] = connection def on_connected(cf): """Invoked by the IOLoop when the future is complete for the connection :param Future cf: The future for the initial connection """ if cf.exception(): self._cleanup_fd(fd, True) future.set_exception(cf.exception()) else: try: # Add the connection to the pool LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) except (ValueError, pool.PoolException) as err: LOGGER.exception('Failed to add %r to the pool', self.pid) self._cleanup_fd(fd) future.set_exception(err) return self._pool_manager.lock(self.pid, connection, self) # Added in because psycopg2cffi connects and leaves the # connection in a weird state: consts.STATUS_DATESTYLE, # returning from Connection._setup without setting the state # as const.STATUS_OK if utils.PYPY: connection.status = extensions.STATUS_READY # Register the custom data types self._register_unicode(connection) self._register_uuid(connection) # Set the future result future.set_result(connection) # Add a future that fires once connected self._futures[fd] = concurrent.Future() self._ioloop.add_future(self._futures[fd], on_connected) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) def _execute(self, method, query, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. This function reduces duplicate code for callproc and query by getting the class attribute for the method passed in as the function to call. :param str method: The method attribute to use :param str query: The SQL statement or Stored Procedure name :param list|dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ future = concurrent.Future() def on_connected(cf): """Invoked by the future returned by self._connect""" if cf.exception(): future.set_exception(cf.exception()) return # Get the psycopg2 connection object and cursor conn = cf.result() cursor = self._get_cursor(conn) def completed(qf): """Invoked by the IOLoop when the future has completed""" if qf.exception(): self._incr_exceptions(conn) err = qf.exception() LOGGER.debug('Cleaning cursor due to exception: %r', err) self._exec_cleanup(cursor, conn.fileno()) future.set_exception(err) else: self._incr_executions(conn) value = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(value) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.Future() # Add the future to the IOLoop self._ioloop.add_future(self._futures[conn.fileno()], completed) # Get the cursor, execute the query func = getattr(cursor, method) try: func(query, parameters) except Exception as error: future.set_exception(error) # Ensure the pool exists for the connection self._ensure_pool_exists() # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. :param psycopg2.extensions.cursor cursor: The cursor to close :param int fd: The connection file descriptor """ LOGGER.debug('Closing cursor and cleaning %s', fd) try: cursor.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.debug('Error closing the cursor: %s', error) self._cleanup_fd(fd) # If the cleanup callback exists, remove it if self._cleanup_callback: self._ioloop.remove_timeout(self._cleanup_callback) # Create a new cleanup callback to clean the pool of idle connections self._cleanup_callback = self._ioloop.add_timeout( self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) def _cleanup_fd(self, fd, close=False): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. :param int fd: The fd # to cleanup """ self._ioloop.remove_handler(fd) if fd in self._connections: try: self._pool_manager.free(self.pid, self._connections[fd]) except pool.ConnectionNotFoundError: pass if close: self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd] def _incr_exceptions(self, conn): """Increment the number of exceptions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).exceptions += 1 def _incr_executions(self, conn): """Increment the number of executions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).executions += 1 def _on_io_events(self, fd=None, _events=None): """Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised """ if fd not in self._connections: LOGGER.warning('Received IO event for non-existing connection') return self._poll_connection(fd) def _poll_connection(self, fd): """Check with psycopg2 to see what action to take. If the state is POLL_OK, we should have a pending callback for that fd. :param int fd: The socket fd for the postgresql connection """ try: state = self._connections[fd].poll() except (OSError, socket.error) as error: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.OperationalError('Connection error (%s)' % error) ) except (psycopg2.Error, psycopg2.Warning) as error: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception(error) else: if state == extensions.POLL_OK: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_result(True) elif state == extensions.POLL_WRITE: self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE) elif state == extensions.POLL_READ: self._ioloop.update_handler(fd, ioloop.IOLoop.READ) elif state == extensions.POLL_ERROR: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.Error('Poll Error')) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. :param dict kwargs: Keyword connection args :rtype: psycopg2.extensions.connection """ kwargs['async'] = True return psycopg2.connect(**kwargs) <MSG> Log a warning when a result is leaked. <DFF> @@ -107,6 +107,7 @@ class Results(results.Results): self.cursor = cursor self._cleanup = cleanup self._fd = fd + self._freed = False @gen.coroutine def free(self): @@ -118,8 +119,13 @@ class Results(results.Results): requests. """ + self._freed = True self._cleanup(self.cursor, self._fd) + def __del__(self): + if not self._freed: + LOGGER.warning('%s not freed - %r', self.__class__.__name__, self) + class TornadoSession(session.Session): """Session class for Tornado asynchronous applications. Uses
6
Log a warning when a result is leaked.
0
.py
py
bsd-3-clause
gmr/queries
1620
<NME> tornado_session.py <BEF> """ Tornado Session Adapter Use Queries asynchronously within the Tornado framework. Example Use: .. code:: python class NameListHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession(pool_max_size=60) @gen.coroutine def get(self): data = yield self.session.query('SELECT * FROM names') if data: self.finish({'names': data.items()}) data.free() else: self.set_status(500, 'Error querying the data') """ import logging import socket import warnings from tornado import concurrent, ioloop from psycopg2 import extras, extensions import psycopg2 from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) DEFAULT_MAX_POOL_SIZE = 25 class Results(results.Results): """A TornadoSession specific :py:class:`queries.Results` class that adds the :py:meth:`Results.free <queries.tornado_session.Results.free>` method. The :py:meth:`Results.free <queries.tornado_session.Results.free>` method **must** be called to free the connection that the results were generated on. `Results` objects that are not freed will cause the connections to remain locked and your application will eventually run out of connections in the pool. The following examples illustrate the various behaviors that the ::py:class:`queries.Results <queries.tornado_session.Requests>` class implements: **Using Results as an Iterator** .. code:: python results = yield session.query('SELECT * FROM foo') for row in results print row results.free() **Accessing an individual row by index** .. code:: python results = yield session.query('SELECT * FROM foo') print results[1] # Access the second row of the results results.free() **Casting single row results as a dict** .. code:: python results = yield session.query('SELECT * FROM foo LIMIT 1') print results.as_dict() results.free() **Checking to see if a query was successful** .. code:: python sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'" results = yield session.query(sql) if results: print 'Success' results.free() **Checking the number of rows by using len(Results)** .. code:: python results = yield session.query('SELECT * FROM foo') print '%i rows' % len(results) results.free() """ def __init__(self, cursor, cleanup, fd): self.cursor = cursor self._cleanup = cleanup self._fd = fd self._freed = False def free(self): """Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or self.cursor = cursor self._cleanup = cleanup self._fd = fd @gen.coroutine def free(self): def __del__(self): if not self._freed: LOGGER.warning('Auto-freeing result on deletion') self.free() requests. """ self._cleanup(self.cursor, self._fd) class TornadoSession(session.Session): """Session class for Tornado asynchronous applications. Uses :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use """ def __init__(self, uri=session.DEFAULT_URI, cursor_factory=extras.RealDictCursor, pool_idle_ttl=pool.DEFAULT_IDLE_TTL, pool_max_size=DEFAULT_MAX_POOL_SIZE, io_loop=None): """Connect to a PostgreSQL server using the module wide connection and set the isolation level. :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use :param tornado.ioloop.IOLoop io_loop: IOLoop instance to use """ self._connections = dict() self._cleanup_callback = None self._cursor_factory = cursor_factory self._futures = dict() self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() self._pool_max_size = pool_max_size self._pool_idle_ttl = pool_idle_ttl self._uri = uri self._ensure_pool_exists() def _ensure_pool_exists(self): """Create the pool in the pool manager if it does not exist.""" if self.pid not in self._pool_manager: self._pool_manager.create(self.pid, self._pool_idle_ttl, self._pool_max_size, self._ioloop.time) @property def connection(self): """Do not use this directly with Tornado applications :return: """ return None @property def cursor(self): return None def callproc(self, name, args=None): """Call a stored procedure asynchronously on the server, passing in the arguments to be passed to the stored procedure, yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str name: The stored procedure name :param list args: An optional list of procedure arguments :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('callproc', name, args) def query(self, sql, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('execute', sql, parameters) def validate(self): """Validate the session can connect or has open connections to PostgreSQL. As of ``1.10.3`` .. deprecated:: 1.10.3 As of 1.10.3, this method only warns about Deprecation :rtype: bool """ warnings.warn( 'All functionality removed from this method', DeprecationWarning) def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool if possible, or by creating the new connection. :rtype: psycopg2.extensions.connection :raises: pool.NoIdleConnectionsError """ future = concurrent.Future() # Attempt to get a cached connection from the connection pool try: connection = self._pool_manager.get(self.pid, self) self._connections[connection.fileno()] = connection future.set_result(connection) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) except pool.NoIdleConnectionsError: self._create_connection(future) return future def _create_connection(self, future): """Create a new PostgreSQL connection :param tornado.concurrent.Future future: future for new conn result """ LOGGER.debug('Creating a new connection for %s', self.pid) # Create a new PostgreSQL connection kwargs = utils.uri_to_kwargs(self._uri) try: connection = self._psycopg2_connect(kwargs) except (psycopg2.Error, OSError, socket.error) as error: future.set_exception(error) return # Add the connection for use in _poll_connection fd = connection.fileno() self._connections[fd] = connection def on_connected(cf): """Invoked by the IOLoop when the future is complete for the connection :param Future cf: The future for the initial connection """ if cf.exception(): self._cleanup_fd(fd, True) future.set_exception(cf.exception()) else: try: # Add the connection to the pool LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) except (ValueError, pool.PoolException) as err: LOGGER.exception('Failed to add %r to the pool', self.pid) self._cleanup_fd(fd) future.set_exception(err) return self._pool_manager.lock(self.pid, connection, self) # Added in because psycopg2cffi connects and leaves the # connection in a weird state: consts.STATUS_DATESTYLE, # returning from Connection._setup without setting the state # as const.STATUS_OK if utils.PYPY: connection.status = extensions.STATUS_READY # Register the custom data types self._register_unicode(connection) self._register_uuid(connection) # Set the future result future.set_result(connection) # Add a future that fires once connected self._futures[fd] = concurrent.Future() self._ioloop.add_future(self._futures[fd], on_connected) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) def _execute(self, method, query, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. This function reduces duplicate code for callproc and query by getting the class attribute for the method passed in as the function to call. :param str method: The method attribute to use :param str query: The SQL statement or Stored Procedure name :param list|dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ future = concurrent.Future() def on_connected(cf): """Invoked by the future returned by self._connect""" if cf.exception(): future.set_exception(cf.exception()) return # Get the psycopg2 connection object and cursor conn = cf.result() cursor = self._get_cursor(conn) def completed(qf): """Invoked by the IOLoop when the future has completed""" if qf.exception(): self._incr_exceptions(conn) err = qf.exception() LOGGER.debug('Cleaning cursor due to exception: %r', err) self._exec_cleanup(cursor, conn.fileno()) future.set_exception(err) else: self._incr_executions(conn) value = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(value) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.Future() # Add the future to the IOLoop self._ioloop.add_future(self._futures[conn.fileno()], completed) # Get the cursor, execute the query func = getattr(cursor, method) try: func(query, parameters) except Exception as error: future.set_exception(error) # Ensure the pool exists for the connection self._ensure_pool_exists() # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. :param psycopg2.extensions.cursor cursor: The cursor to close :param int fd: The connection file descriptor """ LOGGER.debug('Closing cursor and cleaning %s', fd) try: cursor.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.debug('Error closing the cursor: %s', error) self._cleanup_fd(fd) # If the cleanup callback exists, remove it if self._cleanup_callback: self._ioloop.remove_timeout(self._cleanup_callback) # Create a new cleanup callback to clean the pool of idle connections self._cleanup_callback = self._ioloop.add_timeout( self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) def _cleanup_fd(self, fd, close=False): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. :param int fd: The fd # to cleanup """ self._ioloop.remove_handler(fd) if fd in self._connections: try: self._pool_manager.free(self.pid, self._connections[fd]) except pool.ConnectionNotFoundError: pass if close: self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd] def _incr_exceptions(self, conn): """Increment the number of exceptions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).exceptions += 1 def _incr_executions(self, conn): """Increment the number of executions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).executions += 1 def _on_io_events(self, fd=None, _events=None): """Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised """ if fd not in self._connections: LOGGER.warning('Received IO event for non-existing connection') return self._poll_connection(fd) def _poll_connection(self, fd): """Check with psycopg2 to see what action to take. If the state is POLL_OK, we should have a pending callback for that fd. :param int fd: The socket fd for the postgresql connection """ try: state = self._connections[fd].poll() except (OSError, socket.error) as error: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.OperationalError('Connection error (%s)' % error) ) except (psycopg2.Error, psycopg2.Warning) as error: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception(error) else: if state == extensions.POLL_OK: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_result(True) elif state == extensions.POLL_WRITE: self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE) elif state == extensions.POLL_READ: self._ioloop.update_handler(fd, ioloop.IOLoop.READ) elif state == extensions.POLL_ERROR: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.Error('Poll Error')) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. :param dict kwargs: Keyword connection args :rtype: psycopg2.extensions.connection """ kwargs['async'] = True return psycopg2.connect(**kwargs) <MSG> Log a warning when a result is leaked. <DFF> @@ -107,6 +107,7 @@ class Results(results.Results): self.cursor = cursor self._cleanup = cleanup self._fd = fd + self._freed = False @gen.coroutine def free(self): @@ -118,8 +119,13 @@ class Results(results.Results): requests. """ + self._freed = True self._cleanup(self.cursor, self._fd) + def __del__(self): + if not self._freed: + LOGGER.warning('%s not freed - %r', self.__class__.__name__, self) + class TornadoSession(session.Session): """Session class for Tornado asynchronous applications. Uses
6
Log a warning when a result is leaked.
0
.py
py
bsd-3-clause
gmr/queries
1621
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<3'] else: install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setuptools.setup( name='queries', version='2.1.0', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Add 3.4 to the trove classifiers <DFF> @@ -19,6 +19,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython',
1
Add 3.4 to the trove classifiers
0
.py
py
bsd-3-clause
gmr/queries
1622
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<3'] else: install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setuptools.setup( name='queries', version='2.1.0', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Add 3.4 to the trove classifiers <DFF> @@ -19,6 +19,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython',
1
Add 3.4 to the trove classifiers
0
.py
py
bsd-3-clause
gmr/queries
1623
<NME> tornado_session_tests.py <BEF> """ Tests for functionality in the tornado_session module """ import unittest import mock # Out of order import to ensure psycopg2cffi is registered from queries import pool, tornado_session from psycopg2 import extras from tornado import concurrent, gen, ioloop, testing class ResultsTests(unittest.TestCase): def setUp(self): self.cursor = mock.Mock() self.fd = 10 self.cleanup = mock.Mock() self.obj = tornado_session.Results(self.cursor, self.cleanup, self.fd) def test_cursor_is_assigned(self): self.assertEqual(self.obj.cursor, self.cursor) def test_fd_is_assigned(self): self.assertEqual(self.obj._fd, self.fd) def test_cleanup_is_assigned(self): self.assertEqual(self.obj._cleanup, self.cleanup) @gen.coroutine def test_free_invokes_cleanup(self): yield self.obj.free() self.cleanup.assert_called_once_with(self.cursor, self.fd) class SessionInitTests(unittest.TestCase): def setUp(self): self.obj = tornado_session.TornadoSession() def test_creates_empty_callback_dict(self): self.assertDictEqual(self.obj._futures, {}) def test_creates_empty_connections_dict(self): self.assertDictEqual(self.obj._connections, {}) def test_sets_default_cursor_factory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_sets_tornado_ioloop_instance(self): self.assertEqual(self.obj._ioloop, ioloop.IOLoop.instance()) def test_sets_poolmananger_instance(self): self.assertEqual(self.obj._pool_manager, pool.PoolManager.instance()) def test_sets_uri(self): self.assertEqual(self.obj._uri, tornado_session.session.DEFAULT_URI) def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) def test_connection_is_none(self): self.assertIsNone(self.obj.connection) def test_cursor_is_none(self): self.assertIsNone(self.obj.cursor) class SessionConnectTests(testing.AsyncTestCase): def setUp(self): super(SessionConnectTests, self).setUp() self.conn = mock.Mock() self.conn.fileno = mock.Mock(return_value=10) self.obj = tornado_session.TornadoSession(io_loop=self.io_loop) def create_connection(future): future.set_result(self.conn) self.obj._create_connection = create_connection @testing.gen_test def test_connect_returns_new_connection(self): conn = yield self.obj._connect() self.assertEqual(conn, self.conn) @testing.gen_test def test_connect_returns_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) second_result = yield self.obj._connect() self.assertEqual(second_result, conn) @testing.gen_test def test_connect_gets_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: with mock.patch.object(self.io_loop, 'add_handler'): yield self.obj._connect() get.assert_called_once_with(self.obj.pid, self.obj) @testing.gen_test def test_connect_pooled_connection_invokes_add_handler(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: get.return_value = self.conn with mock.patch.object(self.io_loop, 'add_handler') as add_handler: yield self.obj._connect() add_handler.assert_called_once_with(self.conn.fileno(), self.obj._on_io_events, ioloop.IOLoop.WRITE) def test_psycopg2_connect_invokes_psycopg2_connect(self): with mock.patch('psycopg2.connect') as connect: self.obj._psycopg2_connect({}) connect.assert_called_once_with(**{'async': True}) def test_on_io_events_returns_if_fd_not_present(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_not_called() def test_on_io_events_calls_poll_connection(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._connections[1337] = True self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_called_once_with(1337) def test_exec_cleanup_closes_cursor(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() cursor = mock.Mock() cursor.close = mock.Mock() self.obj._exec_cleanup(cursor, 14) cursor.close.assert_called_once_with() def test_exec_cleanup_frees_connection(self): with mock.patch.object(self.obj._pool_manager, 'free') as pm_free: with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = conn = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) pm_free.assert_called_once_with(self.obj.pid, conn) def test_exec_cleanup_remove_handler_invoked(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh: self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) rh.assert_called_once_with(14) def test_exec_removes_connection(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._connections) def test_exec_removes_future(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._futures[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._futures) def test_pool_manager_add_failures_are_propagated(self): futures = [] def add_future(future, callback): futures.append((future, callback)) obj = tornado_session.TornadoSession() obj._ioloop = mock.Mock() obj._ioloop.add_future = add_future future = concurrent.Future() with mock.patch.object(obj._pool_manager, 'add') as add_method: add_method.side_effect = pool.PoolFullError(mock.Mock()) obj._create_connection(future) self.assertEqual(len(futures), 1) connected_future, callback = futures.pop() connected_future.set_result(True) callback(connected_future) self.assertIs(future.exception(), add_method.side_effect) class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_callproc_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) @testing.gen_test def test_query_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) """ @testing.gen_test def test_query_error_key_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) @testing.gen_test def test_query_error_key_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(KeyError): yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) @testing.gen_test def test_query_error_index_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(IndexError): yield obj.query('SELECT * FROM foo WHERE bar=%s', []) <MSG> Catch bare exception in test <DFF> @@ -224,11 +224,11 @@ class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_query_error_key_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) - with self.assertRaises(KeyError): + with self.assertRaises(Exception): yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) @testing.gen_test def test_query_error_index_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) - with self.assertRaises(IndexError): + with self.assertRaises(Exception): yield obj.query('SELECT * FROM foo WHERE bar=%s', [])
2
Catch bare exception in test
2
.py
py
bsd-3-clause
gmr/queries
1624
<NME> tornado_session_tests.py <BEF> """ Tests for functionality in the tornado_session module """ import unittest import mock # Out of order import to ensure psycopg2cffi is registered from queries import pool, tornado_session from psycopg2 import extras from tornado import concurrent, gen, ioloop, testing class ResultsTests(unittest.TestCase): def setUp(self): self.cursor = mock.Mock() self.fd = 10 self.cleanup = mock.Mock() self.obj = tornado_session.Results(self.cursor, self.cleanup, self.fd) def test_cursor_is_assigned(self): self.assertEqual(self.obj.cursor, self.cursor) def test_fd_is_assigned(self): self.assertEqual(self.obj._fd, self.fd) def test_cleanup_is_assigned(self): self.assertEqual(self.obj._cleanup, self.cleanup) @gen.coroutine def test_free_invokes_cleanup(self): yield self.obj.free() self.cleanup.assert_called_once_with(self.cursor, self.fd) class SessionInitTests(unittest.TestCase): def setUp(self): self.obj = tornado_session.TornadoSession() def test_creates_empty_callback_dict(self): self.assertDictEqual(self.obj._futures, {}) def test_creates_empty_connections_dict(self): self.assertDictEqual(self.obj._connections, {}) def test_sets_default_cursor_factory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_sets_tornado_ioloop_instance(self): self.assertEqual(self.obj._ioloop, ioloop.IOLoop.instance()) def test_sets_poolmananger_instance(self): self.assertEqual(self.obj._pool_manager, pool.PoolManager.instance()) def test_sets_uri(self): self.assertEqual(self.obj._uri, tornado_session.session.DEFAULT_URI) def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) def test_connection_is_none(self): self.assertIsNone(self.obj.connection) def test_cursor_is_none(self): self.assertIsNone(self.obj.cursor) class SessionConnectTests(testing.AsyncTestCase): def setUp(self): super(SessionConnectTests, self).setUp() self.conn = mock.Mock() self.conn.fileno = mock.Mock(return_value=10) self.obj = tornado_session.TornadoSession(io_loop=self.io_loop) def create_connection(future): future.set_result(self.conn) self.obj._create_connection = create_connection @testing.gen_test def test_connect_returns_new_connection(self): conn = yield self.obj._connect() self.assertEqual(conn, self.conn) @testing.gen_test def test_connect_returns_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) second_result = yield self.obj._connect() self.assertEqual(second_result, conn) @testing.gen_test def test_connect_gets_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: with mock.patch.object(self.io_loop, 'add_handler'): yield self.obj._connect() get.assert_called_once_with(self.obj.pid, self.obj) @testing.gen_test def test_connect_pooled_connection_invokes_add_handler(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: get.return_value = self.conn with mock.patch.object(self.io_loop, 'add_handler') as add_handler: yield self.obj._connect() add_handler.assert_called_once_with(self.conn.fileno(), self.obj._on_io_events, ioloop.IOLoop.WRITE) def test_psycopg2_connect_invokes_psycopg2_connect(self): with mock.patch('psycopg2.connect') as connect: self.obj._psycopg2_connect({}) connect.assert_called_once_with(**{'async': True}) def test_on_io_events_returns_if_fd_not_present(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_not_called() def test_on_io_events_calls_poll_connection(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._connections[1337] = True self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_called_once_with(1337) def test_exec_cleanup_closes_cursor(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() cursor = mock.Mock() cursor.close = mock.Mock() self.obj._exec_cleanup(cursor, 14) cursor.close.assert_called_once_with() def test_exec_cleanup_frees_connection(self): with mock.patch.object(self.obj._pool_manager, 'free') as pm_free: with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = conn = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) pm_free.assert_called_once_with(self.obj.pid, conn) def test_exec_cleanup_remove_handler_invoked(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh: self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) rh.assert_called_once_with(14) def test_exec_removes_connection(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._connections) def test_exec_removes_future(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._futures[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._futures) def test_pool_manager_add_failures_are_propagated(self): futures = [] def add_future(future, callback): futures.append((future, callback)) obj = tornado_session.TornadoSession() obj._ioloop = mock.Mock() obj._ioloop.add_future = add_future future = concurrent.Future() with mock.patch.object(obj._pool_manager, 'add') as add_method: add_method.side_effect = pool.PoolFullError(mock.Mock()) obj._create_connection(future) self.assertEqual(len(futures), 1) connected_future, callback = futures.pop() connected_future.set_result(True) callback(connected_future) self.assertIs(future.exception(), add_method.side_effect) class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_callproc_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) @testing.gen_test def test_query_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) """ @testing.gen_test def test_query_error_key_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) @testing.gen_test def test_query_error_key_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(KeyError): yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) @testing.gen_test def test_query_error_index_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(IndexError): yield obj.query('SELECT * FROM foo WHERE bar=%s', []) <MSG> Catch bare exception in test <DFF> @@ -224,11 +224,11 @@ class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_query_error_key_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) - with self.assertRaises(KeyError): + with self.assertRaises(Exception): yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) @testing.gen_test def test_query_error_index_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) - with self.assertRaises(IndexError): + with self.assertRaises(Exception): yield obj.query('SELECT * FROM foo WHERE bar=%s', [])
2
Catch bare exception in test
2
.py
py
bsd-3-clause
gmr/queries
1625
<NME> README.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. Check out the `Usage`_ section below to see how easy it can be. Key features include: - Simplified API - Support of Python 2.7+ and 3.4+ - PyPy support via psycopg2cffi_ - Asynchronous support for Tornado_ - Connection information provided by URI - Query results delivered as a generator based iterators - Automatically registered data-type support for UUIDs, Unicode and Unicode Arrays - Ability to directly access psycopg2 ``connection`` and ``cursor`` objects - Internal connection pooling |Version| |Status| |Coverage| |CodeClimate| |License| |PythonVersions| Documentation ------------- Documentation is available at https://queries.readthedocs.org Installation ------------ Queries is available via pypi_ and can be installed with easy_install or pip: .. code:: bash pip install queries Usage ----- Queries provides a session based API for interacting with PostgreSQL. Simply pass in the URI_ of the PostgreSQL server to connect to when creating a session: .. code:: python session = queries.Session("postgresql://postgres@localhost:5432/postgres") Queries built-in connection pooling will re-use connections when possible, lowering the overhead of connecting and reconnecting. When specifying a URI, if you omit the username and database name to connect with, Queries will use the current OS username for both. You can also omit the URI when connecting to connect to localhost on port 5432 as the current OS user, connecting to a database named for the current user. For example, if your username is ``fred`` and you omit the URI when issuing ``queries.query`` the URI that is constructed would be ``postgresql://fred@localhost:5432/fred``. If you'd rather use individual values for the connection, the queries.uri() method provides a quick and easy way to create a URI to pass into the various methods. .. code:: python >>> queries.uri("server-name", 5432, "dbname", "user", "pass") 'postgresql://user:pass@server-name:5432/dbname' Environment Variables ^^^^^^^^^^^^^^^^^^^^^ Currently Queries uses the following environment variables for tweaking various configuration values. The supported ones are: * ``QUERIES_MAX_POOL_SIZE`` - Modify the maximum size of the connection pool (default: 1) Using the queries.Session class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To execute queries or call stored procedures, you start by creating an instance of the ``queries.Session`` class. It can act as a context manager, meaning you can use it with the ``with`` keyword and it will take care of cleaning up after itself. For more information on the ``with`` keyword and context managers, see PEP343_. In addition to both the ``queries.Session.query`` and ``queries.Session.callproc`` methods that are similar to the simple API methods, the ``queries.Session`` class provides access to the psycopg2 connection and cursor objects. **Using queries.Session.query** The following example shows how a ``queries.Session`` object can be used as a context manager to query the database table: .. code:: python >>> import pprint >>> import queries >>> >>> with queries.Session() as session: ... for row in session.query('SELECT * FROM names'): ... pprint.pprint(row) ... {'id': 1, 'name': u'Jacob'} {'id': 2, 'name': u'Mason'} {'id': 3, 'name': u'Ethan'} **Using queries.Session.callproc** This example uses ``queries.Session.callproc`` to execute a stored procedure and then pretty-prints the single row results as a dictionary: .. code:: python >>> import pprint >>> import queries >>> with queries.Session() as session: ... results = session.callproc('chr', [65]) ... pprint.pprint(results.as_dict()) ... {'chr': u'A'} **Asynchronous Queries with Tornado** In addition to providing a Pythonic, synchronous client API for PostgreSQL, Queries provides a very similar asynchronous API for use with Tornado. The only major difference API difference between ``queries.TornadoSession`` and ``queries.Session`` is the ``TornadoSession.query`` and ``TornadoSession.callproc`` methods return the entire result set instead of acting as an iterator over the results. The following example uses ``TornadoSession.query`` in an asynchronous Tornado_ web application to send a JSON payload with the query result set. .. code:: python from tornado import gen, ioloop, web import queries class MainHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession() @gen.coroutine def get(self): results = yield self.session.query('SELECT * FROM names') self.finish({'data': results.items()}) results.free() application = web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) ioloop.IOLoop.instance().start() Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. History ------- Queries is a fork and enhancement of pgsql_wrapper_, which can be found in the main GitHub repository of Queries as tags prior to version 1.2.0. .. _pypi: https://pypi.python.org/pypi/queries .. _psycopg2: https://pypi.python.org/pypi/psycopg2 .. _documentation: https://queries.readthedocs.org .. _URI: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING .. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper .. _Tornado: http://tornadoweb.org .. _PEP343: http://legacy.python.org/dev/peps/pep-0343/ .. _psycopg2cffi: https://pypi.python.org/pypi/psycopg2cffi .. |Version| image:: https://img.shields.io/pypi/v/queries.svg? :target: https://pypi.python.org/pypi/queries .. |Status| image:: https://img.shields.io/travis/gmr/queries.svg? :target: https://travis-ci.org/gmr/queries .. |Coverage| image:: https://img.shields.io/codecov/c/github/gmr/queries.svg? :target: https://codecov.io/github/gmr/queries?branch=master .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries .. |CodeClimate| image:: https://img.shields.io/codeclimate/github/gmr/queries.svg? :target: https://codeclimate.com/github/gmr/queries .. |PythonVersions| image:: https://img.shields.io/pypi/pyversions/queries.svg? :target: https://github.com/gmr/queries <MSG> Remove non-working codeclimate badge <DFF> @@ -21,7 +21,7 @@ Key features include: - Ability to directly access psycopg2 ``connection`` and ``cursor`` objects - Internal connection pooling -|Version| |Status| |Coverage| |CodeClimate| |License| |PythonVersions| +|Version| |Status| |Coverage| |License| |PythonVersions| Documentation ------------- @@ -182,8 +182,5 @@ main GitHub repository of Queries as tags prior to version 1.2.0. .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries -.. |CodeClimate| image:: https://img.shields.io/codeclimate/github/gmr/queries.svg? - :target: https://codeclimate.com/github/gmr/queries - .. |PythonVersions| image:: https://img.shields.io/pypi/pyversions/queries.svg? :target: https://github.com/gmr/queries
1
Remove non-working codeclimate badge
4
.rst
rst
bsd-3-clause
gmr/queries
1626
<NME> README.rst <BEF> Queries: PostgreSQL Simplified ============================== *Queries* is a BSD licensed opinionated wrapper of the psycopg2_ library for interacting with PostgreSQL. The popular psycopg2_ package is a full-featured python client. Unfortunately as a developer, you're often repeating the same steps to get started with your applications that use it. Queries aims to reduce the complexity of psycopg2 while adding additional features to make writing PostgreSQL client applications both fast and easy. Check out the `Usage`_ section below to see how easy it can be. Key features include: - Simplified API - Support of Python 2.7+ and 3.4+ - PyPy support via psycopg2cffi_ - Asynchronous support for Tornado_ - Connection information provided by URI - Query results delivered as a generator based iterators - Automatically registered data-type support for UUIDs, Unicode and Unicode Arrays - Ability to directly access psycopg2 ``connection`` and ``cursor`` objects - Internal connection pooling |Version| |Status| |Coverage| |CodeClimate| |License| |PythonVersions| Documentation ------------- Documentation is available at https://queries.readthedocs.org Installation ------------ Queries is available via pypi_ and can be installed with easy_install or pip: .. code:: bash pip install queries Usage ----- Queries provides a session based API for interacting with PostgreSQL. Simply pass in the URI_ of the PostgreSQL server to connect to when creating a session: .. code:: python session = queries.Session("postgresql://postgres@localhost:5432/postgres") Queries built-in connection pooling will re-use connections when possible, lowering the overhead of connecting and reconnecting. When specifying a URI, if you omit the username and database name to connect with, Queries will use the current OS username for both. You can also omit the URI when connecting to connect to localhost on port 5432 as the current OS user, connecting to a database named for the current user. For example, if your username is ``fred`` and you omit the URI when issuing ``queries.query`` the URI that is constructed would be ``postgresql://fred@localhost:5432/fred``. If you'd rather use individual values for the connection, the queries.uri() method provides a quick and easy way to create a URI to pass into the various methods. .. code:: python >>> queries.uri("server-name", 5432, "dbname", "user", "pass") 'postgresql://user:pass@server-name:5432/dbname' Environment Variables ^^^^^^^^^^^^^^^^^^^^^ Currently Queries uses the following environment variables for tweaking various configuration values. The supported ones are: * ``QUERIES_MAX_POOL_SIZE`` - Modify the maximum size of the connection pool (default: 1) Using the queries.Session class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To execute queries or call stored procedures, you start by creating an instance of the ``queries.Session`` class. It can act as a context manager, meaning you can use it with the ``with`` keyword and it will take care of cleaning up after itself. For more information on the ``with`` keyword and context managers, see PEP343_. In addition to both the ``queries.Session.query`` and ``queries.Session.callproc`` methods that are similar to the simple API methods, the ``queries.Session`` class provides access to the psycopg2 connection and cursor objects. **Using queries.Session.query** The following example shows how a ``queries.Session`` object can be used as a context manager to query the database table: .. code:: python >>> import pprint >>> import queries >>> >>> with queries.Session() as session: ... for row in session.query('SELECT * FROM names'): ... pprint.pprint(row) ... {'id': 1, 'name': u'Jacob'} {'id': 2, 'name': u'Mason'} {'id': 3, 'name': u'Ethan'} **Using queries.Session.callproc** This example uses ``queries.Session.callproc`` to execute a stored procedure and then pretty-prints the single row results as a dictionary: .. code:: python >>> import pprint >>> import queries >>> with queries.Session() as session: ... results = session.callproc('chr', [65]) ... pprint.pprint(results.as_dict()) ... {'chr': u'A'} **Asynchronous Queries with Tornado** In addition to providing a Pythonic, synchronous client API for PostgreSQL, Queries provides a very similar asynchronous API for use with Tornado. The only major difference API difference between ``queries.TornadoSession`` and ``queries.Session`` is the ``TornadoSession.query`` and ``TornadoSession.callproc`` methods return the entire result set instead of acting as an iterator over the results. The following example uses ``TornadoSession.query`` in an asynchronous Tornado_ web application to send a JSON payload with the query result set. .. code:: python from tornado import gen, ioloop, web import queries class MainHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession() @gen.coroutine def get(self): results = yield self.session.query('SELECT * FROM names') self.finish({'data': results.items()}) results.free() application = web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) ioloop.IOLoop.instance().start() Inspiration ----------- Queries is inspired by `Kenneth Reitz's <https://github.com/kennethreitz/>`_ awesome work on `requests <http://docs.python-requests.org/en/latest/>`_. History ------- Queries is a fork and enhancement of pgsql_wrapper_, which can be found in the main GitHub repository of Queries as tags prior to version 1.2.0. .. _pypi: https://pypi.python.org/pypi/queries .. _psycopg2: https://pypi.python.org/pypi/psycopg2 .. _documentation: https://queries.readthedocs.org .. _URI: http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING .. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper .. _Tornado: http://tornadoweb.org .. _PEP343: http://legacy.python.org/dev/peps/pep-0343/ .. _psycopg2cffi: https://pypi.python.org/pypi/psycopg2cffi .. |Version| image:: https://img.shields.io/pypi/v/queries.svg? :target: https://pypi.python.org/pypi/queries .. |Status| image:: https://img.shields.io/travis/gmr/queries.svg? :target: https://travis-ci.org/gmr/queries .. |Coverage| image:: https://img.shields.io/codecov/c/github/gmr/queries.svg? :target: https://codecov.io/github/gmr/queries?branch=master .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries .. |CodeClimate| image:: https://img.shields.io/codeclimate/github/gmr/queries.svg? :target: https://codeclimate.com/github/gmr/queries .. |PythonVersions| image:: https://img.shields.io/pypi/pyversions/queries.svg? :target: https://github.com/gmr/queries <MSG> Remove non-working codeclimate badge <DFF> @@ -21,7 +21,7 @@ Key features include: - Ability to directly access psycopg2 ``connection`` and ``cursor`` objects - Internal connection pooling -|Version| |Status| |Coverage| |CodeClimate| |License| |PythonVersions| +|Version| |Status| |Coverage| |License| |PythonVersions| Documentation ------------- @@ -182,8 +182,5 @@ main GitHub repository of Queries as tags prior to version 1.2.0. .. |License| image:: https://img.shields.io/github/license/gmr/queries.svg? :target: https://github.com/gmr/queries -.. |CodeClimate| image:: https://img.shields.io/codeclimate/github/gmr/queries.svg? - :target: https://codeclimate.com/github/gmr/queries - .. |PythonVersions| image:: https://img.shields.io/pypi/pyversions/queries.svg? :target: https://github.com/gmr/queries
1
Remove non-working codeclimate badge
4
.rst
rst
bsd-3-clause
gmr/queries
1627
<NME> pool_tests.py <BEF> """ Tests for functionality in the pool module """ import time import unittest import uuid except ImportError: import unittest import uuid import weakref from queries import pool def mock_connection(): conn = mock.MagicMock('psycopg2.extensions.connection') conn.close = mock.Mock() conn.closed = True conn.isexecuting = mock.Mock(return_value=False) return conn class PoolTests(unittest.TestCase): def test_id_is_set(self): pool_id = str(uuid.uuid4()) obj = pool.Pool(pool_id) self.assertEqual(obj._id, pool_id) def test_id_property(self): pool_id = str(uuid.uuid4()) obj = pool.Pool(pool_id) self.assertEqual(obj.id, pool_id) def test_idle_ttl_is_default(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(obj.idle_ttl, pool.DEFAULT_IDLE_TTL) def test_max_size_is_default(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(obj.max_size, pool.DEFAULT_MAX_SIZE) def test_idle_ttl_constructor_assignment(self): obj = pool.Pool(str(uuid.uuid4()), 10) self.assertEqual(obj.idle_ttl, 10) def test_max_size_constructor_assignment(self): obj = pool.Pool(str(uuid.uuid4()), max_size=10) self.assertEqual(obj.max_size, 10) def test_idle_ttl_assignment(self): obj = pool.Pool(str(uuid.uuid4())) obj.set_idle_ttl(10) self.assertEqual(obj.idle_ttl, 10) def test_max_size_assignment(self): obj = pool.Pool(str(uuid.uuid4())) obj.set_max_size(10) self.assertEqual(obj.max_size, 10) def test_pool_doesnt_contain_connection(self): obj = pool.Pool(str(uuid.uuid4())) self.assertNotIn('foo', obj) def test_default_connection_count(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(len(obj), 0) def test_add_new_connection(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertIn(psycopg2_conn, obj) def test_connection_count_after_add(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertEqual(len(obj), 1) def test_add_existing_connection_raises_on_second_add(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertRaises(ValueError, obj.add, psycopg2_conn) def test_add_when_pool_is_full_raises(self): obj = pool.Pool(str(uuid.uuid4()), max_size=1) obj.add(mock.Mock()) mock_conn = mock.Mock() self.assertRaises(pool.PoolFullError, obj.add, mock_conn) def test_closed_conn_invokes_remove_on_clean(self): psycopg2_conn = mock.Mock() psycopg2_conn.closed = True obj = pool.Pool(str(uuid.uuid4())) obj.remove = mock.Mock() obj.add(psycopg2_conn) obj.clean() obj.remove.assert_called_once_with(psycopg2_conn) def test_clean_closes_all_when_idle(self): obj = pool.Pool(str(uuid.uuid4()), idle_ttl=10) obj.idle_start = time.time() - 20 obj.close = mock.Mock() obj.clean() obj.close.assert_called_once_with() def test_close_close_removes_all(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) obj.remove = mock.Mock() psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] obj.close() psycopg2_calls = [mock.call(c) for c in psycopg2_conns] obj.remove.assert_has_calls(psycopg2_calls) def test_free_invokes_connection_free(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self._connection = obj.connection_handle conn = self._connection(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conn) conn.free.assert_called_once_with() def test_free_raises_not_found_exception(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) conn = obj.connection_handle(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conn) conn.free.assert_called_once_with() def test_free_resets_idle_start(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): [obj.add(conn) for conn in psycopg2_conns] for psycopg2_conn in psycopg2_conns: conn = obj.connection_handle(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conns[1]) self.assertAlmostEqual(int(obj.idle_start), int(time.time())) def test_free_raises_on_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.free, mock.Mock()) def test_get_returns_first_psycopg2_conn(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] session = mock.Mock() self.assertEqual(obj.get(session), psycopg2_conns[0]) def test_get_locks_first_psycopg2_conn(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] lock = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, lock=lock): session = mock.Mock() obj.get(session) lock.assert_called_once_with(session) def test_get_resets_idle_start_to_none(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): session = mock.Mock() obj.idle_start = time.time() obj.get(session) self.assertIsNone(obj.idle_start) def test_get_raises_when_no_idle_connections(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] session = mock.Mock() self.assertRaises(pool.NoIdleConnectionsError, obj.get, session) def test_idle_connections(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): self.assertListEqual([c.handle for c in obj.idle_connections], psycopg2_conns) def test_idle_duration_when_none(self): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = None self.assertEqual(obj.idle_duration, 0) def test_idle_duration_when_set(self): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() - 5 self.assertAlmostEqual(int(obj.idle_duration), 5) def test_is_full_property_when_full(self): obj = pool.Pool(str(uuid.uuid4()), max_size=2) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] self.assertTrue(obj.is_full) def test_is_full_property_when_not_full(self): obj = pool.Pool(str(uuid.uuid4()), max_size=3) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] self.assertFalse(obj.is_full) def test_connection_lock_is_called_when_lock_is(self): with mock.patch('queries.pool.Connection.lock') as lock: obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) session = mock.Mock() obj.lock(psycopg2_conn, session) lock.assert_called_once_with(session) def test_locks_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.lock, mock.Mock(), mock.Mock()) def test_lock_resets_idle_start(self): with mock.patch('queries.pool.Connection.lock'): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.lock(psycopg2_conn, mock.Mock()) self.assertIsNone(obj.idle_start) def test_remove_removes_connection(self): with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) self.assertNotIn(psycopg2_conn, obj) def test_remove_closes_connection(self): close_method = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, close=close_method): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) close_method.assert_called_once_with() def test_remove_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.remove, mock.Mock()) def test_remove_raises_when_connection_is_busy(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() psycopg2_conn.closed = False obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.remove, psycopg2_conn) def test__connection_returns_handle(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self.assertEqual( obj.connection_handle(psycopg2_conn).handle, psycopg2_conn) def test_shutdown_raises_when_executing(self): psycopg2_conn = mock_connection() psycopg2_conn.isexecuting.return_value = True obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.shutdown) <MSG> Fix typo, remove unused import <DFF> @@ -9,7 +9,6 @@ try: except ImportError: import unittest import uuid -import weakref from queries import pool
0
Fix typo, remove unused import
1
.py
py
bsd-3-clause
gmr/queries
1628
<NME> pool_tests.py <BEF> """ Tests for functionality in the pool module """ import time import unittest import uuid except ImportError: import unittest import uuid import weakref from queries import pool def mock_connection(): conn = mock.MagicMock('psycopg2.extensions.connection') conn.close = mock.Mock() conn.closed = True conn.isexecuting = mock.Mock(return_value=False) return conn class PoolTests(unittest.TestCase): def test_id_is_set(self): pool_id = str(uuid.uuid4()) obj = pool.Pool(pool_id) self.assertEqual(obj._id, pool_id) def test_id_property(self): pool_id = str(uuid.uuid4()) obj = pool.Pool(pool_id) self.assertEqual(obj.id, pool_id) def test_idle_ttl_is_default(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(obj.idle_ttl, pool.DEFAULT_IDLE_TTL) def test_max_size_is_default(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(obj.max_size, pool.DEFAULT_MAX_SIZE) def test_idle_ttl_constructor_assignment(self): obj = pool.Pool(str(uuid.uuid4()), 10) self.assertEqual(obj.idle_ttl, 10) def test_max_size_constructor_assignment(self): obj = pool.Pool(str(uuid.uuid4()), max_size=10) self.assertEqual(obj.max_size, 10) def test_idle_ttl_assignment(self): obj = pool.Pool(str(uuid.uuid4())) obj.set_idle_ttl(10) self.assertEqual(obj.idle_ttl, 10) def test_max_size_assignment(self): obj = pool.Pool(str(uuid.uuid4())) obj.set_max_size(10) self.assertEqual(obj.max_size, 10) def test_pool_doesnt_contain_connection(self): obj = pool.Pool(str(uuid.uuid4())) self.assertNotIn('foo', obj) def test_default_connection_count(self): obj = pool.Pool(str(uuid.uuid4())) self.assertEqual(len(obj), 0) def test_add_new_connection(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertIn(psycopg2_conn, obj) def test_connection_count_after_add(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertEqual(len(obj), 1) def test_add_existing_connection_raises_on_second_add(self): psycopg2_conn = mock.Mock() obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertRaises(ValueError, obj.add, psycopg2_conn) def test_add_when_pool_is_full_raises(self): obj = pool.Pool(str(uuid.uuid4()), max_size=1) obj.add(mock.Mock()) mock_conn = mock.Mock() self.assertRaises(pool.PoolFullError, obj.add, mock_conn) def test_closed_conn_invokes_remove_on_clean(self): psycopg2_conn = mock.Mock() psycopg2_conn.closed = True obj = pool.Pool(str(uuid.uuid4())) obj.remove = mock.Mock() obj.add(psycopg2_conn) obj.clean() obj.remove.assert_called_once_with(psycopg2_conn) def test_clean_closes_all_when_idle(self): obj = pool.Pool(str(uuid.uuid4()), idle_ttl=10) obj.idle_start = time.time() - 20 obj.close = mock.Mock() obj.clean() obj.close.assert_called_once_with() def test_close_close_removes_all(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) obj.remove = mock.Mock() psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] obj.close() psycopg2_calls = [mock.call(c) for c in psycopg2_conns] obj.remove.assert_has_calls(psycopg2_calls) def test_free_invokes_connection_free(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self._connection = obj.connection_handle conn = self._connection(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conn) conn.free.assert_called_once_with() def test_free_raises_not_found_exception(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) conn = obj.connection_handle(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conn) conn.free.assert_called_once_with() def test_free_resets_idle_start(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): [obj.add(conn) for conn in psycopg2_conns] for psycopg2_conn in psycopg2_conns: conn = obj.connection_handle(psycopg2_conn) conn.free = mock.Mock() obj.free(psycopg2_conns[1]) self.assertAlmostEqual(int(obj.idle_start), int(time.time())) def test_free_raises_on_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.free, mock.Mock()) def test_get_returns_first_psycopg2_conn(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] session = mock.Mock() self.assertEqual(obj.get(session), psycopg2_conns[0]) def test_get_locks_first_psycopg2_conn(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] lock = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, lock=lock): session = mock.Mock() obj.get(session) lock.assert_called_once_with(session) def test_get_resets_idle_start_to_none(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): session = mock.Mock() obj.idle_start = time.time() obj.get(session) self.assertIsNone(obj.idle_start) def test_get_raises_when_no_idle_connections(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] session = mock.Mock() self.assertRaises(pool.NoIdleConnectionsError, obj.get, session) def test_idle_connections(self): obj = pool.Pool(str(uuid.uuid4()), max_size=100) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): self.assertListEqual([c.handle for c in obj.idle_connections], psycopg2_conns) def test_idle_duration_when_none(self): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = None self.assertEqual(obj.idle_duration, 0) def test_idle_duration_when_set(self): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() - 5 self.assertAlmostEqual(int(obj.idle_duration), 5) def test_is_full_property_when_full(self): obj = pool.Pool(str(uuid.uuid4()), max_size=2) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] self.assertTrue(obj.is_full) def test_is_full_property_when_not_full(self): obj = pool.Pool(str(uuid.uuid4()), max_size=3) psycopg2_conns = [mock.Mock(), mock.Mock()] [obj.add(conn) for conn in psycopg2_conns] self.assertFalse(obj.is_full) def test_connection_lock_is_called_when_lock_is(self): with mock.patch('queries.pool.Connection.lock') as lock: obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) session = mock.Mock() obj.lock(psycopg2_conn, session) lock.assert_called_once_with(session) def test_locks_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.lock, mock.Mock(), mock.Mock()) def test_lock_resets_idle_start(self): with mock.patch('queries.pool.Connection.lock'): obj = pool.Pool(str(uuid.uuid4())) obj.idle_start = time.time() psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.lock(psycopg2_conn, mock.Mock()) self.assertIsNone(obj.idle_start) def test_remove_removes_connection(self): with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) self.assertNotIn(psycopg2_conn, obj) def test_remove_closes_connection(self): close_method = mock.Mock() with mock.patch.multiple('queries.pool.Connection', busy=False, closed=False, close=close_method): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) obj.remove(psycopg2_conn) close_method.assert_called_once_with() def test_remove_raises_when_connection_not_found(self): obj = pool.Pool(str(uuid.uuid4())) self.assertRaises(pool.ConnectionNotFoundError, obj.remove, mock.Mock()) def test_remove_raises_when_connection_is_busy(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() psycopg2_conn.closed = False obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.remove, psycopg2_conn) def test__connection_returns_handle(self): obj = pool.Pool(str(uuid.uuid4())) psycopg2_conn = mock.Mock() obj.add(psycopg2_conn) self.assertEqual( obj.connection_handle(psycopg2_conn).handle, psycopg2_conn) def test_shutdown_raises_when_executing(self): psycopg2_conn = mock_connection() psycopg2_conn.isexecuting.return_value = True obj = pool.Pool(str(uuid.uuid4())) obj.add(psycopg2_conn) self.assertRaises(pool.ConnectionBusyError, obj.shutdown) <MSG> Fix typo, remove unused import <DFF> @@ -9,7 +9,6 @@ try: except ImportError: import unittest import uuid -import weakref from queries import pool
0
Fix typo, remove unused import
1
.py
py
bsd-3-clause
gmr/queries
1629
<NME> history.rst <BEF> Version History =============== 2.0.0 2018-01-29 ----------------- - REMOVED support for Python 2.6 - FIXED CPU Pegging bug: Cleanup IOLoop and internal stack in ``TornadoSession`` on connection error. In the case of a connection error, the failure to do this caused CPU to peg @ 100% utilization looping on a non-existent file descriptor. Thanks to `cknave <https://github.com/cknave>`_ for his work on identifying the issue, proposing a fix, and writing a working test case. - Move the integration tests to use a local docker development environment - Added new methods ``queries.pool.Pool.report`` and ``queries.pool.PoolManager.Report` for reporting pool status. - Added new methods to ``queries.pool.Pool`` for returning a list of busy, closed, executing, and locked connections. 1.10.4 2018-01-10 ----------------- - Added new methods ``queries.pool.Pool.report`` and ``queries.pool.PoolManager.Report`` for reporting pool status. - Added new methods to ``queries.pool.Pool`` for returning a list of busy, closed, executing, and locked connections. 1.10.4 2018-01-10 ----------------- - Implement ``Results.__bool__`` to be explicit about Python 3 support. - Catch any exception raised when using TornadoSession and invoking the execute function in psycopg2 for exceptions raised prior to sending the query to Postgres. This could be psycopg2.Error, IndexError, KeyError, or who knows, it's not documented in psycopg2. 1.10.3 2017-11-01 ----------------- - Remove the functionality from ``TornadoSession.validate`` and make it raise a ``DeprecationWarning`` - Catch the ``KeyError`` raised when ``PoolManager.clean()`` is invoked for a pool that doesn't exist 1.10.2 2017-10-26 ----------------- - Ensure the pool exists when executing a query in TornadoSession, the new timeout behavior prevented that from happening. 1.10.1 2017-10-24 ----------------- - Use an absolute time in the call to ``add_timeout`` 1.10.0 2017-09-27 ----------------- - Free when tornado_session.Result is ``__del__``'d without ``free`` being called. - Auto-clean the pool after Results.free TTL+1 in tornado_session.TornadoSession - Don't raise NotImplementedError in Results.free for synchronous use, just treat as a noop 1.9.1 2016-10-25 ---------------- - Add better exception handling around connections and getting the logged in user 1.9.0 2016-07-01 ---------------- - Handle a potential race condition in TornadoSession when too many simultaneous new connections are made and a pool fills up - Increase logging in various places to be more informative - Restructure queries specific exceptions to all extend off of a base QueriesException - Trivial code cleanup 1.8.10 2016-06-14 ----------------- - Propagate PoolManager exceptions from TornadoSession (#20) - Fix by Dave Shawley 1.8.9 2015-11-11 ---------------- - Move to psycopg2cffi for PyPy support 1.7.5 2015-09-03 ---------------- - Don't let Session and TornadoSession share connections 1.7.1 2015-03-25 ---------------- - Fix TornadoSession's use of cleanup (#8) - Fix by Oren Itamar 1.7.0 2015-01-13 ---------------- - Implement :py:meth:`Pool.shutdown <queries.pool.Pool.shutdown>` and :py:meth:`PoolManager.shutdown <queries.pool.PoolManager.shutdown>` to cleanly shutdown all open, non-executing connections across a Pool or all pools. Update locks in Pool operations to ensure atomicity. 1.6.1 2015-01-09 ---------------- - Fixes an iteration error when closing a pool (#7) - Fix by Chris McGuire 1.6.0 2014-11-20 ----------------- - Handle URI encoded password values properly 1.5.0 2014-10-07 ---------------- - Handle empty query results in the iterator (#4) - Fix by Den Teresh 1.4.0 2014-09-04 ---------------- - Address exception handling in tornado_session <MSG> Fix version history formatting <DFF> @@ -4,16 +4,10 @@ Version History 2.0.0 2018-01-29 ----------------- - REMOVED support for Python 2.6 - - FIXED CPU Pegging bug: Cleanup IOLoop and internal stack in ``TornadoSession`` - on connection error. In the case of a connection error, the failure to do this - caused CPU to peg @ 100% utilization looping on a non-existent file descriptor. - Thanks to `cknave <https://github.com/cknave>`_ for his work on identifying the - issue, proposing a fix, and writing a working test case. + - FIXED CPU Pegging bug: Cleanup IOLoop and internal stack in ``TornadoSession`` on connection error. In the case of a connection error, the failure to do this caused CPU to peg @ 100% utilization looping on a non-existent file descriptor. Thanks to `cknave <https://github.com/cknave>`_ for his work on identifying the issue, proposing a fix, and writing a working test case. - Move the integration tests to use a local docker development environment - - Added new methods ``queries.pool.Pool.report`` and - ``queries.pool.PoolManager.Report` for reporting pool status. - - Added new methods to ``queries.pool.Pool`` for returning a list of - busy, closed, executing, and locked connections. + - Added new methods ``queries.pool.Pool.report`` and ``queries.pool.PoolManager.Report`` for reporting pool status. + - Added new methods to ``queries.pool.Pool`` for returning a list of busy, closed, executing, and locked connections. 1.10.4 2018-01-10 -----------------
3
Fix version history formatting
9
.rst
rst
bsd-3-clause
gmr/queries
1630
<NME> history.rst <BEF> Version History =============== 2.0.0 2018-01-29 ----------------- - REMOVED support for Python 2.6 - FIXED CPU Pegging bug: Cleanup IOLoop and internal stack in ``TornadoSession`` on connection error. In the case of a connection error, the failure to do this caused CPU to peg @ 100% utilization looping on a non-existent file descriptor. Thanks to `cknave <https://github.com/cknave>`_ for his work on identifying the issue, proposing a fix, and writing a working test case. - Move the integration tests to use a local docker development environment - Added new methods ``queries.pool.Pool.report`` and ``queries.pool.PoolManager.Report` for reporting pool status. - Added new methods to ``queries.pool.Pool`` for returning a list of busy, closed, executing, and locked connections. 1.10.4 2018-01-10 ----------------- - Added new methods ``queries.pool.Pool.report`` and ``queries.pool.PoolManager.Report`` for reporting pool status. - Added new methods to ``queries.pool.Pool`` for returning a list of busy, closed, executing, and locked connections. 1.10.4 2018-01-10 ----------------- - Implement ``Results.__bool__`` to be explicit about Python 3 support. - Catch any exception raised when using TornadoSession and invoking the execute function in psycopg2 for exceptions raised prior to sending the query to Postgres. This could be psycopg2.Error, IndexError, KeyError, or who knows, it's not documented in psycopg2. 1.10.3 2017-11-01 ----------------- - Remove the functionality from ``TornadoSession.validate`` and make it raise a ``DeprecationWarning`` - Catch the ``KeyError`` raised when ``PoolManager.clean()`` is invoked for a pool that doesn't exist 1.10.2 2017-10-26 ----------------- - Ensure the pool exists when executing a query in TornadoSession, the new timeout behavior prevented that from happening. 1.10.1 2017-10-24 ----------------- - Use an absolute time in the call to ``add_timeout`` 1.10.0 2017-09-27 ----------------- - Free when tornado_session.Result is ``__del__``'d without ``free`` being called. - Auto-clean the pool after Results.free TTL+1 in tornado_session.TornadoSession - Don't raise NotImplementedError in Results.free for synchronous use, just treat as a noop 1.9.1 2016-10-25 ---------------- - Add better exception handling around connections and getting the logged in user 1.9.0 2016-07-01 ---------------- - Handle a potential race condition in TornadoSession when too many simultaneous new connections are made and a pool fills up - Increase logging in various places to be more informative - Restructure queries specific exceptions to all extend off of a base QueriesException - Trivial code cleanup 1.8.10 2016-06-14 ----------------- - Propagate PoolManager exceptions from TornadoSession (#20) - Fix by Dave Shawley 1.8.9 2015-11-11 ---------------- - Move to psycopg2cffi for PyPy support 1.7.5 2015-09-03 ---------------- - Don't let Session and TornadoSession share connections 1.7.1 2015-03-25 ---------------- - Fix TornadoSession's use of cleanup (#8) - Fix by Oren Itamar 1.7.0 2015-01-13 ---------------- - Implement :py:meth:`Pool.shutdown <queries.pool.Pool.shutdown>` and :py:meth:`PoolManager.shutdown <queries.pool.PoolManager.shutdown>` to cleanly shutdown all open, non-executing connections across a Pool or all pools. Update locks in Pool operations to ensure atomicity. 1.6.1 2015-01-09 ---------------- - Fixes an iteration error when closing a pool (#7) - Fix by Chris McGuire 1.6.0 2014-11-20 ----------------- - Handle URI encoded password values properly 1.5.0 2014-10-07 ---------------- - Handle empty query results in the iterator (#4) - Fix by Den Teresh 1.4.0 2014-09-04 ---------------- - Address exception handling in tornado_session <MSG> Fix version history formatting <DFF> @@ -4,16 +4,10 @@ Version History 2.0.0 2018-01-29 ----------------- - REMOVED support for Python 2.6 - - FIXED CPU Pegging bug: Cleanup IOLoop and internal stack in ``TornadoSession`` - on connection error. In the case of a connection error, the failure to do this - caused CPU to peg @ 100% utilization looping on a non-existent file descriptor. - Thanks to `cknave <https://github.com/cknave>`_ for his work on identifying the - issue, proposing a fix, and writing a working test case. + - FIXED CPU Pegging bug: Cleanup IOLoop and internal stack in ``TornadoSession`` on connection error. In the case of a connection error, the failure to do this caused CPU to peg @ 100% utilization looping on a non-existent file descriptor. Thanks to `cknave <https://github.com/cknave>`_ for his work on identifying the issue, proposing a fix, and writing a working test case. - Move the integration tests to use a local docker development environment - - Added new methods ``queries.pool.Pool.report`` and - ``queries.pool.PoolManager.Report` for reporting pool status. - - Added new methods to ``queries.pool.Pool`` for returning a list of - busy, closed, executing, and locked connections. + - Added new methods ``queries.pool.Pool.report`` and ``queries.pool.PoolManager.Report`` for reporting pool status. + - Added new methods to ``queries.pool.Pool`` for returning a list of busy, closed, executing, and locked connections. 1.10.4 2018-01-10 -----------------
3
Fix version history formatting
9
.rst
rst
bsd-3-clause
gmr/queries
1631
<NME> pool.py <BEF> """ Connection Pooling """ import datetime import logging import os import threading import time import weakref import psycopg2 LOGGER = logging.getLogger(__name__) DEFAULT_IDLE_TTL = 60 DEFAULT_MAX_SIZE = int(os.environ.get('QUERIES_MAX_POOL_SIZE', 1)) class Connection(object): """Contains the handle to the connection, the current state of the connection and methods for manipulating the state of the connection. """ _lock = threading.Lock() def __init__(self, handle): self.handle = handle self.used_by = None self.executions = 0 self.exceptions = 0 def close(self): """Close the connection :raises: ConnectionBusyError """ LOGGER.debug('Connection %s closing', self.id) if self.busy and not self.closed: raise ConnectionBusyError(self) with self._lock: if not self.handle.closed: try: self.handle.close() except psycopg2.InterfaceError as error: LOGGER.error('Error closing socket: %s', error) @property def closed(self): """Return if the psycopg2 connection is closed. :rtype: bool """ return self.handle.closed @property def busy(self): """Return if the connection is currently executing a query or is locked by a session that still exists. :rtype: bool """ if self.handle.isexecuting(): return True elif self.used_by is None: return False return not self.used_by() is None @property def executing(self): """Return if the connection is currently executing a query :rtype: bool """ return self.handle.isexecuting() def free(self): """Remove the lock on the connection if the connection is not active :raises: ConnectionBusyError """ LOGGER.debug('Connection %s freeing', self.id) if self.handle.isexecuting(): raise ConnectionBusyError(self) with self._lock: self.used_by = None LOGGER.debug('Connection %s freed', self.id) @property def id(self): """Return id of the psycopg2 connection object :rtype: int """ return id(self.handle) def lock(self, session): """Lock the connection, ensuring that it is not busy and storing a weakref for the session. :param queries.Session session: The session to lock the connection with :raises: ConnectionBusyError """ if self.busy: raise ConnectionBusyError(self) with self._lock: self.used_by = weakref.ref(session) LOGGER.debug('Connection %s locked', self.id) @property def locked(self): """Return if the connection is currently exclusively locked :rtype: bool """ return self.used_by is not None class Pool(object): """A connection pool for gaining access to and managing connections""" _lock = threading.Lock() idle_start = None idle_ttl = DEFAULT_IDLE_TTL max_size = DEFAULT_MAX_SIZE def __init__(self, pool_id, idle_ttl=DEFAULT_IDLE_TTL, max_size=DEFAULT_MAX_SIZE, time_method=None): self.connections = {} self._id = pool_id self.idle_ttl = idle_ttl self.max_size = max_size self.time_method = time_method or time.time def __contains__(self, connection): """Return True if the pool contains the connection""" return id(connection) in self.connections def __len__(self): """Return the number of connections in the pool""" return len(self.connections) def add(self, connection): """Add a new connection to the pool :param connection: The connection to add to the pool :type connection: psycopg2.extensions.connection :raises: PoolFullError """ if id(connection) in self.connections: raise ValueError('Connection already exists in pool') if len(self.connections) == self.max_size: LOGGER.warning('Race condition found when adding new connection') try: connection.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.error('Error closing the conn that cant be used: %s', error) raise PoolFullError(self) with self._lock: self.connections[id(connection)] = Connection(connection) LOGGER.debug('Pool %s added connection %s', self.id, id(connection)) @property def busy_connections(self): """Return a list of active/busy connections :rtype: list """ return [c for c in self.connections if c.busy and not c.closed] def clean(self): """Clean the pool by removing any closed connections and if the pool's idle has exceeded its idle TTL, remove all connections. """ LOGGER.debug('Cleaning the pool') for connection in [self.connections[k] for k in self.connections if self.connections[k].closed]: LOGGER.debug('Removing %s', connection.id) self.remove(connection.handle) if self.idle_duration > self.idle_ttl: self.close() LOGGER.debug('Pool %s cleaned', self.id) def close(self): """Close the pool by closing and removing all of the connections""" for cid in list(self.connections.keys()): self.remove(self.connections[cid].handle) LOGGER.debug('Pool %s closed', self.id) @property def closed_connections(self): """Return a list of closed connections :rtype: list """ return [c for c in self.connections.values() if c.closed] def connection_handle(self, connection): """Return a connection object for the given psycopg2 connection :param connection: The connection to return a parent for :type connection: psycopg2.extensions.connection :rtype: Connection """ return self.connections[id(connection)] @property def executing_connections(self): """Return a list of connections actively executing queries :rtype: list """ return [c for c in self.connections if c.executing] def free(self, connection): """Free the connection from use by the session that was using it. :param connection: The connection to free :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError """ LOGGER.debug('Pool %s freeing connection %s', self.id, id(connection)) try: self.connection_handle(connection).free() except KeyError: raise ConnectionNotFoundError(self.id, id(connection)) if self.idle_connections == list(self.connections.values()): with self._lock: self.idle_start = self.time_method() LOGGER.debug('Pool %s freed connection %s', self.id, id(connection)) def get(self, session): """Return an idle connection and assign the session to the connection :param queries.Session session: The session to assign :rtype: psycopg2.extensions.connection :raises: NoIdleConnectionsError """ idle = self.idle_connections if idle: connection = idle.pop(0) connection.lock(session) if self.idle_start: with self._lock: self.idle_start = None return connection.handle raise NoIdleConnectionsError(self.id) @property def id(self): """Return the ID for this pool :rtype: str """ return self._id @property def idle_connections(self): """Return a list of idle connections :rtype: list """ return [c for c in self.connections.values() if not c.busy and not c.closed] @property def idle_duration(self): """Return the number of seconds that the pool has had no active connections. :rtype: float """ if self.idle_start is None: return 0 return self.time_method() - self.idle_start @property def is_full(self): """Return True if there are no more open slots for connections. :rtype: bool """ return len(self.connections) >= self.max_size def lock(self, connection, session): """Explicitly lock the specified connection :type connection: psycopg2.extensions.connection :param connection: The connection to lock :param queries.Session session: The session to hold the lock """ cid = id(connection) try: self.connection_handle(connection).lock(session) except KeyError: raise ConnectionNotFoundError(self.id, cid) else: if self.idle_start: with self._lock: self.idle_start = None LOGGER.debug('Pool %s locked connection %s', self.id, cid) @property def locked_connections(self): """Return a list of all locked connections :rtype: list """ return [c for c in self.connections.values() if c.locked] def remove(self, connection): """Remove the connection from the pool :param connection: The connection to remove :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError :raises: ConnectionBusyError """ cid = id(connection) if cid not in self.connections: raise ConnectionNotFoundError(self.id, cid) self.connection_handle(connection).close() with self._lock: del self.connections[cid] LOGGER.debug('Pool %s removed connection %s', self.id, cid) def report(self): """Return a report about the pool state and configuration. :rtype: dict """ return { 'connections': { 'busy': len(self.busy_connections), 'closed': len(self.closed_connections), 'executing': len([c for c in self.connections if c.executing()]), 'idle': len(self.idle_connections), 'locked': len(self.busy_connections) }, 'exceptions': sum([c.exceptions for c in self.connections.values()]), 'executions': sum([c.executed for c in self.connections.values()]), 'full': self.is_full, 'idle': { 'duration': self.idle_duration, 'ttl': self.idle_ttl }, 'max_size': self.max_size } def shutdown(self): """Forcefully shutdown the entire pool, closing all non-executing connections. :raises: ConnectionBusyError """ with self._lock: for cid in list(self.connections.keys()): if self.connections[cid].executing: raise ConnectionBusyError(cid) if self.connections[cid].locked: self.connections[cid].free() self.connections[cid].close() del self.connections[cid] def set_idle_ttl(self, ttl): """Set the idle ttl :param int ttl: The TTL when idle """ with self._lock: self.idle_ttl = ttl def set_max_size(self, size): """Set the maximum number of connections :param int size: The maximum number of connections """ with self._lock: self.max_size = size class PoolManager(object): """The connection pool object implements behavior around connections and their use in queries.Session objects. We carry a pool id instead of the connection URI so that we will not be carrying the URI in memory, creating a possible security issue. """ _lock = threading.Lock() _pools = {} def __contains__(self, pid): """Returns True if the pool exists :param str pid: The pool id to check for :rtype: bool """ return pid in self.__class__._pools @classmethod def instance(cls): """Only allow a single PoolManager instance to exist, returning the handle for it. :rtype: PoolManager """ if not hasattr(cls, '_instance'): with cls._lock: cls._instance = cls() return cls._instance @classmethod def add(cls, pid, connection): """Add a new connection and session to a pool. :param str pid: The pool id :type connection: psycopg2.extensions.connection :param connection: The connection to add to the pool """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].add(connection) @classmethod def clean(cls, pid): """Clean the specified pool, removing any closed connections or stale locks. :param str pid: The pool id to clean """ with cls._lock: try: cls._ensure_pool_exists(pid) except KeyError: LOGGER.debug('Pool clean invoked against missing pool %s', pid) return cls._pools[pid].clean() cls._maybe_remove_pool(pid) @classmethod def create(cls, pid, idle_ttl=DEFAULT_IDLE_TTL, max_size=DEFAULT_MAX_SIZE, time_method=None): """Create a new pool, with the ability to pass in values to override the default idle TTL and the default maximum size. A pool's idle TTL defines the amount of time that a pool can be open without any sessions before it is removed. A pool's max size defines the maximum number of connections that can be added to the pool to prevent unbounded open connections. :param str pid: The pool ID :param int idle_ttl: Time in seconds for the idle TTL :param int max_size: The maximum pool size :param callable time_method: Override the use of :py:meth:`time.time` method for time values. :raises: KeyError """ if pid in cls._pools: raise KeyError('Pool %s already exists' % pid) with cls._lock: LOGGER.debug("Creating Pool: %s (%i/%i)", pid, idle_ttl, max_size) cls._pools[pid] = Pool(pid, idle_ttl, max_size, time_method) @classmethod def free(cls, pid, connection): """Free a connection that was locked by a session :param str pid: The pool ID :param connection: The connection to remove :type connection: psycopg2.extensions.connection """ with cls._lock: LOGGER.debug('Freeing %s from pool %s', id(connection), pid) cls._ensure_pool_exists(pid) cls._pools[pid].free(connection) @classmethod def get(cls, pid, session): """Get an idle, unused connection from the pool. Once a connection has been retrieved, it will be marked as in-use until it is freed. :param str pid: The pool ID :param queries.Session session: The session to assign to the connection :rtype: psycopg2.extensions.connection """ with cls._lock: cls._ensure_pool_exists(pid) return cls._pools[pid].get(session) @classmethod def get_connection(cls, pid, connection): """Return the specified :class:`~queries.pool.Connection` from the pool. :param str pid: The pool ID :param connection: The connection to return for :type connection: psycopg2.extensions.connection :rtype: queries.pool.Connection """ with cls._lock: return cls._pools[pid].connection_handle(connection) @classmethod def has_connection(cls, pid, connection): """Check to see if a pool has the specified connection :param str pid: The pool ID :param connection: The connection to check for :type connection: psycopg2.extensions.connection :rtype: bool """ with cls._lock: cls._ensure_pool_exists(pid) return connection in cls._pools[pid] @classmethod def has_idle_connection(cls, pid): """Check to see if a pool has an idle connection :param str pid: The pool ID :rtype: bool """ with cls._lock: cls._ensure_pool_exists(pid) return bool(cls._pools[pid].idle_connections) @classmethod def is_full(cls, pid): """Return a bool indicating if the specified pool is full :param str pid: The pool id :rtype: bool """ with cls._lock: cls._ensure_pool_exists(pid) return cls._pools[pid].is_full @classmethod def lock(cls, pid, connection, session): """Explicitly lock the specified connection in the pool :param str pid: The pool id :type connection: psycopg2.extensions.connection :param connection: The connection to add to the pool :param queries.Session session: The session to hold the lock """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].lock(connection, session) @classmethod def remove(cls, pid): """Remove a pool, closing all connections :param str pid: The pool ID """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].close() del cls._pools[pid] @classmethod def remove_connection(cls, pid, connection): """Remove a connection from the pool, closing it if is open. :param str pid: The pool ID :param connection: The connection to remove :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError """ cls._ensure_pool_exists(pid) cls._pools[pid].remove(connection) @classmethod def set_idle_ttl(cls, pid, ttl): """Set the idle TTL for a pool, after which it will be destroyed. :param str pid: The pool id :param int ttl: The TTL for an idle pool """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].set_idle_ttl(ttl) @classmethod def set_max_size(cls, pid, size): """Set the maximum number of connections for the specified pool :param str pid: The pool to set the size for :param int size: The maximum number of connections """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].set_max_size(size) @classmethod def shutdown(cls): """Close all connections on in all pools""" for pid in list(cls._pools.keys()): cls._pools[pid].shutdown() LOGGER.info('Shutdown complete, all pooled connections closed') @classmethod def size(cls, pid): """Return the number of connections in the pool :param str pid: The pool id :rtype int """ with cls._lock: cls._ensure_pool_exists(pid) return len(cls._pools[pid]) @classmethod def report(cls): """Return the state of the all of the registered pools. :rtype: dict """ return { 'timestamp': datetime.datetime.utcnow().isoformat(), 'process': os.getpid(), 'pools': dict([(i, p.report()) for i, p in cls._pools.items()]) } @classmethod def _ensure_pool_exists(cls, pid): """Raise an exception if the pool has yet to be created or has been removed. :param str pid: The pool ID to check for :raises: KeyError """ if pid not in cls._pools: raise KeyError('Pool %s has not been created' % pid) @classmethod def _maybe_remove_pool(cls, pid): """If the pool has no open connections, remove it :param str pid: The pool id to clean """ if not len(cls._pools[pid]): del cls._pools[pid] class QueriesException(Exception): """Base Exception for all other Queries exceptions""" pass class ConnectionException(QueriesException): def __init__(self, cid): self.cid = cid class PoolException(QueriesException): def __init__(self, pid): self.pid = pid class PoolConnectionException(PoolException): def __init__(self, pid, cid): self.pid = pid self.cid = cid class ActivePoolError(PoolException): """Raised when removing a pool that has active connections""" def __str__(self): return 'Pool %s has at least one active connection' % self.pid class ConnectionBusyError(ConnectionException): """Raised when trying to lock a connection that is already busy""" def __str__(self): return 'Connection %s is busy' % self.cid class ConnectionNotFoundError(PoolConnectionException): """Raised if a specific connection is not found in the pool""" def __str__(self): return 'Connection %s not found in pool %s' % (self.cid, self.pid) class NoIdleConnectionsError(PoolException): """Raised if a pool does not have any idle, open connections""" def __str__(self): return 'Pool %s has no idle connections' % self.pid class PoolFullError(PoolException): """Raised when adding a connection to a pool that has hit max-size""" def __str__(self): return 'Pool %s is at its maximum capacity' % self.pid <MSG> Fix property iterators <DFF> @@ -53,7 +53,7 @@ class Connection(object): :rtype: bool """ - return self.handle.closed + return self.handle.closed != 0 @property def busy(self): @@ -181,7 +181,8 @@ class Pool(object): :rtype: list """ - return [c for c in self.connections if c.busy and not c.closed] + return [c for c in self.connections.values() + if c.busy and not c.closed] def clean(self): """Clean the pool by removing any closed connections and if the pool's @@ -231,7 +232,7 @@ class Pool(object): :rtype: list """ - return [c for c in self.connections if c.executing] + return [c for c in self.connections.values() if c.executing] def free(self, connection): """Free the connection from use by the session that was using it. @@ -365,14 +366,13 @@ class Pool(object): 'connections': { 'busy': len(self.busy_connections), 'closed': len(self.closed_connections), - 'executing': len([c for c in self.connections - if c.executing()]), + 'executing': len(self.executing_connections), 'idle': len(self.idle_connections), 'locked': len(self.busy_connections) }, 'exceptions': sum([c.exceptions for c in self.connections.values()]), - 'executions': sum([c.executed + 'executions': sum([c.executions for c in self.connections.values()]), 'full': self.is_full, 'idle': {
6
Fix property iterators
6
.py
py
bsd-3-clause
gmr/queries
1632
<NME> pool.py <BEF> """ Connection Pooling """ import datetime import logging import os import threading import time import weakref import psycopg2 LOGGER = logging.getLogger(__name__) DEFAULT_IDLE_TTL = 60 DEFAULT_MAX_SIZE = int(os.environ.get('QUERIES_MAX_POOL_SIZE', 1)) class Connection(object): """Contains the handle to the connection, the current state of the connection and methods for manipulating the state of the connection. """ _lock = threading.Lock() def __init__(self, handle): self.handle = handle self.used_by = None self.executions = 0 self.exceptions = 0 def close(self): """Close the connection :raises: ConnectionBusyError """ LOGGER.debug('Connection %s closing', self.id) if self.busy and not self.closed: raise ConnectionBusyError(self) with self._lock: if not self.handle.closed: try: self.handle.close() except psycopg2.InterfaceError as error: LOGGER.error('Error closing socket: %s', error) @property def closed(self): """Return if the psycopg2 connection is closed. :rtype: bool """ return self.handle.closed @property def busy(self): """Return if the connection is currently executing a query or is locked by a session that still exists. :rtype: bool """ if self.handle.isexecuting(): return True elif self.used_by is None: return False return not self.used_by() is None @property def executing(self): """Return if the connection is currently executing a query :rtype: bool """ return self.handle.isexecuting() def free(self): """Remove the lock on the connection if the connection is not active :raises: ConnectionBusyError """ LOGGER.debug('Connection %s freeing', self.id) if self.handle.isexecuting(): raise ConnectionBusyError(self) with self._lock: self.used_by = None LOGGER.debug('Connection %s freed', self.id) @property def id(self): """Return id of the psycopg2 connection object :rtype: int """ return id(self.handle) def lock(self, session): """Lock the connection, ensuring that it is not busy and storing a weakref for the session. :param queries.Session session: The session to lock the connection with :raises: ConnectionBusyError """ if self.busy: raise ConnectionBusyError(self) with self._lock: self.used_by = weakref.ref(session) LOGGER.debug('Connection %s locked', self.id) @property def locked(self): """Return if the connection is currently exclusively locked :rtype: bool """ return self.used_by is not None class Pool(object): """A connection pool for gaining access to and managing connections""" _lock = threading.Lock() idle_start = None idle_ttl = DEFAULT_IDLE_TTL max_size = DEFAULT_MAX_SIZE def __init__(self, pool_id, idle_ttl=DEFAULT_IDLE_TTL, max_size=DEFAULT_MAX_SIZE, time_method=None): self.connections = {} self._id = pool_id self.idle_ttl = idle_ttl self.max_size = max_size self.time_method = time_method or time.time def __contains__(self, connection): """Return True if the pool contains the connection""" return id(connection) in self.connections def __len__(self): """Return the number of connections in the pool""" return len(self.connections) def add(self, connection): """Add a new connection to the pool :param connection: The connection to add to the pool :type connection: psycopg2.extensions.connection :raises: PoolFullError """ if id(connection) in self.connections: raise ValueError('Connection already exists in pool') if len(self.connections) == self.max_size: LOGGER.warning('Race condition found when adding new connection') try: connection.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.error('Error closing the conn that cant be used: %s', error) raise PoolFullError(self) with self._lock: self.connections[id(connection)] = Connection(connection) LOGGER.debug('Pool %s added connection %s', self.id, id(connection)) @property def busy_connections(self): """Return a list of active/busy connections :rtype: list """ return [c for c in self.connections if c.busy and not c.closed] def clean(self): """Clean the pool by removing any closed connections and if the pool's idle has exceeded its idle TTL, remove all connections. """ LOGGER.debug('Cleaning the pool') for connection in [self.connections[k] for k in self.connections if self.connections[k].closed]: LOGGER.debug('Removing %s', connection.id) self.remove(connection.handle) if self.idle_duration > self.idle_ttl: self.close() LOGGER.debug('Pool %s cleaned', self.id) def close(self): """Close the pool by closing and removing all of the connections""" for cid in list(self.connections.keys()): self.remove(self.connections[cid].handle) LOGGER.debug('Pool %s closed', self.id) @property def closed_connections(self): """Return a list of closed connections :rtype: list """ return [c for c in self.connections.values() if c.closed] def connection_handle(self, connection): """Return a connection object for the given psycopg2 connection :param connection: The connection to return a parent for :type connection: psycopg2.extensions.connection :rtype: Connection """ return self.connections[id(connection)] @property def executing_connections(self): """Return a list of connections actively executing queries :rtype: list """ return [c for c in self.connections if c.executing] def free(self, connection): """Free the connection from use by the session that was using it. :param connection: The connection to free :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError """ LOGGER.debug('Pool %s freeing connection %s', self.id, id(connection)) try: self.connection_handle(connection).free() except KeyError: raise ConnectionNotFoundError(self.id, id(connection)) if self.idle_connections == list(self.connections.values()): with self._lock: self.idle_start = self.time_method() LOGGER.debug('Pool %s freed connection %s', self.id, id(connection)) def get(self, session): """Return an idle connection and assign the session to the connection :param queries.Session session: The session to assign :rtype: psycopg2.extensions.connection :raises: NoIdleConnectionsError """ idle = self.idle_connections if idle: connection = idle.pop(0) connection.lock(session) if self.idle_start: with self._lock: self.idle_start = None return connection.handle raise NoIdleConnectionsError(self.id) @property def id(self): """Return the ID for this pool :rtype: str """ return self._id @property def idle_connections(self): """Return a list of idle connections :rtype: list """ return [c for c in self.connections.values() if not c.busy and not c.closed] @property def idle_duration(self): """Return the number of seconds that the pool has had no active connections. :rtype: float """ if self.idle_start is None: return 0 return self.time_method() - self.idle_start @property def is_full(self): """Return True if there are no more open slots for connections. :rtype: bool """ return len(self.connections) >= self.max_size def lock(self, connection, session): """Explicitly lock the specified connection :type connection: psycopg2.extensions.connection :param connection: The connection to lock :param queries.Session session: The session to hold the lock """ cid = id(connection) try: self.connection_handle(connection).lock(session) except KeyError: raise ConnectionNotFoundError(self.id, cid) else: if self.idle_start: with self._lock: self.idle_start = None LOGGER.debug('Pool %s locked connection %s', self.id, cid) @property def locked_connections(self): """Return a list of all locked connections :rtype: list """ return [c for c in self.connections.values() if c.locked] def remove(self, connection): """Remove the connection from the pool :param connection: The connection to remove :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError :raises: ConnectionBusyError """ cid = id(connection) if cid not in self.connections: raise ConnectionNotFoundError(self.id, cid) self.connection_handle(connection).close() with self._lock: del self.connections[cid] LOGGER.debug('Pool %s removed connection %s', self.id, cid) def report(self): """Return a report about the pool state and configuration. :rtype: dict """ return { 'connections': { 'busy': len(self.busy_connections), 'closed': len(self.closed_connections), 'executing': len([c for c in self.connections if c.executing()]), 'idle': len(self.idle_connections), 'locked': len(self.busy_connections) }, 'exceptions': sum([c.exceptions for c in self.connections.values()]), 'executions': sum([c.executed for c in self.connections.values()]), 'full': self.is_full, 'idle': { 'duration': self.idle_duration, 'ttl': self.idle_ttl }, 'max_size': self.max_size } def shutdown(self): """Forcefully shutdown the entire pool, closing all non-executing connections. :raises: ConnectionBusyError """ with self._lock: for cid in list(self.connections.keys()): if self.connections[cid].executing: raise ConnectionBusyError(cid) if self.connections[cid].locked: self.connections[cid].free() self.connections[cid].close() del self.connections[cid] def set_idle_ttl(self, ttl): """Set the idle ttl :param int ttl: The TTL when idle """ with self._lock: self.idle_ttl = ttl def set_max_size(self, size): """Set the maximum number of connections :param int size: The maximum number of connections """ with self._lock: self.max_size = size class PoolManager(object): """The connection pool object implements behavior around connections and their use in queries.Session objects. We carry a pool id instead of the connection URI so that we will not be carrying the URI in memory, creating a possible security issue. """ _lock = threading.Lock() _pools = {} def __contains__(self, pid): """Returns True if the pool exists :param str pid: The pool id to check for :rtype: bool """ return pid in self.__class__._pools @classmethod def instance(cls): """Only allow a single PoolManager instance to exist, returning the handle for it. :rtype: PoolManager """ if not hasattr(cls, '_instance'): with cls._lock: cls._instance = cls() return cls._instance @classmethod def add(cls, pid, connection): """Add a new connection and session to a pool. :param str pid: The pool id :type connection: psycopg2.extensions.connection :param connection: The connection to add to the pool """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].add(connection) @classmethod def clean(cls, pid): """Clean the specified pool, removing any closed connections or stale locks. :param str pid: The pool id to clean """ with cls._lock: try: cls._ensure_pool_exists(pid) except KeyError: LOGGER.debug('Pool clean invoked against missing pool %s', pid) return cls._pools[pid].clean() cls._maybe_remove_pool(pid) @classmethod def create(cls, pid, idle_ttl=DEFAULT_IDLE_TTL, max_size=DEFAULT_MAX_SIZE, time_method=None): """Create a new pool, with the ability to pass in values to override the default idle TTL and the default maximum size. A pool's idle TTL defines the amount of time that a pool can be open without any sessions before it is removed. A pool's max size defines the maximum number of connections that can be added to the pool to prevent unbounded open connections. :param str pid: The pool ID :param int idle_ttl: Time in seconds for the idle TTL :param int max_size: The maximum pool size :param callable time_method: Override the use of :py:meth:`time.time` method for time values. :raises: KeyError """ if pid in cls._pools: raise KeyError('Pool %s already exists' % pid) with cls._lock: LOGGER.debug("Creating Pool: %s (%i/%i)", pid, idle_ttl, max_size) cls._pools[pid] = Pool(pid, idle_ttl, max_size, time_method) @classmethod def free(cls, pid, connection): """Free a connection that was locked by a session :param str pid: The pool ID :param connection: The connection to remove :type connection: psycopg2.extensions.connection """ with cls._lock: LOGGER.debug('Freeing %s from pool %s', id(connection), pid) cls._ensure_pool_exists(pid) cls._pools[pid].free(connection) @classmethod def get(cls, pid, session): """Get an idle, unused connection from the pool. Once a connection has been retrieved, it will be marked as in-use until it is freed. :param str pid: The pool ID :param queries.Session session: The session to assign to the connection :rtype: psycopg2.extensions.connection """ with cls._lock: cls._ensure_pool_exists(pid) return cls._pools[pid].get(session) @classmethod def get_connection(cls, pid, connection): """Return the specified :class:`~queries.pool.Connection` from the pool. :param str pid: The pool ID :param connection: The connection to return for :type connection: psycopg2.extensions.connection :rtype: queries.pool.Connection """ with cls._lock: return cls._pools[pid].connection_handle(connection) @classmethod def has_connection(cls, pid, connection): """Check to see if a pool has the specified connection :param str pid: The pool ID :param connection: The connection to check for :type connection: psycopg2.extensions.connection :rtype: bool """ with cls._lock: cls._ensure_pool_exists(pid) return connection in cls._pools[pid] @classmethod def has_idle_connection(cls, pid): """Check to see if a pool has an idle connection :param str pid: The pool ID :rtype: bool """ with cls._lock: cls._ensure_pool_exists(pid) return bool(cls._pools[pid].idle_connections) @classmethod def is_full(cls, pid): """Return a bool indicating if the specified pool is full :param str pid: The pool id :rtype: bool """ with cls._lock: cls._ensure_pool_exists(pid) return cls._pools[pid].is_full @classmethod def lock(cls, pid, connection, session): """Explicitly lock the specified connection in the pool :param str pid: The pool id :type connection: psycopg2.extensions.connection :param connection: The connection to add to the pool :param queries.Session session: The session to hold the lock """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].lock(connection, session) @classmethod def remove(cls, pid): """Remove a pool, closing all connections :param str pid: The pool ID """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].close() del cls._pools[pid] @classmethod def remove_connection(cls, pid, connection): """Remove a connection from the pool, closing it if is open. :param str pid: The pool ID :param connection: The connection to remove :type connection: psycopg2.extensions.connection :raises: ConnectionNotFoundError """ cls._ensure_pool_exists(pid) cls._pools[pid].remove(connection) @classmethod def set_idle_ttl(cls, pid, ttl): """Set the idle TTL for a pool, after which it will be destroyed. :param str pid: The pool id :param int ttl: The TTL for an idle pool """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].set_idle_ttl(ttl) @classmethod def set_max_size(cls, pid, size): """Set the maximum number of connections for the specified pool :param str pid: The pool to set the size for :param int size: The maximum number of connections """ with cls._lock: cls._ensure_pool_exists(pid) cls._pools[pid].set_max_size(size) @classmethod def shutdown(cls): """Close all connections on in all pools""" for pid in list(cls._pools.keys()): cls._pools[pid].shutdown() LOGGER.info('Shutdown complete, all pooled connections closed') @classmethod def size(cls, pid): """Return the number of connections in the pool :param str pid: The pool id :rtype int """ with cls._lock: cls._ensure_pool_exists(pid) return len(cls._pools[pid]) @classmethod def report(cls): """Return the state of the all of the registered pools. :rtype: dict """ return { 'timestamp': datetime.datetime.utcnow().isoformat(), 'process': os.getpid(), 'pools': dict([(i, p.report()) for i, p in cls._pools.items()]) } @classmethod def _ensure_pool_exists(cls, pid): """Raise an exception if the pool has yet to be created or has been removed. :param str pid: The pool ID to check for :raises: KeyError """ if pid not in cls._pools: raise KeyError('Pool %s has not been created' % pid) @classmethod def _maybe_remove_pool(cls, pid): """If the pool has no open connections, remove it :param str pid: The pool id to clean """ if not len(cls._pools[pid]): del cls._pools[pid] class QueriesException(Exception): """Base Exception for all other Queries exceptions""" pass class ConnectionException(QueriesException): def __init__(self, cid): self.cid = cid class PoolException(QueriesException): def __init__(self, pid): self.pid = pid class PoolConnectionException(PoolException): def __init__(self, pid, cid): self.pid = pid self.cid = cid class ActivePoolError(PoolException): """Raised when removing a pool that has active connections""" def __str__(self): return 'Pool %s has at least one active connection' % self.pid class ConnectionBusyError(ConnectionException): """Raised when trying to lock a connection that is already busy""" def __str__(self): return 'Connection %s is busy' % self.cid class ConnectionNotFoundError(PoolConnectionException): """Raised if a specific connection is not found in the pool""" def __str__(self): return 'Connection %s not found in pool %s' % (self.cid, self.pid) class NoIdleConnectionsError(PoolException): """Raised if a pool does not have any idle, open connections""" def __str__(self): return 'Pool %s has no idle connections' % self.pid class PoolFullError(PoolException): """Raised when adding a connection to a pool that has hit max-size""" def __str__(self): return 'Pool %s is at its maximum capacity' % self.pid <MSG> Fix property iterators <DFF> @@ -53,7 +53,7 @@ class Connection(object): :rtype: bool """ - return self.handle.closed + return self.handle.closed != 0 @property def busy(self): @@ -181,7 +181,8 @@ class Pool(object): :rtype: list """ - return [c for c in self.connections if c.busy and not c.closed] + return [c for c in self.connections.values() + if c.busy and not c.closed] def clean(self): """Clean the pool by removing any closed connections and if the pool's @@ -231,7 +232,7 @@ class Pool(object): :rtype: list """ - return [c for c in self.connections if c.executing] + return [c for c in self.connections.values() if c.executing] def free(self, connection): """Free the connection from use by the session that was using it. @@ -365,14 +366,13 @@ class Pool(object): 'connections': { 'busy': len(self.busy_connections), 'closed': len(self.closed_connections), - 'executing': len([c for c in self.connections - if c.executing()]), + 'executing': len(self.executing_connections), 'idle': len(self.idle_connections), 'locked': len(self.busy_connections) }, 'exceptions': sum([c.exceptions for c in self.connections.values()]), - 'executions': sum([c.executed + 'executions': sum([c.executions for c in self.connections.values()]), 'full': self.is_full, 'idle': {
6
Fix property iterators
6
.py
py
bsd-3-clause
gmr/queries
1633
<NME> .travis.yml <BEF> sudo: false language: python dist: xenial env: global: - PATH=$HOME/.local/bin:$PATH - AWS_DEFAULT_REGION=us-east-1 - secure: "inURdx4ldkJqQXL1TyvKImC3EnL5TixC1DlNMBYi5ttygwAk+mSSSw8Yc7klB6D1m6q79xUlHRk06vbz23CsXTM4AClC5Emrk6XN2GlUKl5WI+z+A2skI59buEhLWe7e2KzhB/AVx2E3TfKa0oY7raM0UUnaOkpV1Cj+mHKPIT0=" - secure: "H32DV3713a6UUuEJujrG7SfUX4/5WrwQy/3DxeptC6L7YPlTYxHBdEsccTfN5z806EheIl4BdIoxoDtq7PU/tWQoG1Lp2ze60mpwrniHajhFnjk7zP6pHvkhGLr8flhSmAb6CQBreNFOHTLWBMGPfi7k1Q9Td9MHbRo/FsTxqsM=" stages: - test - name: coverage - name: deploy if: tag IS present services: - postgresql install: - pip install awscli - pip install -r requires/testing.txt - python setup.py develop script: nosetests user: crad password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= - python: 3.7 - python: 3.8 - stage: coverage if: repo = gmr/queries services: [] python: 3.7 install: - pip install awscli coverage codecov script: - mkdir coverage - aws s3 cp --recursive s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/ coverage - cd coverage - coverage combine - cd .. - mv coverage/.coverage . - coverage report after_success: codecov - stage: deploy if: repo = gmr/queries python: 3.6 services: [] install: true script: true after_success: true deploy: distributions: sdist bdist_wheel provider: pypi user: crad on: tags: true all_branches: true password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= <MSG> Update the travis notification webhooks for gitter <DFF> @@ -27,3 +27,10 @@ deploy: user: crad password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= +notifications: + webhooks: + urls: + - https://webhooks.gitter.im/e/d96fcd17db66e06d833d + on_success: always + on_failure: always + on_start: always
7
Update the travis notification webhooks for gitter
0
.yml
travis
bsd-3-clause
gmr/queries
1634
<NME> .travis.yml <BEF> sudo: false language: python dist: xenial env: global: - PATH=$HOME/.local/bin:$PATH - AWS_DEFAULT_REGION=us-east-1 - secure: "inURdx4ldkJqQXL1TyvKImC3EnL5TixC1DlNMBYi5ttygwAk+mSSSw8Yc7klB6D1m6q79xUlHRk06vbz23CsXTM4AClC5Emrk6XN2GlUKl5WI+z+A2skI59buEhLWe7e2KzhB/AVx2E3TfKa0oY7raM0UUnaOkpV1Cj+mHKPIT0=" - secure: "H32DV3713a6UUuEJujrG7SfUX4/5WrwQy/3DxeptC6L7YPlTYxHBdEsccTfN5z806EheIl4BdIoxoDtq7PU/tWQoG1Lp2ze60mpwrniHajhFnjk7zP6pHvkhGLr8flhSmAb6CQBreNFOHTLWBMGPfi7k1Q9Td9MHbRo/FsTxqsM=" stages: - test - name: coverage - name: deploy if: tag IS present services: - postgresql install: - pip install awscli - pip install -r requires/testing.txt - python setup.py develop script: nosetests user: crad password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= - python: 3.7 - python: 3.8 - stage: coverage if: repo = gmr/queries services: [] python: 3.7 install: - pip install awscli coverage codecov script: - mkdir coverage - aws s3 cp --recursive s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/ coverage - cd coverage - coverage combine - cd .. - mv coverage/.coverage . - coverage report after_success: codecov - stage: deploy if: repo = gmr/queries python: 3.6 services: [] install: true script: true after_success: true deploy: distributions: sdist bdist_wheel provider: pypi user: crad on: tags: true all_branches: true password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= <MSG> Update the travis notification webhooks for gitter <DFF> @@ -27,3 +27,10 @@ deploy: user: crad password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= +notifications: + webhooks: + urls: + - https://webhooks.gitter.im/e/d96fcd17db66e06d833d + on_success: always + on_failure: always + on_start: always
7
Update the travis notification webhooks for gitter
0
.yml
travis
bsd-3-clause
gmr/queries
1635
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<3'] else: install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setuptools.setup( name='queries', version='2.1.0', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy', maintainer_email='[email protected]', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Topic :: Software Development :: Libraries'] setup(name='queries', version='1.7.1', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]", 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Bump the rev <DFF> @@ -30,7 +30,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.7.1', + version='1.7.2', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]",
1
Bump the rev
1
.py
py
bsd-3-clause
gmr/queries
1636
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<3'] else: install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setuptools.setup( name='queries', version='2.1.0', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy', maintainer_email='[email protected]', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Topic :: Software Development :: Libraries'] setup(name='queries', version='1.7.1', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]", 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Bump the rev <DFF> @@ -30,7 +30,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.7.1', + version='1.7.2', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]",
1
Bump the rev
1
.py
py
bsd-3-clause
gmr/queries
1637
<NME> tornado_session.py <BEF> """ Tornado Session Adapter Use Queries asynchronously within the Tornado framework. Example Use: .. code:: python class NameListHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession(pool_max_size=60) @gen.coroutine def get(self): data = yield self.session.query('SELECT * FROM names') if data: self.finish({'names': data.items()}) data.free() else: self.set_status(500, 'Error querying the data') """ import logging import socket import warnings from tornado import concurrent, ioloop from psycopg2 import extras, extensions import psycopg2 from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) DEFAULT_MAX_POOL_SIZE = 25 class Results(results.Results): """A TornadoSession specific :py:class:`queries.Results` class that adds the :py:meth:`Results.free <queries.tornado_session.Results.free>` method. The :py:meth:`Results.free <queries.tornado_session.Results.free>` method **must** be called to free the connection that the results were generated on. `Results` objects that are not freed will cause the connections to remain locked and your application will eventually run out of connections in the pool. The following examples illustrate the various behaviors that the ::py:class:`queries.Results <queries.tornado_session.Requests>` class implements: **Using Results as an Iterator** .. code:: python results = yield session.query('SELECT * FROM foo') for row in results print row results.free() **Accessing an individual row by index** .. code:: python results = yield session.query('SELECT * FROM foo') print results[1] # Access the second row of the results results.free() **Casting single row results as a dict** .. code:: python results = yield session.query('SELECT * FROM foo LIMIT 1') print results.as_dict() results.free() **Checking to see if a query was successful** .. code:: python sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'" results = yield session.query(sql) if results: print 'Success' results.free() **Checking the number of rows by using len(Results)** .. code:: python results = yield session.query('SELECT * FROM foo') print '%i rows' % len(results) results.free() """ def __init__(self, cursor, cleanup, fd): self.cursor = cursor self._cleanup = cleanup self._fd = fd self._freed = False def free(self): """Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or the connection will not be able to be reused by other asynchronous requests. """ self._freed = True self._cleanup(self.cursor, self._fd) def __del__(self): if not self._freed: LOGGER.warning('Auto-freeing result on deletion') self.free() class TornadoSession(session.Session): """Session class for Tornado asynchronous applications. Uses :py:func:`tornado.gen.coroutine` to wrap API methods for use in Tornado. Utilizes connection pooling to ensure that multiple concurrent asynchronous queries do not block each other. Heavily trafficked services will require a higher ``max_pool_size`` to allow for greater connection concurrency. :py:meth:`TornadoSession.query <queries.TornadoSession.query>` and :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` must call :py:meth:`Results.free <queries.tornado_session.Results.free>` :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use """ def __init__(self, uri=session.DEFAULT_URI, cursor_factory=extras.RealDictCursor, pool_idle_ttl=pool.DEFAULT_IDLE_TTL, pool_max_size=DEFAULT_MAX_POOL_SIZE, io_loop=None): """Connect to a PostgreSQL server using the module wide connection and set the isolation level. :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use :param tornado.ioloop.IOLoop io_loop: IOLoop instance to use """ self._connections = dict() self._cleanup_callback = None self._cursor_factory = cursor_factory self._futures = dict() self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() self._pool_max_size = pool_max_size """ self._connections = dict() self._futures = dict() self._cleanup_callback = None self._pool_idle_ttl = pool_idle_ttl self._cursor_factory = cursor_factory self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() self._uri = uri # Ensure the pool exists in the pool manager if self.pid not in self._pool_manager: self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size, self._ioloop.time) @property def connection(self): return None def callproc(self, name, args=None): """Call a stored procedure asynchronously on the server, passing in the arguments to be passed to the stored procedure, yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str name: The stored procedure name :param list args: An optional list of procedure arguments :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('callproc', name, args) def query(self, sql, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('execute', sql, parameters) def validate(self): """Validate the session can connect or has open connections to PostgreSQL. As of ``1.10.3`` .. deprecated:: 1.10.3 As of 1.10.3, this method only warns about Deprecation :rtype: bool """ warnings.warn( 'All functionality removed from this method', DeprecationWarning) def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool if possible, or by creating the new connection. :rtype: psycopg2.extensions.connection :raises: pool.NoIdleConnectionsError """ future = concurrent.Future() # Attempt to get a cached connection from the connection pool try: connection = self._pool_manager.get(self.pid, self) self._connections[connection.fileno()] = connection future.set_result(connection) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) except pool.NoIdleConnectionsError: self._create_connection(future) return future def _create_connection(self, future): """Create a new PostgreSQL connection :param tornado.concurrent.Future future: future for new conn result """ LOGGER.debug('Creating a new connection for %s', self.pid) # Create a new PostgreSQL connection kwargs = utils.uri_to_kwargs(self._uri) try: connection = self._psycopg2_connect(kwargs) except (psycopg2.Error, OSError, socket.error) as error: future.set_exception(error) return # Add the connection for use in _poll_connection fd = connection.fileno() self._connections[fd] = connection def on_connected(cf): """Invoked by the IOLoop when the future is complete for the connection :param Future cf: The future for the initial connection """ if cf.exception(): self._cleanup_fd(fd, True) future.set_exception(cf.exception()) else: try: # Add the connection to the pool LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) except (ValueError, pool.PoolException) as err: LOGGER.exception('Failed to add %r to the pool', self.pid) self._cleanup_fd(fd) future.set_exception(err) return self._pool_manager.lock(self.pid, connection, self) # Added in because psycopg2cffi connects and leaves the # connection in a weird state: consts.STATUS_DATESTYLE, # returning from Connection._setup without setting the state # as const.STATUS_OK if utils.PYPY: connection.status = extensions.STATUS_READY # Register the custom data types self._register_unicode(connection) self._register_uuid(connection) # Set the future result future.set_result(connection) # Add a future that fires once connected self._futures[fd] = concurrent.Future() self._ioloop.add_future(self._futures[fd], on_connected) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) def _execute(self, method, query, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. This function reduces duplicate code for callproc and query by getting the class attribute for the method passed in as the function to call. :param str method: The method attribute to use :param str query: The SQL statement or Stored Procedure name :param list|dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ future = concurrent.Future() def on_connected(cf): """Invoked by the future returned by self._connect""" if cf.exception(): future.set_exception(cf.exception()) return # Get the psycopg2 connection object and cursor conn = cf.result() cursor = self._get_cursor(conn) def completed(qf): """Invoked by the IOLoop when the future has completed""" if qf.exception(): self._incr_exceptions(conn) err = qf.exception() LOGGER.debug('Cleaning cursor due to exception: %r', err) self._exec_cleanup(cursor, conn.fileno()) future.set_exception(err) else: self._incr_executions(conn) value = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(value) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.Future() # Add the future to the IOLoop self._ioloop.add_future(self._futures[conn.fileno()], completed) # Get the cursor, execute the query func = getattr(cursor, method) try: func(query, parameters) except Exception as error: future.set_exception(error) # Ensure the pool exists for the connection self._ensure_pool_exists() # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. :param psycopg2.extensions.cursor cursor: The cursor to close :param int fd: The connection file descriptor """ LOGGER.debug('Closing cursor and cleaning %s', fd) try: cursor.close() func = getattr(cursor, method) func(query, parameters) # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Create a new cleanup callback to clean the pool of idle connections self._cleanup_callback = self._ioloop.add_timeout( self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) def _cleanup_fd(self, fd, close=False): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. :param int fd: The fd # to cleanup """ self._ioloop.remove_handler(fd) if fd in self._connections: try: self._pool_manager.free(self.pid, self._connections[fd]) except pool.ConnectionNotFoundError: pass if close: self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd] def _incr_exceptions(self, conn): """Increment the number of exceptions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).exceptions += 1 def _incr_executions(self, conn): """Increment the number of executions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).executions += 1 def _on_io_events(self, fd=None, _events=None): """Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised """ if fd not in self._connections: LOGGER.warning('Received IO event for non-existing connection') return self._poll_connection(fd) def _poll_connection(self, fd): """Check with psycopg2 to see what action to take. If the state is POLL_OK, we should have a pending callback for that fd. :param int fd: The socket fd for the postgresql connection """ try: state = self._connections[fd].poll() except (OSError, socket.error) as error: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.OperationalError('Connection error (%s)' % error) ) except (psycopg2.Error, psycopg2.Warning) as error: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception(error) else: if state == extensions.POLL_OK: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_result(True) elif state == extensions.POLL_WRITE: self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE) elif state == extensions.POLL_READ: self._ioloop.update_handler(fd, ioloop.IOLoop.READ) elif state == extensions.POLL_ERROR: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.Error('Poll Error')) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. :param dict kwargs: Keyword connection args :rtype: psycopg2.extensions.connection """ kwargs['async'] = True return psycopg2.connect(**kwargs) <MSG> Ensure the pool exists when executing a query <DFF> @@ -161,19 +161,20 @@ class TornadoSession(session.Session): """ self._connections = dict() - self._futures = dict() self._cleanup_callback = None - self._pool_idle_ttl = pool_idle_ttl - self._cursor_factory = cursor_factory + self._futures = dict() self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() + self._pool_max_size = pool_max_size + self._pool_idle_ttl = pool_idle_ttl self._uri = uri - # Ensure the pool exists in the pool manager + def _ensure_pool_exists(self): + """Create the pool in the pool manager if it does not exist.""" if self.pid not in self._pool_manager: - self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size, - self._ioloop.time) + self._pool_manager.create(self.pid, self._pool_idle_ttl, + self._pool_max_size, self._ioloop.time) @property def connection(self): @@ -418,6 +419,9 @@ class TornadoSession(session.Session): func = getattr(cursor, method) func(query, parameters) + # Ensure the pool exists for the connection + self._ensure_pool_exists() + # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected)
10
Ensure the pool exists when executing a query
6
.py
py
bsd-3-clause
gmr/queries
1638
<NME> tornado_session.py <BEF> """ Tornado Session Adapter Use Queries asynchronously within the Tornado framework. Example Use: .. code:: python class NameListHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession(pool_max_size=60) @gen.coroutine def get(self): data = yield self.session.query('SELECT * FROM names') if data: self.finish({'names': data.items()}) data.free() else: self.set_status(500, 'Error querying the data') """ import logging import socket import warnings from tornado import concurrent, ioloop from psycopg2 import extras, extensions import psycopg2 from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) DEFAULT_MAX_POOL_SIZE = 25 class Results(results.Results): """A TornadoSession specific :py:class:`queries.Results` class that adds the :py:meth:`Results.free <queries.tornado_session.Results.free>` method. The :py:meth:`Results.free <queries.tornado_session.Results.free>` method **must** be called to free the connection that the results were generated on. `Results` objects that are not freed will cause the connections to remain locked and your application will eventually run out of connections in the pool. The following examples illustrate the various behaviors that the ::py:class:`queries.Results <queries.tornado_session.Requests>` class implements: **Using Results as an Iterator** .. code:: python results = yield session.query('SELECT * FROM foo') for row in results print row results.free() **Accessing an individual row by index** .. code:: python results = yield session.query('SELECT * FROM foo') print results[1] # Access the second row of the results results.free() **Casting single row results as a dict** .. code:: python results = yield session.query('SELECT * FROM foo LIMIT 1') print results.as_dict() results.free() **Checking to see if a query was successful** .. code:: python sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'" results = yield session.query(sql) if results: print 'Success' results.free() **Checking the number of rows by using len(Results)** .. code:: python results = yield session.query('SELECT * FROM foo') print '%i rows' % len(results) results.free() """ def __init__(self, cursor, cleanup, fd): self.cursor = cursor self._cleanup = cleanup self._fd = fd self._freed = False def free(self): """Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or the connection will not be able to be reused by other asynchronous requests. """ self._freed = True self._cleanup(self.cursor, self._fd) def __del__(self): if not self._freed: LOGGER.warning('Auto-freeing result on deletion') self.free() class TornadoSession(session.Session): """Session class for Tornado asynchronous applications. Uses :py:func:`tornado.gen.coroutine` to wrap API methods for use in Tornado. Utilizes connection pooling to ensure that multiple concurrent asynchronous queries do not block each other. Heavily trafficked services will require a higher ``max_pool_size`` to allow for greater connection concurrency. :py:meth:`TornadoSession.query <queries.TornadoSession.query>` and :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` must call :py:meth:`Results.free <queries.tornado_session.Results.free>` :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use """ def __init__(self, uri=session.DEFAULT_URI, cursor_factory=extras.RealDictCursor, pool_idle_ttl=pool.DEFAULT_IDLE_TTL, pool_max_size=DEFAULT_MAX_POOL_SIZE, io_loop=None): """Connect to a PostgreSQL server using the module wide connection and set the isolation level. :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use :param tornado.ioloop.IOLoop io_loop: IOLoop instance to use """ self._connections = dict() self._cleanup_callback = None self._cursor_factory = cursor_factory self._futures = dict() self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() self._pool_max_size = pool_max_size """ self._connections = dict() self._futures = dict() self._cleanup_callback = None self._pool_idle_ttl = pool_idle_ttl self._cursor_factory = cursor_factory self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() self._uri = uri # Ensure the pool exists in the pool manager if self.pid not in self._pool_manager: self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size, self._ioloop.time) @property def connection(self): return None def callproc(self, name, args=None): """Call a stored procedure asynchronously on the server, passing in the arguments to be passed to the stored procedure, yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str name: The stored procedure name :param list args: An optional list of procedure arguments :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('callproc', name, args) def query(self, sql, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('execute', sql, parameters) def validate(self): """Validate the session can connect or has open connections to PostgreSQL. As of ``1.10.3`` .. deprecated:: 1.10.3 As of 1.10.3, this method only warns about Deprecation :rtype: bool """ warnings.warn( 'All functionality removed from this method', DeprecationWarning) def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool if possible, or by creating the new connection. :rtype: psycopg2.extensions.connection :raises: pool.NoIdleConnectionsError """ future = concurrent.Future() # Attempt to get a cached connection from the connection pool try: connection = self._pool_manager.get(self.pid, self) self._connections[connection.fileno()] = connection future.set_result(connection) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) except pool.NoIdleConnectionsError: self._create_connection(future) return future def _create_connection(self, future): """Create a new PostgreSQL connection :param tornado.concurrent.Future future: future for new conn result """ LOGGER.debug('Creating a new connection for %s', self.pid) # Create a new PostgreSQL connection kwargs = utils.uri_to_kwargs(self._uri) try: connection = self._psycopg2_connect(kwargs) except (psycopg2.Error, OSError, socket.error) as error: future.set_exception(error) return # Add the connection for use in _poll_connection fd = connection.fileno() self._connections[fd] = connection def on_connected(cf): """Invoked by the IOLoop when the future is complete for the connection :param Future cf: The future for the initial connection """ if cf.exception(): self._cleanup_fd(fd, True) future.set_exception(cf.exception()) else: try: # Add the connection to the pool LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) except (ValueError, pool.PoolException) as err: LOGGER.exception('Failed to add %r to the pool', self.pid) self._cleanup_fd(fd) future.set_exception(err) return self._pool_manager.lock(self.pid, connection, self) # Added in because psycopg2cffi connects and leaves the # connection in a weird state: consts.STATUS_DATESTYLE, # returning from Connection._setup without setting the state # as const.STATUS_OK if utils.PYPY: connection.status = extensions.STATUS_READY # Register the custom data types self._register_unicode(connection) self._register_uuid(connection) # Set the future result future.set_result(connection) # Add a future that fires once connected self._futures[fd] = concurrent.Future() self._ioloop.add_future(self._futures[fd], on_connected) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) def _execute(self, method, query, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. This function reduces duplicate code for callproc and query by getting the class attribute for the method passed in as the function to call. :param str method: The method attribute to use :param str query: The SQL statement or Stored Procedure name :param list|dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ future = concurrent.Future() def on_connected(cf): """Invoked by the future returned by self._connect""" if cf.exception(): future.set_exception(cf.exception()) return # Get the psycopg2 connection object and cursor conn = cf.result() cursor = self._get_cursor(conn) def completed(qf): """Invoked by the IOLoop when the future has completed""" if qf.exception(): self._incr_exceptions(conn) err = qf.exception() LOGGER.debug('Cleaning cursor due to exception: %r', err) self._exec_cleanup(cursor, conn.fileno()) future.set_exception(err) else: self._incr_executions(conn) value = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(value) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.Future() # Add the future to the IOLoop self._ioloop.add_future(self._futures[conn.fileno()], completed) # Get the cursor, execute the query func = getattr(cursor, method) try: func(query, parameters) except Exception as error: future.set_exception(error) # Ensure the pool exists for the connection self._ensure_pool_exists() # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. :param psycopg2.extensions.cursor cursor: The cursor to close :param int fd: The connection file descriptor """ LOGGER.debug('Closing cursor and cleaning %s', fd) try: cursor.close() func = getattr(cursor, method) func(query, parameters) # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Create a new cleanup callback to clean the pool of idle connections self._cleanup_callback = self._ioloop.add_timeout( self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) def _cleanup_fd(self, fd, close=False): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. :param int fd: The fd # to cleanup """ self._ioloop.remove_handler(fd) if fd in self._connections: try: self._pool_manager.free(self.pid, self._connections[fd]) except pool.ConnectionNotFoundError: pass if close: self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd] def _incr_exceptions(self, conn): """Increment the number of exceptions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).exceptions += 1 def _incr_executions(self, conn): """Increment the number of executions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).executions += 1 def _on_io_events(self, fd=None, _events=None): """Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised """ if fd not in self._connections: LOGGER.warning('Received IO event for non-existing connection') return self._poll_connection(fd) def _poll_connection(self, fd): """Check with psycopg2 to see what action to take. If the state is POLL_OK, we should have a pending callback for that fd. :param int fd: The socket fd for the postgresql connection """ try: state = self._connections[fd].poll() except (OSError, socket.error) as error: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.OperationalError('Connection error (%s)' % error) ) except (psycopg2.Error, psycopg2.Warning) as error: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception(error) else: if state == extensions.POLL_OK: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_result(True) elif state == extensions.POLL_WRITE: self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE) elif state == extensions.POLL_READ: self._ioloop.update_handler(fd, ioloop.IOLoop.READ) elif state == extensions.POLL_ERROR: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.Error('Poll Error')) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. :param dict kwargs: Keyword connection args :rtype: psycopg2.extensions.connection """ kwargs['async'] = True return psycopg2.connect(**kwargs) <MSG> Ensure the pool exists when executing a query <DFF> @@ -161,19 +161,20 @@ class TornadoSession(session.Session): """ self._connections = dict() - self._futures = dict() self._cleanup_callback = None - self._pool_idle_ttl = pool_idle_ttl - self._cursor_factory = cursor_factory + self._futures = dict() self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() + self._pool_max_size = pool_max_size + self._pool_idle_ttl = pool_idle_ttl self._uri = uri - # Ensure the pool exists in the pool manager + def _ensure_pool_exists(self): + """Create the pool in the pool manager if it does not exist.""" if self.pid not in self._pool_manager: - self._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size, - self._ioloop.time) + self._pool_manager.create(self.pid, self._pool_idle_ttl, + self._pool_max_size, self._ioloop.time) @property def connection(self): @@ -418,6 +419,9 @@ class TornadoSession(session.Session): func = getattr(cursor, method) func(query, parameters) + # Ensure the pool exists for the connection + self._ensure_pool_exists() + # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected)
10
Ensure the pool exists when executing a query
6
.py
py
bsd-3-clause
gmr/queries
1639
<NME> .travis.yml <BEF> sudo: false cache: directories: - $HOME/.pip-cache/ language: python python: - 2.6 env: global: - 3.3 - 3.4 - 3.5 addons: postgresql: '9.3' install: - pip install -r test-requirements.txt - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2 --download-cache $HOME/.pip-cache; fi - python setup.py develop script: nosetests after_success: services: - postgresql install: - pip install awscli - pip install -r requires/testing.txt - python setup.py develop user: crad password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= notifications: webhooks: urls: - https://webhooks.gitter.im/e/d96fcd17db66e06d833d on_success: always on_failure: always on_start: always - aws s3 cp .coverage "s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/.coverage.${TRAVIS_PYTHON_VERSION}" jobs: include: - python: 2.7 - python: 3.4 - python: 3.5 - python: 3.6 - python: 3.7 - python: 3.8 - stage: coverage if: repo = gmr/queries services: [] python: 3.7 install: - pip install awscli coverage codecov script: - mkdir coverage - aws s3 cp --recursive s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/ coverage - cd coverage - coverage combine - cd .. - mv coverage/.coverage . - coverage report after_success: codecov - stage: deploy if: repo = gmr/queries python: 3.6 services: [] install: true script: true after_success: true deploy: distributions: sdist bdist_wheel provider: pypi user: crad on: tags: true all_branches: true password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= <MSG> Update Travis config <DFF> @@ -1,7 +1,4 @@ sudo: false -cache: - directories: - - $HOME/.pip-cache/ language: python python: - 2.6 @@ -10,11 +7,11 @@ python: - 3.3 - 3.4 - 3.5 -addons: - postgresql: '9.3' +services: + - postgresql install: - pip install -r test-requirements.txt - - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2 --download-cache $HOME/.pip-cache; fi + - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi - python setup.py develop script: nosetests after_success: @@ -29,10 +26,3 @@ deploy: user: crad password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/d96fcd17db66e06d833d - on_success: always - on_failure: always - on_start: always
3
Update Travis config
13
.yml
travis
bsd-3-clause
gmr/queries
1640
<NME> .travis.yml <BEF> sudo: false cache: directories: - $HOME/.pip-cache/ language: python python: - 2.6 env: global: - 3.3 - 3.4 - 3.5 addons: postgresql: '9.3' install: - pip install -r test-requirements.txt - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2 --download-cache $HOME/.pip-cache; fi - python setup.py develop script: nosetests after_success: services: - postgresql install: - pip install awscli - pip install -r requires/testing.txt - python setup.py develop user: crad password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= notifications: webhooks: urls: - https://webhooks.gitter.im/e/d96fcd17db66e06d833d on_success: always on_failure: always on_start: always - aws s3 cp .coverage "s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/.coverage.${TRAVIS_PYTHON_VERSION}" jobs: include: - python: 2.7 - python: 3.4 - python: 3.5 - python: 3.6 - python: 3.7 - python: 3.8 - stage: coverage if: repo = gmr/queries services: [] python: 3.7 install: - pip install awscli coverage codecov script: - mkdir coverage - aws s3 cp --recursive s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/ coverage - cd coverage - coverage combine - cd .. - mv coverage/.coverage . - coverage report after_success: codecov - stage: deploy if: repo = gmr/queries python: 3.6 services: [] install: true script: true after_success: true deploy: distributions: sdist bdist_wheel provider: pypi user: crad on: tags: true all_branches: true password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= <MSG> Update Travis config <DFF> @@ -1,7 +1,4 @@ sudo: false -cache: - directories: - - $HOME/.pip-cache/ language: python python: - 2.6 @@ -10,11 +7,11 @@ python: - 3.3 - 3.4 - 3.5 -addons: - postgresql: '9.3' +services: + - postgresql install: - pip install -r test-requirements.txt - - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2 --download-cache $HOME/.pip-cache; fi + - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install unittest2; fi - python setup.py develop script: nosetests after_success: @@ -29,10 +26,3 @@ deploy: user: crad password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= -notifications: - webhooks: - urls: - - https://webhooks.gitter.im/e/d96fcd17db66e06d833d - on_success: always - on_failure: always - on_start: always
3
Update Travis config
13
.yml
travis
bsd-3-clause
gmr/queries
1641
<NME> .gitignore <BEF> .DS_Store .idea *.pyc build dist *.egg-info atlassian-ide-plugin.xml docs/_build .coverage <MSG> Ignore virtualenv dir <DFF> @@ -7,3 +7,4 @@ dist atlassian-ide-plugin.xml docs/_build .coverage +env
1
Ignore virtualenv dir
0
gitignore
bsd-3-clause
gmr/queries
1642
<NME> .gitignore <BEF> .DS_Store .idea *.pyc build dist *.egg-info atlassian-ide-plugin.xml docs/_build .coverage <MSG> Ignore virtualenv dir <DFF> @@ -7,3 +7,4 @@ dist atlassian-ide-plugin.xml docs/_build .coverage +env
1
Ignore virtualenv dir
0
gitignore
bsd-3-clause
gmr/queries
1643
<NME> tornado_session.py <BEF> """ Tornado Session Adapter Use Queries asynchronously within the Tornado framework. Example Use: .. code:: python class NameListHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession(pool_max_size=60) @gen.coroutine def get(self): data = yield self.session.query('SELECT * FROM names') if data: self.finish({'names': data.items()}) data.free() else: self.set_status(500, 'Error querying the data') """ import logging import socket import warnings from tornado import concurrent, ioloop from psycopg2 import extras, extensions import psycopg2 from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) DEFAULT_MAX_POOL_SIZE = 25 class Results(results.Results): """A TornadoSession specific :py:class:`queries.Results` class that adds the :py:meth:`Results.free <queries.tornado_session.Results.free>` method. The :py:meth:`Results.free <queries.tornado_session.Results.free>` method **must** be called to free the connection that the results were generated on. `Results` objects that are not freed will cause the connections to remain locked and your application will eventually run out of connections in the pool. The following examples illustrate the various behaviors that the ::py:class:`queries.Results <queries.tornado_session.Requests>` class implements: **Using Results as an Iterator** .. code:: python results = yield session.query('SELECT * FROM foo') for row in results print row results.free() **Accessing an individual row by index** .. code:: python results = yield session.query('SELECT * FROM foo') print results[1] # Access the second row of the results results.free() **Casting single row results as a dict** .. code:: python results = yield session.query('SELECT * FROM foo LIMIT 1') print results.as_dict() results.free() **Checking to see if a query was successful** .. code:: python sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'" results = yield session.query(sql) if results: print 'Success' results.free() **Checking the number of rows by using len(Results)** .. code:: python results = yield session.query('SELECT * FROM foo') print '%i rows' % len(results) results.free() """ def __init__(self, cursor, cleanup, fd): self.cursor = cursor self._cleanup = cleanup self._fd = fd self._freed = False def free(self): """Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or the connection will not be able to be reused by other asynchronous requests. """ self._freed = True self._cleanup(self.cursor, self._fd) def __del__(self): if not self._freed: LOGGER.warning('Auto-freeing result on deletion') self.free() class TornadoSession(session.Session): """Session class for Tornado asynchronous applications. Uses :py:func:`tornado.gen.coroutine` to wrap API methods for use in Tornado. Utilizes connection pooling to ensure that multiple concurrent asynchronous queries do not block each other. Heavily trafficked services will require a higher ``max_pool_size`` to allow for greater connection concurrency. :py:meth:`TornadoSession.query <queries.TornadoSession.query>` and :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` must call :py:meth:`Results.free <queries.tornado_session.Results.free>` :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use """ def __init__(self, uri=session.DEFAULT_URI, cursor_factory=extras.RealDictCursor, pool_idle_ttl=pool.DEFAULT_IDLE_TTL, pool_max_size=DEFAULT_MAX_POOL_SIZE, io_loop=None): """Connect to a PostgreSQL server using the module wide connection and set the isolation level. :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use :param tornado.ioloop.IOLoop io_loop: IOLoop instance to use """ self._connections = dict() self._cleanup_callback = None self._cursor_factory = cursor_factory self._futures = dict() self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() self._pool_max_size = pool_max_size self._pool_idle_ttl = pool_idle_ttl self._uri = uri self._ensure_pool_exists() def _ensure_pool_exists(self): """Create the pool in the pool manager if it does not exist.""" if self.pid not in self._pool_manager: self._pool_manager.create(self.pid, self._pool_idle_ttl, self._pool_max_size, self._ioloop.time) @property def connection(self): """Do not use this directly with Tornado applications :return: """ return None @property def cursor(self): return None def callproc(self, name, args=None): """Call a stored procedure asynchronously on the server, passing in the arguments to be passed to the stored procedure, yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str name: The stored procedure name :param list args: An optional list of procedure arguments :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('callproc', name, args) def query(self, sql, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('execute', sql, parameters) def validate(self): """Validate the session can connect or has open connections to PostgreSQL. As of ``1.10.3`` .. deprecated:: 1.10.3 As of 1.10.3, this method only warns about Deprecation :rtype: bool """ warnings.warn( 'All functionality removed from this method', DeprecationWarning) def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool if possible, or by creating the new connection. :rtype: psycopg2.extensions.connection :raises: pool.NoIdleConnectionsError """ future = concurrent.Future() # Attempt to get a cached connection from the connection pool try: connection = self._pool_manager.get(self.pid, self) self._connections[connection.fileno()] = connection future.set_result(connection) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) except pool.NoIdleConnectionsError: self._create_connection(future) return future def _create_connection(self, future): """Create a new PostgreSQL connection :param tornado.concurrent.Future future: future for new conn result """ LOGGER.debug('Creating a new connection for %s', self.pid) # Create a new PostgreSQL connection kwargs = utils.uri_to_kwargs(self._uri) try: connection = self._psycopg2_connect(kwargs) except (psycopg2.Error, OSError, socket.error) as error: future.set_exception(error) return # Add the connection for use in _poll_connection fd = connection.fileno() self._connections[fd] = connection def on_connected(cf): """Invoked by the IOLoop when the future is complete for the connection :param Future cf: The future for the initial connection """ if cf.exception(): self._cleanup_fd(fd) future.set_exception(cf.exception()) else: try: # Add the connection to the pool LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) except (ValueError, pool.PoolException) as err: LOGGER.exception('Failed to add %r to the pool', self.pid) self._cleanup_fd(fd) future.set_exception(err) return self._pool_manager.lock(self.pid, connection, self) # Added in because psycopg2cffi connects and leaves the # connection in a weird state: consts.STATUS_DATESTYLE, # returning from Connection._setup without setting the state # as const.STATUS_OK if utils.PYPY: connection.status = extensions.STATUS_READY # Register the custom data types self._register_unicode(connection) self._register_uuid(connection) # Set the future result future.set_result(connection) # Add a future that fires once connected self._futures[fd] = concurrent.Future() self._ioloop.add_future(self._futures[fd], on_connected) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) def _execute(self, method, query, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. This function reduces duplicate code for callproc and query by getting the class attribute for the method passed in as the function to call. :param str method: The method attribute to use :param str query: The SQL statement or Stored Procedure name :param list|dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ future = concurrent.Future() def on_connected(cf): """Invoked by the future returned by self._connect""" if cf.exception(): future.set_exception(cf.exception()) return # Get the psycopg2 connection object and cursor conn = cf.result() cursor = self._get_cursor(conn) def completed(qf): """Invoked by the IOLoop when the future has completed""" if qf.exception(): self._incr_exceptions(conn) err = qf.exception() LOGGER.debug('Cleaning cursor due to exception: %r', err) self._exec_cleanup(cursor, conn.fileno()) future.set_exception(err) else: self._incr_executions(conn) value = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(value) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.Future() # Add the future to the IOLoop self._ioloop.add_future(self._futures[conn.fileno()], completed) # Get the cursor, execute the query func = getattr(cursor, method) try: func(query, parameters) except Exception as error: future.set_exception(error) # Ensure the pool exists for the connection self._ensure_pool_exists() # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. :param psycopg2.extensions.cursor cursor: The cursor to close :param int fd: The connection file descriptor """ LOGGER.debug('Closing cursor and cleaning %s', fd) try: cursor.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.debug('Error closing the cursor: %s', error) self._cleanup_fd(fd) # If the cleanup callback exists, remove it if self._cleanup_callback: self._ioloop.remove_timeout(self._cleanup_callback) # Create a new cleanup callback to clean the pool of idle connections self._cleanup_callback = self._ioloop.add_timeout( self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) def _cleanup_fd(self, fd): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. :param int fd: The fd # to cleanup """ self._ioloop.remove_handler(fd) if fd in self._connections: try: self._pool_manager.free(self.pid, self._connections[fd]) except pool.ConnectionNotFoundError: pass self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd] def _incr_exceptions(self, conn): """Increment the number of exceptions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).exceptions += 1 def _incr_executions(self, conn): """Increment the number of executions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).executions += 1 def _on_io_events(self, fd=None, _events=None): """Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised """ if fd not in self._connections: LOGGER.warning('Received IO event for non-existing connection') return self._poll_connection(fd) def _poll_connection(self, fd): """Check with psycopg2 to see what action to take. If the state is POLL_OK, we should have a pending callback for that fd. :param int fd: The socket fd for the postgresql connection """ try: state = self._connections[fd].poll() except (OSError, socket.error) as error: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.OperationalError('Connection error (%s)' % error) ) except (psycopg2.Error, psycopg2.Warning) as error: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception(error) else: if state == extensions.POLL_OK: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_result(True) elif state == extensions.POLL_WRITE: self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE) elif state == extensions.POLL_READ: self._ioloop.update_handler(fd, ioloop.IOLoop.READ) elif state == extensions.POLL_ERROR: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.Error('Poll Error')) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. :param dict kwargs: Keyword connection args :rtype: psycopg2.extensions.connection """ kwargs['async'] = True return psycopg2.connect(**kwargs) <MSG> Dont close when cleaning up (all the time) — add counters <DFF> @@ -295,7 +295,7 @@ class TornadoSession(session.Session): """ if cf.exception(): - self._cleanup_fd(fd) + self._cleanup_fd(fd, True) future.set_exception(cf.exception()) else: @@ -430,7 +430,7 @@ class TornadoSession(session.Session): self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) - def _cleanup_fd(self, fd): + def _cleanup_fd(self, fd, close=False): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. @@ -443,7 +443,8 @@ class TornadoSession(session.Session): self._pool_manager.free(self.pid, self._connections[fd]) except pool.ConnectionNotFoundError: pass - self._connections[fd].close() + if close: + self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd]
4
Dont close when cleaning up (all the time) — add counters
3
.py
py
bsd-3-clause
gmr/queries
1644
<NME> tornado_session.py <BEF> """ Tornado Session Adapter Use Queries asynchronously within the Tornado framework. Example Use: .. code:: python class NameListHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession(pool_max_size=60) @gen.coroutine def get(self): data = yield self.session.query('SELECT * FROM names') if data: self.finish({'names': data.items()}) data.free() else: self.set_status(500, 'Error querying the data') """ import logging import socket import warnings from tornado import concurrent, ioloop from psycopg2 import extras, extensions import psycopg2 from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) DEFAULT_MAX_POOL_SIZE = 25 class Results(results.Results): """A TornadoSession specific :py:class:`queries.Results` class that adds the :py:meth:`Results.free <queries.tornado_session.Results.free>` method. The :py:meth:`Results.free <queries.tornado_session.Results.free>` method **must** be called to free the connection that the results were generated on. `Results` objects that are not freed will cause the connections to remain locked and your application will eventually run out of connections in the pool. The following examples illustrate the various behaviors that the ::py:class:`queries.Results <queries.tornado_session.Requests>` class implements: **Using Results as an Iterator** .. code:: python results = yield session.query('SELECT * FROM foo') for row in results print row results.free() **Accessing an individual row by index** .. code:: python results = yield session.query('SELECT * FROM foo') print results[1] # Access the second row of the results results.free() **Casting single row results as a dict** .. code:: python results = yield session.query('SELECT * FROM foo LIMIT 1') print results.as_dict() results.free() **Checking to see if a query was successful** .. code:: python sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'" results = yield session.query(sql) if results: print 'Success' results.free() **Checking the number of rows by using len(Results)** .. code:: python results = yield session.query('SELECT * FROM foo') print '%i rows' % len(results) results.free() """ def __init__(self, cursor, cleanup, fd): self.cursor = cursor self._cleanup = cleanup self._fd = fd self._freed = False def free(self): """Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or the connection will not be able to be reused by other asynchronous requests. """ self._freed = True self._cleanup(self.cursor, self._fd) def __del__(self): if not self._freed: LOGGER.warning('Auto-freeing result on deletion') self.free() class TornadoSession(session.Session): """Session class for Tornado asynchronous applications. Uses :py:func:`tornado.gen.coroutine` to wrap API methods for use in Tornado. Utilizes connection pooling to ensure that multiple concurrent asynchronous queries do not block each other. Heavily trafficked services will require a higher ``max_pool_size`` to allow for greater connection concurrency. :py:meth:`TornadoSession.query <queries.TornadoSession.query>` and :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` must call :py:meth:`Results.free <queries.tornado_session.Results.free>` :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use """ def __init__(self, uri=session.DEFAULT_URI, cursor_factory=extras.RealDictCursor, pool_idle_ttl=pool.DEFAULT_IDLE_TTL, pool_max_size=DEFAULT_MAX_POOL_SIZE, io_loop=None): """Connect to a PostgreSQL server using the module wide connection and set the isolation level. :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use :param tornado.ioloop.IOLoop io_loop: IOLoop instance to use """ self._connections = dict() self._cleanup_callback = None self._cursor_factory = cursor_factory self._futures = dict() self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() self._pool_max_size = pool_max_size self._pool_idle_ttl = pool_idle_ttl self._uri = uri self._ensure_pool_exists() def _ensure_pool_exists(self): """Create the pool in the pool manager if it does not exist.""" if self.pid not in self._pool_manager: self._pool_manager.create(self.pid, self._pool_idle_ttl, self._pool_max_size, self._ioloop.time) @property def connection(self): """Do not use this directly with Tornado applications :return: """ return None @property def cursor(self): return None def callproc(self, name, args=None): """Call a stored procedure asynchronously on the server, passing in the arguments to be passed to the stored procedure, yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str name: The stored procedure name :param list args: An optional list of procedure arguments :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('callproc', name, args) def query(self, sql, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('execute', sql, parameters) def validate(self): """Validate the session can connect or has open connections to PostgreSQL. As of ``1.10.3`` .. deprecated:: 1.10.3 As of 1.10.3, this method only warns about Deprecation :rtype: bool """ warnings.warn( 'All functionality removed from this method', DeprecationWarning) def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool if possible, or by creating the new connection. :rtype: psycopg2.extensions.connection :raises: pool.NoIdleConnectionsError """ future = concurrent.Future() # Attempt to get a cached connection from the connection pool try: connection = self._pool_manager.get(self.pid, self) self._connections[connection.fileno()] = connection future.set_result(connection) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) except pool.NoIdleConnectionsError: self._create_connection(future) return future def _create_connection(self, future): """Create a new PostgreSQL connection :param tornado.concurrent.Future future: future for new conn result """ LOGGER.debug('Creating a new connection for %s', self.pid) # Create a new PostgreSQL connection kwargs = utils.uri_to_kwargs(self._uri) try: connection = self._psycopg2_connect(kwargs) except (psycopg2.Error, OSError, socket.error) as error: future.set_exception(error) return # Add the connection for use in _poll_connection fd = connection.fileno() self._connections[fd] = connection def on_connected(cf): """Invoked by the IOLoop when the future is complete for the connection :param Future cf: The future for the initial connection """ if cf.exception(): self._cleanup_fd(fd) future.set_exception(cf.exception()) else: try: # Add the connection to the pool LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) except (ValueError, pool.PoolException) as err: LOGGER.exception('Failed to add %r to the pool', self.pid) self._cleanup_fd(fd) future.set_exception(err) return self._pool_manager.lock(self.pid, connection, self) # Added in because psycopg2cffi connects and leaves the # connection in a weird state: consts.STATUS_DATESTYLE, # returning from Connection._setup without setting the state # as const.STATUS_OK if utils.PYPY: connection.status = extensions.STATUS_READY # Register the custom data types self._register_unicode(connection) self._register_uuid(connection) # Set the future result future.set_result(connection) # Add a future that fires once connected self._futures[fd] = concurrent.Future() self._ioloop.add_future(self._futures[fd], on_connected) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) def _execute(self, method, query, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. This function reduces duplicate code for callproc and query by getting the class attribute for the method passed in as the function to call. :param str method: The method attribute to use :param str query: The SQL statement or Stored Procedure name :param list|dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ future = concurrent.Future() def on_connected(cf): """Invoked by the future returned by self._connect""" if cf.exception(): future.set_exception(cf.exception()) return # Get the psycopg2 connection object and cursor conn = cf.result() cursor = self._get_cursor(conn) def completed(qf): """Invoked by the IOLoop when the future has completed""" if qf.exception(): self._incr_exceptions(conn) err = qf.exception() LOGGER.debug('Cleaning cursor due to exception: %r', err) self._exec_cleanup(cursor, conn.fileno()) future.set_exception(err) else: self._incr_executions(conn) value = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(value) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.Future() # Add the future to the IOLoop self._ioloop.add_future(self._futures[conn.fileno()], completed) # Get the cursor, execute the query func = getattr(cursor, method) try: func(query, parameters) except Exception as error: future.set_exception(error) # Ensure the pool exists for the connection self._ensure_pool_exists() # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. :param psycopg2.extensions.cursor cursor: The cursor to close :param int fd: The connection file descriptor """ LOGGER.debug('Closing cursor and cleaning %s', fd) try: cursor.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.debug('Error closing the cursor: %s', error) self._cleanup_fd(fd) # If the cleanup callback exists, remove it if self._cleanup_callback: self._ioloop.remove_timeout(self._cleanup_callback) # Create a new cleanup callback to clean the pool of idle connections self._cleanup_callback = self._ioloop.add_timeout( self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) def _cleanup_fd(self, fd): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. :param int fd: The fd # to cleanup """ self._ioloop.remove_handler(fd) if fd in self._connections: try: self._pool_manager.free(self.pid, self._connections[fd]) except pool.ConnectionNotFoundError: pass self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd] def _incr_exceptions(self, conn): """Increment the number of exceptions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).exceptions += 1 def _incr_executions(self, conn): """Increment the number of executions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).executions += 1 def _on_io_events(self, fd=None, _events=None): """Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised """ if fd not in self._connections: LOGGER.warning('Received IO event for non-existing connection') return self._poll_connection(fd) def _poll_connection(self, fd): """Check with psycopg2 to see what action to take. If the state is POLL_OK, we should have a pending callback for that fd. :param int fd: The socket fd for the postgresql connection """ try: state = self._connections[fd].poll() except (OSError, socket.error) as error: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.OperationalError('Connection error (%s)' % error) ) except (psycopg2.Error, psycopg2.Warning) as error: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception(error) else: if state == extensions.POLL_OK: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_result(True) elif state == extensions.POLL_WRITE: self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE) elif state == extensions.POLL_READ: self._ioloop.update_handler(fd, ioloop.IOLoop.READ) elif state == extensions.POLL_ERROR: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.Error('Poll Error')) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. :param dict kwargs: Keyword connection args :rtype: psycopg2.extensions.connection """ kwargs['async'] = True return psycopg2.connect(**kwargs) <MSG> Dont close when cleaning up (all the time) — add counters <DFF> @@ -295,7 +295,7 @@ class TornadoSession(session.Session): """ if cf.exception(): - self._cleanup_fd(fd) + self._cleanup_fd(fd, True) future.set_exception(cf.exception()) else: @@ -430,7 +430,7 @@ class TornadoSession(session.Session): self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) - def _cleanup_fd(self, fd): + def _cleanup_fd(self, fd, close=False): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. @@ -443,7 +443,8 @@ class TornadoSession(session.Session): self._pool_manager.free(self.pid, self._connections[fd]) except pool.ConnectionNotFoundError: pass - self._connections[fd].close() + if close: + self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd]
4
Dont close when cleaning up (all the time) — add counters
3
.py
py
bsd-3-clause
gmr/queries
1645
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<3'] else: install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setuptools.setup( name='queries', version='2.1.0', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy', maintainer_email='[email protected]', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Topic :: Software Development :: Libraries'] setup(name='queries', version='1.6.1', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]", 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Update history and version for release of 1.7.0 <DFF> @@ -30,7 +30,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.6.1', + version='1.7.0', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]",
1
Update history and version for release of 1.7.0
1
.py
py
bsd-3-clause
gmr/queries
1646
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<3'] else: install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setuptools.setup( name='queries', version='2.1.0', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy', maintainer_email='[email protected]', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Topic :: Software Development :: Libraries'] setup(name='queries', version='1.6.1', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]", 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Update history and version for release of 1.7.0 <DFF> @@ -30,7 +30,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.6.1', + version='1.7.0', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]",
1
Update history and version for release of 1.7.0
1
.py
py
bsd-3-clause
gmr/queries
1647
<NME> tornado_session_tests.py <BEF> """ Tests for functionality in the tornado_session module """ import unittest import mock # Out of order import to ensure psycopg2cffi is registered from queries import pool, tornado_session from psycopg2 import extras from tornado import concurrent, gen, ioloop, testing class ResultsTests(unittest.TestCase): def setUp(self): self.cursor = mock.Mock() self.fd = 10 self.cleanup = mock.Mock() self.obj = tornado_session.Results(self.cursor, self.cleanup, self.fd) def test_cursor_is_assigned(self): self.assertEqual(self.obj.cursor, self.cursor) def test_fd_is_assigned(self): self.assertEqual(self.obj._fd, self.fd) def test_cleanup_is_assigned(self): self.assertEqual(self.obj._cleanup, self.cleanup) @gen.coroutine def test_free_invokes_cleanup(self): yield self.obj.free() self.cleanup.assert_called_once_with(self.cursor, self.fd) class SessionInitTests(unittest.TestCase): def setUp(self): self.obj = tornado_session.TornadoSession() def test_creates_empty_callback_dict(self): self.assertDictEqual(self.obj._futures, {}) def test_creates_empty_connections_dict(self): self.assertDictEqual(self.obj._connections, {}) def test_sets_default_cursor_factory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_sets_tornado_ioloop_instance(self): self.assertEqual(self.obj._ioloop, ioloop.IOLoop.instance()) def test_sets_poolmananger_instance(self): self.assertEqual(self.obj._pool_manager, pool.PoolManager.instance()) def test_sets_uri(self): self.assertEqual(self.obj._uri, tornado_session.session.DEFAULT_URI) def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) def test_connection_is_none(self): self.assertIsNone(self.obj.connection) def test_cursor_is_none(self): self.assertIsNone(self.obj.cursor) class SessionConnectTests(testing.AsyncTestCase): def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) class SessionTests(testing.AsyncTestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') @mock.patch('queries.utils.uri_to_kwargs') def setUp(self, uri_to_kwargs, register_uuid, register_type, connect): super(SessionTests, self).setUp() self.conn = mock.Mock() self.conn.autocommit = False self.conn.closed = False self.conn.cursor = mock.Mock() self.conn.fileno = mock.Mock(return_value=True) self.conn.isexecuting = mock.Mock(return_value=False) self.conn.reset = mock.Mock() self.conn.status = psycopg2.extensions.STATUS_BEGIN self.psycopg2_connect = connect self.psycopg2_register_type = register_type self.psycopg2_register_uuid = register_uuid self.uri_to_kwargs = uri_to_kwargs self.uri_to_kwargs.return_value = {'host': 'localhost', 'port': 5432, 'user': 'foo', 'password': 'bar', 'dbname': 'foo'} @testing.gen_test def test_callproc_invokes_execute(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() cursor = mock.Mock() cursor.close = mock.Mock() self.obj._exec_cleanup(cursor, 14) cursor.close.assert_called_once_with() def test_exec_cleanup_frees_connection(self): with mock.patch.object(self.obj._pool_manager, 'free') as pm_free: with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = conn = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) pm_free.assert_called_once_with(self.obj.pid, conn) def test_exec_cleanup_remove_handler_invoked(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) result = yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) self.obj._exec_cleanup(mock.Mock(), 14) rh.assert_called_once_with(14) def test_exec_removes_connection(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._connections) def test_exec_removes_future(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._futures[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._futures) def test_pool_manager_add_failures_are_propagated(self): futures = [] def add_future(future, callback): futures.append((future, callback)) obj = tornado_session.TornadoSession() obj._ioloop = mock.Mock() obj._ioloop.add_future = add_future future = concurrent.Future() with mock.patch.object(obj._pool_manager, 'add') as add_method: add_method.side_effect = pool.PoolFullError(mock.Mock()) obj._create_connection(future) self.assertEqual(len(futures), 1) connected_future, callback = futures.pop() connected_future.set_result(True) callback(connected_future) self.assertIs(future.exception(), add_method.side_effect) class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_callproc_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) @testing.gen_test def test_query_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) """ @testing.gen_test def test_query_error_key_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) @testing.gen_test def test_query_error_index_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): r = yield obj.query('SELECT * FROM foo WHERE bar=%s', []) """ <MSG> Add additional TornadoSession tests Add coverage of TornadoSession._connect <DFF> @@ -74,37 +74,61 @@ class SessionInitTests(unittest.TestCase): def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) + def test_connection_is_none(self): + self.assertIsNone(self.obj.connection) -class SessionTests(testing.AsyncTestCase): + def test_cursor_is_none(self): + self.assertIsNone(self.obj.cursor) - @mock.patch('psycopg2.connect') - @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_uuid') - @mock.patch('queries.utils.uri_to_kwargs') - def setUp(self, uri_to_kwargs, register_uuid, register_type, connect): - super(SessionTests, self).setUp() +class SessionConnectTests(testing.AsyncTestCase): + def setUp(self): + super(SessionConnectTests, self).setUp() self.conn = mock.Mock() - self.conn.autocommit = False - self.conn.closed = False - self.conn.cursor = mock.Mock() - - self.conn.fileno = mock.Mock(return_value=True) - self.conn.isexecuting = mock.Mock(return_value=False) - self.conn.reset = mock.Mock() - self.conn.status = psycopg2.extensions.STATUS_BEGIN - - self.psycopg2_connect = connect - self.psycopg2_register_type = register_type - self.psycopg2_register_uuid = register_uuid - - self.uri_to_kwargs = uri_to_kwargs - self.uri_to_kwargs.return_value = {'host': 'localhost', - 'port': 5432, - 'user': 'foo', - 'password': 'bar', - 'dbname': 'foo'} + self.conn.fileno = mock.Mock(return_value=10) + self.obj = tornado_session.TornadoSession(io_loop=self.io_loop) + + def create_connection(future): + future.set_result(self.conn) + + self.obj._create_connection = create_connection + + @testing.gen_test + def test_connect_returns_new_connection(self): + conn = yield self.obj._connect() + self.assertEqual(conn, self.conn) + + @testing.gen_test + def test_connect_returns_pooled_connection(self): + conn = yield self.obj._connect() + self.obj._pool_manager.add(self.obj.pid, conn) + second_result = yield self.obj._connect() + self.assertEqual(second_result, conn) + + @testing.gen_test + def test_connect_gets_pooled_connection(self): + conn = yield self.obj._connect() + self.obj._pool_manager.add(self.obj.pid, conn) + with mock.patch.object(self.obj._pool_manager, 'get') as get: + with mock.patch.object(self.io_loop, 'add_handler') as add_handler: + second_result = yield self.obj._connect() + get.assert_called_once_with(self.obj.pid, self.obj) + + @testing.gen_test + def test_connect_pooled_connection_invokes_add_handler(self): + conn = yield self.obj._connect() + self.obj._pool_manager.add(self.obj.pid, conn) + with mock.patch.object(self.obj._pool_manager, 'get') as get: + get.return_value = self.conn + with mock.patch.object(self.io_loop, 'add_handler') as add_handler: + second_result = yield self.obj._connect() + add_handler.assert_called_once_with(self.conn.fileno(), + self.obj._on_io_events, + ioloop.IOLoop.WRITE) + + +class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_callproc_invokes_execute(self): @@ -127,7 +151,3 @@ class SessionTests(testing.AsyncTestCase): obj = tornado_session.TornadoSession(io_loop=self.io_loop) result = yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) - - - -
50
Add additional TornadoSession tests
30
.py
py
bsd-3-clause
gmr/queries
1648
<NME> tornado_session_tests.py <BEF> """ Tests for functionality in the tornado_session module """ import unittest import mock # Out of order import to ensure psycopg2cffi is registered from queries import pool, tornado_session from psycopg2 import extras from tornado import concurrent, gen, ioloop, testing class ResultsTests(unittest.TestCase): def setUp(self): self.cursor = mock.Mock() self.fd = 10 self.cleanup = mock.Mock() self.obj = tornado_session.Results(self.cursor, self.cleanup, self.fd) def test_cursor_is_assigned(self): self.assertEqual(self.obj.cursor, self.cursor) def test_fd_is_assigned(self): self.assertEqual(self.obj._fd, self.fd) def test_cleanup_is_assigned(self): self.assertEqual(self.obj._cleanup, self.cleanup) @gen.coroutine def test_free_invokes_cleanup(self): yield self.obj.free() self.cleanup.assert_called_once_with(self.cursor, self.fd) class SessionInitTests(unittest.TestCase): def setUp(self): self.obj = tornado_session.TornadoSession() def test_creates_empty_callback_dict(self): self.assertDictEqual(self.obj._futures, {}) def test_creates_empty_connections_dict(self): self.assertDictEqual(self.obj._connections, {}) def test_sets_default_cursor_factory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_sets_tornado_ioloop_instance(self): self.assertEqual(self.obj._ioloop, ioloop.IOLoop.instance()) def test_sets_poolmananger_instance(self): self.assertEqual(self.obj._pool_manager, pool.PoolManager.instance()) def test_sets_uri(self): self.assertEqual(self.obj._uri, tornado_session.session.DEFAULT_URI) def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) def test_connection_is_none(self): self.assertIsNone(self.obj.connection) def test_cursor_is_none(self): self.assertIsNone(self.obj.cursor) class SessionConnectTests(testing.AsyncTestCase): def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) class SessionTests(testing.AsyncTestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') @mock.patch('queries.utils.uri_to_kwargs') def setUp(self, uri_to_kwargs, register_uuid, register_type, connect): super(SessionTests, self).setUp() self.conn = mock.Mock() self.conn.autocommit = False self.conn.closed = False self.conn.cursor = mock.Mock() self.conn.fileno = mock.Mock(return_value=True) self.conn.isexecuting = mock.Mock(return_value=False) self.conn.reset = mock.Mock() self.conn.status = psycopg2.extensions.STATUS_BEGIN self.psycopg2_connect = connect self.psycopg2_register_type = register_type self.psycopg2_register_uuid = register_uuid self.uri_to_kwargs = uri_to_kwargs self.uri_to_kwargs.return_value = {'host': 'localhost', 'port': 5432, 'user': 'foo', 'password': 'bar', 'dbname': 'foo'} @testing.gen_test def test_callproc_invokes_execute(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() cursor = mock.Mock() cursor.close = mock.Mock() self.obj._exec_cleanup(cursor, 14) cursor.close.assert_called_once_with() def test_exec_cleanup_frees_connection(self): with mock.patch.object(self.obj._pool_manager, 'free') as pm_free: with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = conn = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) pm_free.assert_called_once_with(self.obj.pid, conn) def test_exec_cleanup_remove_handler_invoked(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) result = yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) self.obj._exec_cleanup(mock.Mock(), 14) rh.assert_called_once_with(14) def test_exec_removes_connection(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._connections) def test_exec_removes_future(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._futures[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._futures) def test_pool_manager_add_failures_are_propagated(self): futures = [] def add_future(future, callback): futures.append((future, callback)) obj = tornado_session.TornadoSession() obj._ioloop = mock.Mock() obj._ioloop.add_future = add_future future = concurrent.Future() with mock.patch.object(obj._pool_manager, 'add') as add_method: add_method.side_effect = pool.PoolFullError(mock.Mock()) obj._create_connection(future) self.assertEqual(len(futures), 1) connected_future, callback = futures.pop() connected_future.set_result(True) callback(connected_future) self.assertIs(future.exception(), add_method.side_effect) class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_callproc_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) @testing.gen_test def test_query_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) """ @testing.gen_test def test_query_error_key_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) @testing.gen_test def test_query_error_index_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): r = yield obj.query('SELECT * FROM foo WHERE bar=%s', []) """ <MSG> Add additional TornadoSession tests Add coverage of TornadoSession._connect <DFF> @@ -74,37 +74,61 @@ class SessionInitTests(unittest.TestCase): def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) + def test_connection_is_none(self): + self.assertIsNone(self.obj.connection) -class SessionTests(testing.AsyncTestCase): + def test_cursor_is_none(self): + self.assertIsNone(self.obj.cursor) - @mock.patch('psycopg2.connect') - @mock.patch('psycopg2.extensions.register_type') - @mock.patch('psycopg2.extras.register_uuid') - @mock.patch('queries.utils.uri_to_kwargs') - def setUp(self, uri_to_kwargs, register_uuid, register_type, connect): - super(SessionTests, self).setUp() +class SessionConnectTests(testing.AsyncTestCase): + def setUp(self): + super(SessionConnectTests, self).setUp() self.conn = mock.Mock() - self.conn.autocommit = False - self.conn.closed = False - self.conn.cursor = mock.Mock() - - self.conn.fileno = mock.Mock(return_value=True) - self.conn.isexecuting = mock.Mock(return_value=False) - self.conn.reset = mock.Mock() - self.conn.status = psycopg2.extensions.STATUS_BEGIN - - self.psycopg2_connect = connect - self.psycopg2_register_type = register_type - self.psycopg2_register_uuid = register_uuid - - self.uri_to_kwargs = uri_to_kwargs - self.uri_to_kwargs.return_value = {'host': 'localhost', - 'port': 5432, - 'user': 'foo', - 'password': 'bar', - 'dbname': 'foo'} + self.conn.fileno = mock.Mock(return_value=10) + self.obj = tornado_session.TornadoSession(io_loop=self.io_loop) + + def create_connection(future): + future.set_result(self.conn) + + self.obj._create_connection = create_connection + + @testing.gen_test + def test_connect_returns_new_connection(self): + conn = yield self.obj._connect() + self.assertEqual(conn, self.conn) + + @testing.gen_test + def test_connect_returns_pooled_connection(self): + conn = yield self.obj._connect() + self.obj._pool_manager.add(self.obj.pid, conn) + second_result = yield self.obj._connect() + self.assertEqual(second_result, conn) + + @testing.gen_test + def test_connect_gets_pooled_connection(self): + conn = yield self.obj._connect() + self.obj._pool_manager.add(self.obj.pid, conn) + with mock.patch.object(self.obj._pool_manager, 'get') as get: + with mock.patch.object(self.io_loop, 'add_handler') as add_handler: + second_result = yield self.obj._connect() + get.assert_called_once_with(self.obj.pid, self.obj) + + @testing.gen_test + def test_connect_pooled_connection_invokes_add_handler(self): + conn = yield self.obj._connect() + self.obj._pool_manager.add(self.obj.pid, conn) + with mock.patch.object(self.obj._pool_manager, 'get') as get: + get.return_value = self.conn + with mock.patch.object(self.io_loop, 'add_handler') as add_handler: + second_result = yield self.obj._connect() + add_handler.assert_called_once_with(self.conn.fileno(), + self.obj._on_io_events, + ioloop.IOLoop.WRITE) + + +class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_callproc_invokes_execute(self): @@ -127,7 +151,3 @@ class SessionTests(testing.AsyncTestCase): obj = tornado_session.TornadoSession(io_loop=self.io_loop) result = yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) - - - -
50
Add additional TornadoSession tests
30
.py
py
bsd-3-clause
gmr/queries
1649
<NME> results.py <BEF> """ query or callproc Results """ import logging import psycopg2 LOGGER = logging.getLogger(__name__) class Results(object): """The :py:class:`Results` class contains the results returned from :py:meth:`Session.query <queries.Session.query>` and :py:meth:`Session.callproc <queries.Session.callproc>`. It is able to act as an iterator and provides many different methods for accessing the information about and results from a query. :param psycopg2.extensions.cursor cursor: The cursor for the results """ def __init__(self, cursor): self.cursor = cursor def __getitem__(self, item): """Fetch an individual row from the result set :rtype: mixed :raises: IndexError """ try: self.cursor.scroll(item, 'absolute') except psycopg2.ProgrammingError: raise IndexError('No such row') else: return self.cursor.fetchone() def __iter__(self): """Iterate through the result set :rtype: mixed """ if not self.cursor.rowcount: raise StopIteration self._rewind() for row in self.cursor: yield row def __len__(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount if self.cursor.rowcount >= 0 else 0 def __nonzero__(self): return bool(self.cursor.rowcount) def __bool__(self): return self.__nonzero__() def __repr__(self): return '<queries.%s rows=%s>' % (self.__class__.__name__, len(self)) def as_dict(self): """Return a single row result as a dictionary. If the results contain multiple rows, a :py:class:`ValueError` will be raised. :return: dict :raises: ValueError """ if not self.cursor.rowcount: return {} self._rewind() if self.cursor.rowcount == 1: return dict(self.cursor.fetchone()) else: raise ValueError('More than one row') def count(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount def free(self): """Used in asynchronous sessions for freeing results and their locked connections. """ LOGGER.debug('Invoking synchronous free has no effect') def items(self): """Return all of the rows that are in the result set. :rtype: list """ if not self.cursor.rowcount: return [] self.cursor.scroll(0, 'absolute') return self.cursor.fetchall() @property def rownumber(self): """Return the current offset of the result set :rtype: int """ return self.cursor.rownumber @property def query(self): """Return a read-only value of the query that was submitted to PostgreSQL. :rtype: str """ return self.cursor.query @property def status(self): """Return the status message returned by PostgreSQL after the query was executed. :rtype: str """ return self.cursor.statusmessage def _rewind(self): """Rewind the cursor to the first row""" self.cursor.scroll(0, 'absolute') <MSG> Merge pull request #31 from nvllsvm/iterfix Update generator for Python 3.7 <DFF> @@ -41,12 +41,10 @@ class Results(object): :rtype: mixed """ - if not self.cursor.rowcount: - raise StopIteration - - self._rewind() - for row in self.cursor: - yield row + if self.cursor.rowcount: + self._rewind() + for row in self.cursor: + yield row def __len__(self): """Return the number of rows that were returned from the query
4
Merge pull request #31 from nvllsvm/iterfix
6
.py
py
bsd-3-clause
gmr/queries
1650
<NME> results.py <BEF> """ query or callproc Results """ import logging import psycopg2 LOGGER = logging.getLogger(__name__) class Results(object): """The :py:class:`Results` class contains the results returned from :py:meth:`Session.query <queries.Session.query>` and :py:meth:`Session.callproc <queries.Session.callproc>`. It is able to act as an iterator and provides many different methods for accessing the information about and results from a query. :param psycopg2.extensions.cursor cursor: The cursor for the results """ def __init__(self, cursor): self.cursor = cursor def __getitem__(self, item): """Fetch an individual row from the result set :rtype: mixed :raises: IndexError """ try: self.cursor.scroll(item, 'absolute') except psycopg2.ProgrammingError: raise IndexError('No such row') else: return self.cursor.fetchone() def __iter__(self): """Iterate through the result set :rtype: mixed """ if not self.cursor.rowcount: raise StopIteration self._rewind() for row in self.cursor: yield row def __len__(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount if self.cursor.rowcount >= 0 else 0 def __nonzero__(self): return bool(self.cursor.rowcount) def __bool__(self): return self.__nonzero__() def __repr__(self): return '<queries.%s rows=%s>' % (self.__class__.__name__, len(self)) def as_dict(self): """Return a single row result as a dictionary. If the results contain multiple rows, a :py:class:`ValueError` will be raised. :return: dict :raises: ValueError """ if not self.cursor.rowcount: return {} self._rewind() if self.cursor.rowcount == 1: return dict(self.cursor.fetchone()) else: raise ValueError('More than one row') def count(self): """Return the number of rows that were returned from the query :rtype: int """ return self.cursor.rowcount def free(self): """Used in asynchronous sessions for freeing results and their locked connections. """ LOGGER.debug('Invoking synchronous free has no effect') def items(self): """Return all of the rows that are in the result set. :rtype: list """ if not self.cursor.rowcount: return [] self.cursor.scroll(0, 'absolute') return self.cursor.fetchall() @property def rownumber(self): """Return the current offset of the result set :rtype: int """ return self.cursor.rownumber @property def query(self): """Return a read-only value of the query that was submitted to PostgreSQL. :rtype: str """ return self.cursor.query @property def status(self): """Return the status message returned by PostgreSQL after the query was executed. :rtype: str """ return self.cursor.statusmessage def _rewind(self): """Rewind the cursor to the first row""" self.cursor.scroll(0, 'absolute') <MSG> Merge pull request #31 from nvllsvm/iterfix Update generator for Python 3.7 <DFF> @@ -41,12 +41,10 @@ class Results(object): :rtype: mixed """ - if not self.cursor.rowcount: - raise StopIteration - - self._rewind() - for row in self.cursor: - yield row + if self.cursor.rowcount: + self._rewind() + for row in self.cursor: + yield row def __len__(self): """Return the number of rows that were returned from the query
4
Merge pull request #31 from nvllsvm/iterfix
6
.py
py
bsd-3-clause
gmr/queries
1651
<NME> tornado_session_tests.py <BEF> """ Tests for functionality in the tornado_session module """ import unittest import mock # Out of order import to ensure psycopg2cffi is registered from queries import pool, tornado_session from psycopg2 import extras from tornado import concurrent, gen, ioloop, testing class ResultsTests(unittest.TestCase): def setUp(self): self.cursor = mock.Mock() self.fd = 10 self.cleanup = mock.Mock() self.obj = tornado_session.Results(self.cursor, self.cleanup, self.fd) def test_cursor_is_assigned(self): self.assertEqual(self.obj.cursor, self.cursor) def test_fd_is_assigned(self): self.assertEqual(self.obj._fd, self.fd) def test_cleanup_is_assigned(self): self.assertEqual(self.obj._cleanup, self.cleanup) @gen.coroutine def test_free_invokes_cleanup(self): yield self.obj.free() self.cleanup.assert_called_once_with(self.cursor, self.fd) class SessionInitTests(unittest.TestCase): def setUp(self): self.obj = tornado_session.TornadoSession() def test_creates_empty_callback_dict(self): self.assertDictEqual(self.obj._futures, {}) def test_creates_empty_connections_dict(self): self.assertDictEqual(self.obj._connections, {}) def test_sets_default_cursor_factory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_sets_tornado_ioloop_instance(self): self.assertEqual(self.obj._ioloop, ioloop.IOLoop.instance()) def test_sets_poolmananger_instance(self): self.assertEqual(self.obj._pool_manager, pool.PoolManager.instance()) def test_sets_uri(self): self.assertEqual(self.obj._uri, tornado_session.session.DEFAULT_URI) def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) def test_connection_is_none(self): self.assertIsNone(self.obj.connection) def test_cursor_is_none(self): self.assertIsNone(self.obj.cursor) class SessionConnectTests(testing.AsyncTestCase): def setUp(self): super(SessionConnectTests, self).setUp() self.conn = mock.Mock() self.conn.fileno = mock.Mock(return_value=10) self.obj = tornado_session.TornadoSession(io_loop=self.io_loop) def create_connection(future): future.set_result(self.conn) self.obj._create_connection = create_connection @testing.gen_test def test_connect_returns_new_connection(self): conn = yield self.obj._connect() self.assertEqual(conn, self.conn) @testing.gen_test def test_connect_returns_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) second_result = yield self.obj._connect() self.assertEqual(second_result, conn) @testing.gen_test def test_connect_gets_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: with mock.patch.object(self.io_loop, 'add_handler'): yield self.obj._connect() get.assert_called_once_with(self.obj.pid, self.obj) @testing.gen_test def test_connect_pooled_connection_invokes_add_handler(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: get.return_value = self.conn with mock.patch.object(self.io_loop, 'add_handler') as add_handler: yield self.obj._connect() add_handler.assert_called_once_with(self.conn.fileno(), self.obj._on_io_events, ioloop.IOLoop.WRITE) def test_psycopg2_connect_invokes_psycopg2_connect(self): with mock.patch('psycopg2.connect') as connect: self.obj._psycopg2_connect({}) connect.assert_called_once_with(**{'async': True}) def test_on_io_events_returns_if_fd_not_present(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_not_called() def test_on_io_events_calls_poll_connection(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._connections[1337] = True self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_called_once_with(1337) def test_exec_cleanup_closes_cursor(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() cursor = mock.Mock() cursor.close = mock.Mock() self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_called_once_with(1337) class SessionPublicMethodTests(testing.AsyncTestCase): add_method.side_effect = pool.PoolFullError(mock.Mock()) obj._create_connection(future) self.assertEqual(len(futures), 1) connected_future, callback = futures.pop() connected_future.set_result(True) callback(connected_future) self.assertIs(future.exception(), add_method.side_effect) class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_callproc_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) @testing.gen_test def test_query_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) """ @testing.gen_test def test_query_error_key_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) @testing.gen_test def test_query_error_index_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): r = yield obj.query('SELECT * FROM foo WHERE bar=%s', []) """ <MSG> Add additional test coverage <DFF> @@ -140,6 +140,44 @@ class SessionConnectTests(testing.AsyncTestCase): self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_called_once_with(1337) + def test_exec_cleanup_closes_cursor(self): + with mock.patch.object(self.obj._pool_manager, 'free'): + with mock.patch.object(self.obj._ioloop, 'remove_handler'): + self.obj._connections[14] = mock.Mock() + cursor = mock.Mock() + cursor.close = mock.Mock() + self.obj._exec_cleanup(cursor, 14) + cursor.close.assert_called_once_with() + + def test_exec_cleanup_frees_connection(self): + with mock.patch.object(self.obj._pool_manager, 'free') as pm_free: + with mock.patch.object(self.obj._ioloop, 'remove_handler'): + self.obj._connections[14] = conn = mock.Mock() + self.obj._exec_cleanup(mock.Mock(), 14) + pm_free.assert_called_once_with(self.obj.pid, conn) + + def test_exec_cleanup_frees_connection(self): + with mock.patch.object(self.obj._pool_manager, 'free'): + with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh: + self.obj._connections[14] = mock.Mock() + self.obj._exec_cleanup(mock.Mock(), 14) + rh.assert_called_once_with(14) + + def test_exec_removes_connection(self): + with mock.patch.object(self.obj._pool_manager, 'free'): + with mock.patch.object(self.obj._ioloop, 'remove_handler'): + self.obj._connections[14] = mock.Mock() + self.obj._exec_cleanup(mock.Mock(), 14) + self.assertNotIn(14, self.obj._connections) + + def test_exec_removes_future(self): + with mock.patch.object(self.obj._pool_manager, 'free'): + with mock.patch.object(self.obj._ioloop, 'remove_handler'): + self.obj._connections[14] = mock.Mock() + self.obj._futures[14] = mock.Mock() + self.obj._exec_cleanup(mock.Mock(), 14) + self.assertNotIn(14, self.obj._futures) + class SessionPublicMethodTests(testing.AsyncTestCase):
38
Add additional test coverage
0
.py
py
bsd-3-clause
gmr/queries
1652
<NME> tornado_session_tests.py <BEF> """ Tests for functionality in the tornado_session module """ import unittest import mock # Out of order import to ensure psycopg2cffi is registered from queries import pool, tornado_session from psycopg2 import extras from tornado import concurrent, gen, ioloop, testing class ResultsTests(unittest.TestCase): def setUp(self): self.cursor = mock.Mock() self.fd = 10 self.cleanup = mock.Mock() self.obj = tornado_session.Results(self.cursor, self.cleanup, self.fd) def test_cursor_is_assigned(self): self.assertEqual(self.obj.cursor, self.cursor) def test_fd_is_assigned(self): self.assertEqual(self.obj._fd, self.fd) def test_cleanup_is_assigned(self): self.assertEqual(self.obj._cleanup, self.cleanup) @gen.coroutine def test_free_invokes_cleanup(self): yield self.obj.free() self.cleanup.assert_called_once_with(self.cursor, self.fd) class SessionInitTests(unittest.TestCase): def setUp(self): self.obj = tornado_session.TornadoSession() def test_creates_empty_callback_dict(self): self.assertDictEqual(self.obj._futures, {}) def test_creates_empty_connections_dict(self): self.assertDictEqual(self.obj._connections, {}) def test_sets_default_cursor_factory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_sets_tornado_ioloop_instance(self): self.assertEqual(self.obj._ioloop, ioloop.IOLoop.instance()) def test_sets_poolmananger_instance(self): self.assertEqual(self.obj._pool_manager, pool.PoolManager.instance()) def test_sets_uri(self): self.assertEqual(self.obj._uri, tornado_session.session.DEFAULT_URI) def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) def test_connection_is_none(self): self.assertIsNone(self.obj.connection) def test_cursor_is_none(self): self.assertIsNone(self.obj.cursor) class SessionConnectTests(testing.AsyncTestCase): def setUp(self): super(SessionConnectTests, self).setUp() self.conn = mock.Mock() self.conn.fileno = mock.Mock(return_value=10) self.obj = tornado_session.TornadoSession(io_loop=self.io_loop) def create_connection(future): future.set_result(self.conn) self.obj._create_connection = create_connection @testing.gen_test def test_connect_returns_new_connection(self): conn = yield self.obj._connect() self.assertEqual(conn, self.conn) @testing.gen_test def test_connect_returns_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) second_result = yield self.obj._connect() self.assertEqual(second_result, conn) @testing.gen_test def test_connect_gets_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: with mock.patch.object(self.io_loop, 'add_handler'): yield self.obj._connect() get.assert_called_once_with(self.obj.pid, self.obj) @testing.gen_test def test_connect_pooled_connection_invokes_add_handler(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: get.return_value = self.conn with mock.patch.object(self.io_loop, 'add_handler') as add_handler: yield self.obj._connect() add_handler.assert_called_once_with(self.conn.fileno(), self.obj._on_io_events, ioloop.IOLoop.WRITE) def test_psycopg2_connect_invokes_psycopg2_connect(self): with mock.patch('psycopg2.connect') as connect: self.obj._psycopg2_connect({}) connect.assert_called_once_with(**{'async': True}) def test_on_io_events_returns_if_fd_not_present(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_not_called() def test_on_io_events_calls_poll_connection(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._connections[1337] = True self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_called_once_with(1337) def test_exec_cleanup_closes_cursor(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() cursor = mock.Mock() cursor.close = mock.Mock() self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_called_once_with(1337) class SessionPublicMethodTests(testing.AsyncTestCase): add_method.side_effect = pool.PoolFullError(mock.Mock()) obj._create_connection(future) self.assertEqual(len(futures), 1) connected_future, callback = futures.pop() connected_future.set_result(True) callback(connected_future) self.assertIs(future.exception(), add_method.side_effect) class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_callproc_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) @testing.gen_test def test_query_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) """ @testing.gen_test def test_query_error_key_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) @testing.gen_test def test_query_error_index_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): r = yield obj.query('SELECT * FROM foo WHERE bar=%s', []) """ <MSG> Add additional test coverage <DFF> @@ -140,6 +140,44 @@ class SessionConnectTests(testing.AsyncTestCase): self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_called_once_with(1337) + def test_exec_cleanup_closes_cursor(self): + with mock.patch.object(self.obj._pool_manager, 'free'): + with mock.patch.object(self.obj._ioloop, 'remove_handler'): + self.obj._connections[14] = mock.Mock() + cursor = mock.Mock() + cursor.close = mock.Mock() + self.obj._exec_cleanup(cursor, 14) + cursor.close.assert_called_once_with() + + def test_exec_cleanup_frees_connection(self): + with mock.patch.object(self.obj._pool_manager, 'free') as pm_free: + with mock.patch.object(self.obj._ioloop, 'remove_handler'): + self.obj._connections[14] = conn = mock.Mock() + self.obj._exec_cleanup(mock.Mock(), 14) + pm_free.assert_called_once_with(self.obj.pid, conn) + + def test_exec_cleanup_frees_connection(self): + with mock.patch.object(self.obj._pool_manager, 'free'): + with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh: + self.obj._connections[14] = mock.Mock() + self.obj._exec_cleanup(mock.Mock(), 14) + rh.assert_called_once_with(14) + + def test_exec_removes_connection(self): + with mock.patch.object(self.obj._pool_manager, 'free'): + with mock.patch.object(self.obj._ioloop, 'remove_handler'): + self.obj._connections[14] = mock.Mock() + self.obj._exec_cleanup(mock.Mock(), 14) + self.assertNotIn(14, self.obj._connections) + + def test_exec_removes_future(self): + with mock.patch.object(self.obj._pool_manager, 'free'): + with mock.patch.object(self.obj._ioloop, 'remove_handler'): + self.obj._connections[14] = mock.Mock() + self.obj._futures[14] = mock.Mock() + self.obj._exec_cleanup(mock.Mock(), 14) + self.assertNotIn(14, self.obj._futures) + class SessionPublicMethodTests(testing.AsyncTestCase):
38
Add additional test coverage
0
.py
py
bsd-3-clause
gmr/queries
1653
<NME> session_tests.py <BEF> """ Tests for functionality in the session module """ import hashlib import logging import unittest import mock from psycopg2 import extras import psycopg2 # Out of order import to ensure psycopg2cffi is registered from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) class SessionTestCase(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def setUp(self, register_uuid, register_type, connect): self._connect = connect self._connect.reset = mock.Mock() self._reg_type = register_type self._reg_uuid = register_uuid self.uri = 'pgsql://[email protected]:5432/queries' self.conn.isexecuting = mock.Mock(return_value=False) self.conn.reset = mock.Mock() self.conn.status = psycopg2.extensions.STATUS_BEGIN def test_psycopg2_connection_invoked(self): """Ensure that psycopg2.connect was invoked""" self._connect.assert_called_once_with(self.uri) def test_psycopg2_register_uuid(self): """Ensure that the UUID extension was registered""" self._reg_uuid.assert_called_once_with(self.client._conn) def test_psycopg2_register_unicode_type(self): """Ensure that the UNICODE type was registered""" self._reg_type.assert_any_call(psycopg2.extensions.UNICODE, self.client._cursor) def test_psycopg2_register_unicode_array_type(self): """Ensure that the UNICODEARRAY type was registered""" self._reg_type.assert_any_call(psycopg2.extensions.UNICODEARRAY, self.client._cursor) def test_default_autocommit_value(self): """Connection should be autocommit by default""" def test_init_sets_cursorfactory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_init_gets_cursor(self): self.conn.cursor.assert_called_once_with( name=None, cursor_factory=extras.RealDictCursor) def test_init_sets_autocommit(self): self.assertTrue(self.conn.autocommit) def test_backend_pid_invokes_conn_backend_pid(self): self.conn.get_backend_pid = get_backend_pid = mock.Mock() LOGGER.debug('ValueL %s', self.obj.backend_pid) get_backend_pid.assert_called_once_with() def test_callproc_invokes_cursor_callproc(self): self.obj._cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.obj.callproc(*args) self.obj._cursor.callproc.assert_called_once_with(*args) def test_callproc_returns_results(self): self.obj._cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.assertIsInstance(self.obj.callproc(*args), results.Results) def test_close_raises_exception(self): self.obj._conn = None self.assertRaises(psycopg2.InterfaceError, self.obj.close) def test_close_removes_connection(self): self.obj.close() self.assertNotIn(self.conn, self.obj._pool_manager._pools[self.obj.pid]) cleanup.assert_called_once_with() @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_context_manager_creation(self, _reg_uuid, _reg_type): """Ensure context manager returns self""" with session.Session(self.uri) as conn: self.assertIsInstance(conn, session.Session) @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_context_manager_cleanup(self, _reg_uuid, _reg_type): """Ensure context manager cleans up after self""" with mock.patch('queries.session.Session._cleanup') as cleanup: with session.Session(self.uri): def test_notices_value(self): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_close_removes_from_cache(self, _reg_uuid, _reg_type, _connect): """Ensure connection removed from cache on close""" uri = 'pgsql://foo@bar:9999/baz' pgsql = session.Session(uri) def test_query_invokes_cursor_execute(self): self.obj._cursor.callproc = mock.Mock() args = ('SELECT * FROM foo', ['bar', 'baz']) @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_close_invokes_connection_close(self, _reg_uuid, _reg_type, connect): """Ensure close calls connection.close""" sess = session.Session('pgsql://foo@bar:9999/baz') close_mock = mock.Mock() def test_set_encoding_does_not_set_encoding_if_same(self): self.conn.encoding = 'UTF-8' self.conn.set_client_encoding = set_client_encoding = mock.Mock() @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_close_sets_conn_to_none(self, _reg_uuid, _reg_type, connect): """Ensure Session._conn is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() _connect=mock.Mock(), @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_close_sets_cursor_to_none(self, _reg_uuid, _reg_type, connect): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() self.assertIsNone(sess._cursor) @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_close_raises_when_closed(self, _reg_uuid, _reg_type, _conn): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() self.obj._autocommit(True) self.assertTrue(self.conn.autocommit) def test_cleanup_closes_cursor(self): self.obj._cursor.close = closeit = mock.Mock() self.conn = None self.obj._cleanup() closeit.assert_called_once_with() def test_cleanup_sets_cursor_to_none(self): self.obj._cursor.close = mock.Mock() self.conn = None self.obj._cleanup() self.assertIsNone(self.obj._cursor) def test_cleanup_frees_connection(self): with mock.patch.object(self.obj._pool_manager, 'free') as free: conn = self.obj._conn self.obj._cleanup() free.assert_called_once_with(self.obj.pid, conn) def test_cleanup_sets_connect_to_none(self): self.obj._cleanup() self.assertIsNone(self.obj._conn) def test_connect_invokes_pool_manager_get(self): with mock.patch.object(self.obj._pool_manager, 'get') as get: self.obj._connect() get.assert_called_once_with(self.obj.pid, self.obj) def test_connect_raises_noidleconnectionserror(self): with mock.patch.object(self.obj._pool_manager, 'get') as get: with mock.patch.object(self.obj._pool_manager, 'is_full') as full: get.side_effect = pool.NoIdleConnectionsError(self.obj.pid) full.return_value = True self.assertRaises(pool.NoIdleConnectionsError, self.obj._connect) def test_connect_invokes_uri_to_kwargs(self): self.uri_to_kwargs.assert_called_once_with(self.URI) def test_connect_returned_the_proper_value(self): self.assertEqual(self.obj.connection, self.conn) def test_status_is_ready_by_default(self): self.assertEqual(self.obj._status, self.obj.READY) def test_status_when_not_ready(self): self.conn.status = self.obj.SETUP self.assertEqual(self.obj._status, self.obj.SETUP) def test_get_named_cursor_sets_scrollable(self): result = self.obj._get_cursor(self.obj._conn, 'test1') self.assertTrue(result.scrollable) def test_get_named_cursor_sets_withhold(self): result = self.obj._get_cursor(self.obj._conn, 'test2') self.assertTrue(result.withhhold) @unittest.skipUnless(utils.PYPY, 'connection.reset is PYPY only behavior') def test_connection_reset_in_pypy(self): self.conn.reset.assert_called_once_with() <MSG> Fix tests <DFF> @@ -20,10 +20,12 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def setUp(self, register_uuid, register_type, connect): + def setUp(self, register_uuid, register_json, register_type, connect): self._connect = connect self._connect.reset = mock.Mock() + self._reg_json = register_json self._reg_type = register_type self._reg_uuid = register_uuid self.uri = 'pgsql://[email protected]:5432/queries' @@ -33,21 +35,26 @@ class SessionTests(unittest.TestCase): def test_psycopg2_connection_invoked(self): """Ensure that psycopg2.connect was invoked""" - self._connect.assert_called_once_with(self.uri) + expectation = {'user': 'postgres', + 'dbname': 'queries', + 'host': '127.0.0.1', + 'port': 5432, + 'password': None} + self._connect.assert_called_once_with(**expectation) def test_psycopg2_register_uuid(self): """Ensure that the UUID extension was registered""" - self._reg_uuid.assert_called_once_with(self.client._conn) + self._reg_uuid.assert_called_once_with(conn_or_curs=self.client._conn) def test_psycopg2_register_unicode_type(self): """Ensure that the UNICODE type was registered""" self._reg_type.assert_any_call(psycopg2.extensions.UNICODE, - self.client._cursor) + self.client._conn) def test_psycopg2_register_unicode_array_type(self): """Ensure that the UNICODEARRAY type was registered""" self._reg_type.assert_any_call(psycopg2.extensions.UNICODEARRAY, - self.client._cursor) + self.client._conn) def test_default_autocommit_value(self): """Connection should be autocommit by default""" @@ -89,15 +96,17 @@ class SessionTests(unittest.TestCase): cleanup.assert_called_once_with() @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_context_manager_creation(self, _reg_uuid, _reg_type): + def test_context_manager_creation(self, _uuid, _json, _type,): """Ensure context manager returns self""" with session.Session(self.uri) as conn: self.assertIsInstance(conn, session.Session) @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_context_manager_cleanup(self, _reg_uuid, _reg_type): + def test_context_manager_cleanup(self, _uuid, _json, _type,): """Ensure context manager cleans up after self""" with mock.patch('queries.session.Session._cleanup') as cleanup: with session.Session(self.uri): @@ -106,8 +115,9 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_removes_from_cache(self, _reg_uuid, _reg_type, _connect): + def test_close_removes_from_cache(self, _uuid, _json, _type, _connect): """Ensure connection removed from cache on close""" uri = 'pgsql://foo@bar:9999/baz' pgsql = session.Session(uri) @@ -117,8 +127,9 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_invokes_connection_close(self, _reg_uuid, _reg_type, connect): + def test_close_invokes_connection_close(self, _uuid, _json, _type, connect): """Ensure close calls connection.close""" sess = session.Session('pgsql://foo@bar:9999/baz') close_mock = mock.Mock() @@ -128,8 +139,9 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_sets_conn_to_none(self, _reg_uuid, _reg_type, connect): + def test_close_sets_conn_to_none(self, _uuid, _json, _type, connect): """Ensure Session._conn is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() @@ -137,17 +149,19 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_sets_cursor_to_none(self, _reg_uuid, _reg_type, connect): + def test_close_sets_cursor_to_none(self, _uuid, _json, _type, connect): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() self.assertIsNone(sess._cursor) @mock.patch('psycopg2.connect') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') - def test_close_raises_when_closed(self, _reg_uuid, _reg_type, _conn): + def test_close_raises_when_closed(self, _uuid, _json, _type, _conn): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close()
26
Fix tests
12
.py
py
bsd-3-clause
gmr/queries
1654
<NME> session_tests.py <BEF> """ Tests for functionality in the session module """ import hashlib import logging import unittest import mock from psycopg2 import extras import psycopg2 # Out of order import to ensure psycopg2cffi is registered from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) class SessionTestCase(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def setUp(self, register_uuid, register_type, connect): self._connect = connect self._connect.reset = mock.Mock() self._reg_type = register_type self._reg_uuid = register_uuid self.uri = 'pgsql://[email protected]:5432/queries' self.conn.isexecuting = mock.Mock(return_value=False) self.conn.reset = mock.Mock() self.conn.status = psycopg2.extensions.STATUS_BEGIN def test_psycopg2_connection_invoked(self): """Ensure that psycopg2.connect was invoked""" self._connect.assert_called_once_with(self.uri) def test_psycopg2_register_uuid(self): """Ensure that the UUID extension was registered""" self._reg_uuid.assert_called_once_with(self.client._conn) def test_psycopg2_register_unicode_type(self): """Ensure that the UNICODE type was registered""" self._reg_type.assert_any_call(psycopg2.extensions.UNICODE, self.client._cursor) def test_psycopg2_register_unicode_array_type(self): """Ensure that the UNICODEARRAY type was registered""" self._reg_type.assert_any_call(psycopg2.extensions.UNICODEARRAY, self.client._cursor) def test_default_autocommit_value(self): """Connection should be autocommit by default""" def test_init_sets_cursorfactory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_init_gets_cursor(self): self.conn.cursor.assert_called_once_with( name=None, cursor_factory=extras.RealDictCursor) def test_init_sets_autocommit(self): self.assertTrue(self.conn.autocommit) def test_backend_pid_invokes_conn_backend_pid(self): self.conn.get_backend_pid = get_backend_pid = mock.Mock() LOGGER.debug('ValueL %s', self.obj.backend_pid) get_backend_pid.assert_called_once_with() def test_callproc_invokes_cursor_callproc(self): self.obj._cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.obj.callproc(*args) self.obj._cursor.callproc.assert_called_once_with(*args) def test_callproc_returns_results(self): self.obj._cursor.callproc = mock.Mock() args = ('foo', ['bar', 'baz']) self.assertIsInstance(self.obj.callproc(*args), results.Results) def test_close_raises_exception(self): self.obj._conn = None self.assertRaises(psycopg2.InterfaceError, self.obj.close) def test_close_removes_connection(self): self.obj.close() self.assertNotIn(self.conn, self.obj._pool_manager._pools[self.obj.pid]) cleanup.assert_called_once_with() @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_context_manager_creation(self, _reg_uuid, _reg_type): """Ensure context manager returns self""" with session.Session(self.uri) as conn: self.assertIsInstance(conn, session.Session) @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_context_manager_cleanup(self, _reg_uuid, _reg_type): """Ensure context manager cleans up after self""" with mock.patch('queries.session.Session._cleanup') as cleanup: with session.Session(self.uri): def test_notices_value(self): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_close_removes_from_cache(self, _reg_uuid, _reg_type, _connect): """Ensure connection removed from cache on close""" uri = 'pgsql://foo@bar:9999/baz' pgsql = session.Session(uri) def test_query_invokes_cursor_execute(self): self.obj._cursor.callproc = mock.Mock() args = ('SELECT * FROM foo', ['bar', 'baz']) @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_close_invokes_connection_close(self, _reg_uuid, _reg_type, connect): """Ensure close calls connection.close""" sess = session.Session('pgsql://foo@bar:9999/baz') close_mock = mock.Mock() def test_set_encoding_does_not_set_encoding_if_same(self): self.conn.encoding = 'UTF-8' self.conn.set_client_encoding = set_client_encoding = mock.Mock() @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_close_sets_conn_to_none(self, _reg_uuid, _reg_type, connect): """Ensure Session._conn is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() _connect=mock.Mock(), @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_close_sets_cursor_to_none(self, _reg_uuid, _reg_type, connect): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() self.assertIsNone(sess._cursor) @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') def test_close_raises_when_closed(self, _reg_uuid, _reg_type, _conn): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() self.obj._autocommit(True) self.assertTrue(self.conn.autocommit) def test_cleanup_closes_cursor(self): self.obj._cursor.close = closeit = mock.Mock() self.conn = None self.obj._cleanup() closeit.assert_called_once_with() def test_cleanup_sets_cursor_to_none(self): self.obj._cursor.close = mock.Mock() self.conn = None self.obj._cleanup() self.assertIsNone(self.obj._cursor) def test_cleanup_frees_connection(self): with mock.patch.object(self.obj._pool_manager, 'free') as free: conn = self.obj._conn self.obj._cleanup() free.assert_called_once_with(self.obj.pid, conn) def test_cleanup_sets_connect_to_none(self): self.obj._cleanup() self.assertIsNone(self.obj._conn) def test_connect_invokes_pool_manager_get(self): with mock.patch.object(self.obj._pool_manager, 'get') as get: self.obj._connect() get.assert_called_once_with(self.obj.pid, self.obj) def test_connect_raises_noidleconnectionserror(self): with mock.patch.object(self.obj._pool_manager, 'get') as get: with mock.patch.object(self.obj._pool_manager, 'is_full') as full: get.side_effect = pool.NoIdleConnectionsError(self.obj.pid) full.return_value = True self.assertRaises(pool.NoIdleConnectionsError, self.obj._connect) def test_connect_invokes_uri_to_kwargs(self): self.uri_to_kwargs.assert_called_once_with(self.URI) def test_connect_returned_the_proper_value(self): self.assertEqual(self.obj.connection, self.conn) def test_status_is_ready_by_default(self): self.assertEqual(self.obj._status, self.obj.READY) def test_status_when_not_ready(self): self.conn.status = self.obj.SETUP self.assertEqual(self.obj._status, self.obj.SETUP) def test_get_named_cursor_sets_scrollable(self): result = self.obj._get_cursor(self.obj._conn, 'test1') self.assertTrue(result.scrollable) def test_get_named_cursor_sets_withhold(self): result = self.obj._get_cursor(self.obj._conn, 'test2') self.assertTrue(result.withhhold) @unittest.skipUnless(utils.PYPY, 'connection.reset is PYPY only behavior') def test_connection_reset_in_pypy(self): self.conn.reset.assert_called_once_with() <MSG> Fix tests <DFF> @@ -20,10 +20,12 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def setUp(self, register_uuid, register_type, connect): + def setUp(self, register_uuid, register_json, register_type, connect): self._connect = connect self._connect.reset = mock.Mock() + self._reg_json = register_json self._reg_type = register_type self._reg_uuid = register_uuid self.uri = 'pgsql://[email protected]:5432/queries' @@ -33,21 +35,26 @@ class SessionTests(unittest.TestCase): def test_psycopg2_connection_invoked(self): """Ensure that psycopg2.connect was invoked""" - self._connect.assert_called_once_with(self.uri) + expectation = {'user': 'postgres', + 'dbname': 'queries', + 'host': '127.0.0.1', + 'port': 5432, + 'password': None} + self._connect.assert_called_once_with(**expectation) def test_psycopg2_register_uuid(self): """Ensure that the UUID extension was registered""" - self._reg_uuid.assert_called_once_with(self.client._conn) + self._reg_uuid.assert_called_once_with(conn_or_curs=self.client._conn) def test_psycopg2_register_unicode_type(self): """Ensure that the UNICODE type was registered""" self._reg_type.assert_any_call(psycopg2.extensions.UNICODE, - self.client._cursor) + self.client._conn) def test_psycopg2_register_unicode_array_type(self): """Ensure that the UNICODEARRAY type was registered""" self._reg_type.assert_any_call(psycopg2.extensions.UNICODEARRAY, - self.client._cursor) + self.client._conn) def test_default_autocommit_value(self): """Connection should be autocommit by default""" @@ -89,15 +96,17 @@ class SessionTests(unittest.TestCase): cleanup.assert_called_once_with() @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_context_manager_creation(self, _reg_uuid, _reg_type): + def test_context_manager_creation(self, _uuid, _json, _type,): """Ensure context manager returns self""" with session.Session(self.uri) as conn: self.assertIsInstance(conn, session.Session) @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_context_manager_cleanup(self, _reg_uuid, _reg_type): + def test_context_manager_cleanup(self, _uuid, _json, _type,): """Ensure context manager cleans up after self""" with mock.patch('queries.session.Session._cleanup') as cleanup: with session.Session(self.uri): @@ -106,8 +115,9 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_removes_from_cache(self, _reg_uuid, _reg_type, _connect): + def test_close_removes_from_cache(self, _uuid, _json, _type, _connect): """Ensure connection removed from cache on close""" uri = 'pgsql://foo@bar:9999/baz' pgsql = session.Session(uri) @@ -117,8 +127,9 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_invokes_connection_close(self, _reg_uuid, _reg_type, connect): + def test_close_invokes_connection_close(self, _uuid, _json, _type, connect): """Ensure close calls connection.close""" sess = session.Session('pgsql://foo@bar:9999/baz') close_mock = mock.Mock() @@ -128,8 +139,9 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_sets_conn_to_none(self, _reg_uuid, _reg_type, connect): + def test_close_sets_conn_to_none(self, _uuid, _json, _type, connect): """Ensure Session._conn is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() @@ -137,17 +149,19 @@ class SessionTests(unittest.TestCase): @mock.patch('psycopg2.connect') @mock.patch('psycopg2.extensions.register_type') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extras.register_uuid') - def test_close_sets_cursor_to_none(self, _reg_uuid, _reg_type, connect): + def test_close_sets_cursor_to_none(self, _uuid, _json, _type, connect): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close() self.assertIsNone(sess._cursor) @mock.patch('psycopg2.connect') + @mock.patch('psycopg2.extras.register_json') @mock.patch('psycopg2.extensions.register_type') @mock.patch('psycopg2.extras.register_uuid') - def test_close_raises_when_closed(self, _reg_uuid, _reg_type, _conn): + def test_close_raises_when_closed(self, _uuid, _json, _type, _conn): """Ensure Session._cursor is None after close""" sess = session.Session('pgsql://foo@bar:9999/baz') sess.close()
26
Fix tests
12
.py
py
bsd-3-clause
gmr/queries
1655
<NME> session.rst <BEF> .. py:module:: queries.session Session API =========== The Session class allows for a unified (and simplified) view of interfacing with a PostgreSQL database server. Connection details are passed in as a PostgreSQL URI and connections are pooled by default, allowing for reuse of connections across modules in the Python runtime without having to pass around the object handle. While you can still access the raw psycopg2_ :py:class:`~psycopg2.extensions.connection` methods designed to simplify the interaction with PostgreSQL. For psycopg2_ functionality outside of what is exposed in Session, simply use the :py:meth:`queries.Session.connection` or :py:meth:`queries.Session.cursor` properties to gain access to either object just as you would in a program using psycopg2_ directly. psycopg2_ directly. Example Usage ------------- The following example connects to the ``postgres`` database on ``localhost`` as the ``postgres`` user and then queries a table, iterating over the results: .. code:: python import queries with queries.Session('postgresql://postgres@localhost/postgres') as session: for row in session.query('SELECT * FROM table'): print row Class Documentation ------------------- .. autoclass:: queries.Session :members: .. _psycopg2: https://pypi.python.org/pypi/psycopg2 <MSG> These are @property methods, set to :py:attr: <DFF> @@ -13,7 +13,7 @@ in how you use the :py:class:`queries.Session` object, there are convenience methods designed to simplify the interaction with PostgreSQL. For psycopg2_ functionality outside of what is exposed in Session, simply -use the :py:meth:`queries.Session.connection` or :py:meth:`queries.Session.cursor` +use the :py:attr:`queries.Session.connection` or :py:attr:`queries.Session.cursor` properties to gain access to either object just as you would in a program using psycopg2_ directly.
1
These are @property methods, set to :py:attr:
1
.rst
rst
bsd-3-clause
gmr/queries
1656
<NME> session.rst <BEF> .. py:module:: queries.session Session API =========== The Session class allows for a unified (and simplified) view of interfacing with a PostgreSQL database server. Connection details are passed in as a PostgreSQL URI and connections are pooled by default, allowing for reuse of connections across modules in the Python runtime without having to pass around the object handle. While you can still access the raw psycopg2_ :py:class:`~psycopg2.extensions.connection` methods designed to simplify the interaction with PostgreSQL. For psycopg2_ functionality outside of what is exposed in Session, simply use the :py:meth:`queries.Session.connection` or :py:meth:`queries.Session.cursor` properties to gain access to either object just as you would in a program using psycopg2_ directly. psycopg2_ directly. Example Usage ------------- The following example connects to the ``postgres`` database on ``localhost`` as the ``postgres`` user and then queries a table, iterating over the results: .. code:: python import queries with queries.Session('postgresql://postgres@localhost/postgres') as session: for row in session.query('SELECT * FROM table'): print row Class Documentation ------------------- .. autoclass:: queries.Session :members: .. _psycopg2: https://pypi.python.org/pypi/psycopg2 <MSG> These are @property methods, set to :py:attr: <DFF> @@ -13,7 +13,7 @@ in how you use the :py:class:`queries.Session` object, there are convenience methods designed to simplify the interaction with PostgreSQL. For psycopg2_ functionality outside of what is exposed in Session, simply -use the :py:meth:`queries.Session.connection` or :py:meth:`queries.Session.cursor` +use the :py:attr:`queries.Session.connection` or :py:attr:`queries.Session.cursor` properties to gain access to either object just as you would in a program using psycopg2_ directly.
1
These are @property methods, set to :py:attr:
1
.rst
rst
bsd-3-clause
gmr/queries
1657
<NME> __init__.py <BEF> """ Queries: PostgreSQL database access simplified Queries is an opinionated wrapper for interfacing with PostgreSQL that offers caching of connections and support for PyPy via psycopg2ct. The core `queries.Queries` class will automatically register support for UUIDs, Unicode and Unicode arrays. """ import logging import sys try: import psycopg2cffi import psycopg2cffi.extras # Import PyPy compatibility PYPY = False target = platform.python_implementation() if target == 'PyPy': from psycopg2ct import compat compat.register() PYPY = True # Add a Null logging handler to prevent logging output when un-configured try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): """Python 2.6 does not have a NullHandler""" def emit(self, record): # For ease of access to different cursor types from psycopg2.extras import DictCursor from psycopg2.extras import NamedTupleCursor from psycopg2.extras import RealDictCursor from psycopg2.extras import LoggingCursor from psycopg2.extras import MinTimeLoggingCursor # Expose exceptions so clients do not need to import psycopg2 too from psycopg2 import Warning from psycopg2 import Error from psycopg2 import DataError from psycopg2 import DatabaseError from psycopg2 import IntegrityError from psycopg2 import InterfaceError try: from queries.tornado_session import TornadoSession except ImportError: TornadoSession = None __version__ = '2.1.0' version = __version__ # Add a Null logging handler to prevent logging output when un-configured logging.getLogger('queries').addHandler(logging.NullHandler()) <MSG> Add a few things to ignore coverage checking for <DFF> @@ -17,7 +17,7 @@ import platform # Import PyPy compatibility PYPY = False target = platform.python_implementation() -if target == 'PyPy': +if target == 'PyPy': # pragma: no cover from psycopg2ct import compat compat.register() PYPY = True @@ -25,7 +25,7 @@ if target == 'PyPy': # Add a Null logging handler to prevent logging output when un-configured try: from logging import NullHandler -except ImportError: +except ImportError: # pragma: no cover class NullHandler(logging.Handler): """Python 2.6 does not have a NullHandler""" def emit(self, record): @@ -47,7 +47,7 @@ from queries.session import Session try: from queries.tornado_session import TornadoSession -except ImportError: +except ImportError: # pragma: no cover TornadoSession = None
3
Add a few things to ignore coverage checking for
3
.py
py
bsd-3-clause
gmr/queries
1658
<NME> __init__.py <BEF> """ Queries: PostgreSQL database access simplified Queries is an opinionated wrapper for interfacing with PostgreSQL that offers caching of connections and support for PyPy via psycopg2ct. The core `queries.Queries` class will automatically register support for UUIDs, Unicode and Unicode arrays. """ import logging import sys try: import psycopg2cffi import psycopg2cffi.extras # Import PyPy compatibility PYPY = False target = platform.python_implementation() if target == 'PyPy': from psycopg2ct import compat compat.register() PYPY = True # Add a Null logging handler to prevent logging output when un-configured try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): """Python 2.6 does not have a NullHandler""" def emit(self, record): # For ease of access to different cursor types from psycopg2.extras import DictCursor from psycopg2.extras import NamedTupleCursor from psycopg2.extras import RealDictCursor from psycopg2.extras import LoggingCursor from psycopg2.extras import MinTimeLoggingCursor # Expose exceptions so clients do not need to import psycopg2 too from psycopg2 import Warning from psycopg2 import Error from psycopg2 import DataError from psycopg2 import DatabaseError from psycopg2 import IntegrityError from psycopg2 import InterfaceError try: from queries.tornado_session import TornadoSession except ImportError: TornadoSession = None __version__ = '2.1.0' version = __version__ # Add a Null logging handler to prevent logging output when un-configured logging.getLogger('queries').addHandler(logging.NullHandler()) <MSG> Add a few things to ignore coverage checking for <DFF> @@ -17,7 +17,7 @@ import platform # Import PyPy compatibility PYPY = False target = platform.python_implementation() -if target == 'PyPy': +if target == 'PyPy': # pragma: no cover from psycopg2ct import compat compat.register() PYPY = True @@ -25,7 +25,7 @@ if target == 'PyPy': # Add a Null logging handler to prevent logging output when un-configured try: from logging import NullHandler -except ImportError: +except ImportError: # pragma: no cover class NullHandler(logging.Handler): """Python 2.6 does not have a NullHandler""" def emit(self, record): @@ -47,7 +47,7 @@ from queries.session import Session try: from queries.tornado_session import TornadoSession -except ImportError: +except ImportError: # pragma: no cover TornadoSession = None
3
Add a few things to ignore coverage checking for
3
.py
py
bsd-3-clause
gmr/queries
1659
<NME> utils.py <BEF> """ Utility functions for access to OS level info and URI parsing """ import collections import getpass import logging import os import platform # All systems do not support pwd module try: import pwd except ImportError: pwd = None # Python 2 & 3 compatibility try: from urllib import parse as _urlparse except ImportError: import urlparse as _urlparse try: from urllib.parse import unquote except ImportError: from urllib import unquote LOGGER = logging.getLogger(__name__) PARSED = collections.namedtuple('Parsed', 'scheme,netloc,path,params,query,fragment,' 'username,password,hostname,port') PYPY = platform.python_implementation().lower() == 'pypy' KEYWORDS = ['connect_timeout', 'client_encoding', 'options', 'application_name', 'fallback_application_name', 'keepalives', 'keepalives_idle', 'keepalives_interval', 'keepalives_count', 'sslmode', 'requiressl', 'sslcompression', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl', 'requirepeer', 'krbsrvname', 'gsslib', 'service'] def get_current_user(): """Return the current username for the logged in user :rtype: str """ if pwd is None: return getpass.getuser() else: try: return pwd.getpwuid(os.getuid())[0] except KeyError as error: LOGGER.error('Could not get logged-in user: %s', error) def parse_qs(query_string): """Return the parsed query string in a python2/3 agnostic fashion :param str query_string: The URI query string :rtype: dict """ return _urlparse.parse_qs(query_string) def uri(host='localhost', port=5432, dbname='postgres', user='postgres', password=None): """Return a PostgreSQL connection URI for the specified values. :param str host: Host to connect to :param int port: Port to connect on :param str dbname: The database name :param str user: User to connect as :param str password: The password to use, None for no password :return str: The PostgreSQL connection URI """ value = 'http%s' % url[5:] if url[:5] == 'postgresql' else url parsed = _urlparse.urlparse(value) hostname = parsed.hostname if parsed.hostname else '' return PARSED(parsed.scheme.replace('http', 'postgresql'), parsed.netloc, parsed.path, parsed.params, parsed.query, parsed.fragment, parsed.username, parsed.password, password = unquote(parsed.password) if parsed.password else None kwargs = {'host': parsed.hostname, 'port': parsed.port, 'dbname': parsed.path[1:] or default_user, 'user': parsed.username or default_user, 'password': password} values = parse_qs(parsed.query) if 'host' in values: kwargs['host'] = values['host'][0] for k in [k for k in values if k in KEYWORDS]: kwargs[k] = values[k][0] if len(values[k]) == 1 else values[k] try: if kwargs[k].isdigit(): kwargs[k] = int(kwargs[k]) except AttributeError: pass return kwargs def urlparse(url): """Parse the URL in a Python2/3 independent fashion. :param str url: The URL to parse :rtype: Parsed """ value = 'http%s' % url[5:] if url[:5] == 'postgresql' else url parsed = _urlparse.urlparse(value) path, query = parsed.path, parsed.query hostname = parsed.hostname if parsed.hostname else '' return PARSED(parsed.scheme.replace('http', 'postgresql'), parsed.netloc, path, parsed.params, query, parsed.fragment, parsed.username, parsed.password, hostname.replace('%2F', '/').replace('%2f', '/'), parsed.port) <MSG> Fix query parameters parsing in Python 2.6 <DFF> @@ -92,12 +92,19 @@ def urlparse(url): """ value = 'http%s' % url[5:] if url[:5] == 'postgresql' else url parsed = _urlparse.urlparse(value) + + # Python 2.6 hack + if not parsed.query and '?' in parsed.path: + path, query = parsed.path.split('?') + else: + path, query = parsed.path, parsed.query + hostname = parsed.hostname if parsed.hostname else '' return PARSED(parsed.scheme.replace('http', 'postgresql'), parsed.netloc, - parsed.path, + path, parsed.params, - parsed.query, + query, parsed.fragment, parsed.username, parsed.password,
9
Fix query parameters parsing in Python 2.6
2
.py
py
bsd-3-clause
gmr/queries
1660
<NME> utils.py <BEF> """ Utility functions for access to OS level info and URI parsing """ import collections import getpass import logging import os import platform # All systems do not support pwd module try: import pwd except ImportError: pwd = None # Python 2 & 3 compatibility try: from urllib import parse as _urlparse except ImportError: import urlparse as _urlparse try: from urllib.parse import unquote except ImportError: from urllib import unquote LOGGER = logging.getLogger(__name__) PARSED = collections.namedtuple('Parsed', 'scheme,netloc,path,params,query,fragment,' 'username,password,hostname,port') PYPY = platform.python_implementation().lower() == 'pypy' KEYWORDS = ['connect_timeout', 'client_encoding', 'options', 'application_name', 'fallback_application_name', 'keepalives', 'keepalives_idle', 'keepalives_interval', 'keepalives_count', 'sslmode', 'requiressl', 'sslcompression', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl', 'requirepeer', 'krbsrvname', 'gsslib', 'service'] def get_current_user(): """Return the current username for the logged in user :rtype: str """ if pwd is None: return getpass.getuser() else: try: return pwd.getpwuid(os.getuid())[0] except KeyError as error: LOGGER.error('Could not get logged-in user: %s', error) def parse_qs(query_string): """Return the parsed query string in a python2/3 agnostic fashion :param str query_string: The URI query string :rtype: dict """ return _urlparse.parse_qs(query_string) def uri(host='localhost', port=5432, dbname='postgres', user='postgres', password=None): """Return a PostgreSQL connection URI for the specified values. :param str host: Host to connect to :param int port: Port to connect on :param str dbname: The database name :param str user: User to connect as :param str password: The password to use, None for no password :return str: The PostgreSQL connection URI """ value = 'http%s' % url[5:] if url[:5] == 'postgresql' else url parsed = _urlparse.urlparse(value) hostname = parsed.hostname if parsed.hostname else '' return PARSED(parsed.scheme.replace('http', 'postgresql'), parsed.netloc, parsed.path, parsed.params, parsed.query, parsed.fragment, parsed.username, parsed.password, password = unquote(parsed.password) if parsed.password else None kwargs = {'host': parsed.hostname, 'port': parsed.port, 'dbname': parsed.path[1:] or default_user, 'user': parsed.username or default_user, 'password': password} values = parse_qs(parsed.query) if 'host' in values: kwargs['host'] = values['host'][0] for k in [k for k in values if k in KEYWORDS]: kwargs[k] = values[k][0] if len(values[k]) == 1 else values[k] try: if kwargs[k].isdigit(): kwargs[k] = int(kwargs[k]) except AttributeError: pass return kwargs def urlparse(url): """Parse the URL in a Python2/3 independent fashion. :param str url: The URL to parse :rtype: Parsed """ value = 'http%s' % url[5:] if url[:5] == 'postgresql' else url parsed = _urlparse.urlparse(value) path, query = parsed.path, parsed.query hostname = parsed.hostname if parsed.hostname else '' return PARSED(parsed.scheme.replace('http', 'postgresql'), parsed.netloc, path, parsed.params, query, parsed.fragment, parsed.username, parsed.password, hostname.replace('%2F', '/').replace('%2f', '/'), parsed.port) <MSG> Fix query parameters parsing in Python 2.6 <DFF> @@ -92,12 +92,19 @@ def urlparse(url): """ value = 'http%s' % url[5:] if url[:5] == 'postgresql' else url parsed = _urlparse.urlparse(value) + + # Python 2.6 hack + if not parsed.query and '?' in parsed.path: + path, query = parsed.path.split('?') + else: + path, query = parsed.path, parsed.query + hostname = parsed.hostname if parsed.hostname else '' return PARSED(parsed.scheme.replace('http', 'postgresql'), parsed.netloc, - parsed.path, + path, parsed.params, - parsed.query, + query, parsed.fragment, parsed.username, parsed.password,
9
Fix query parameters parsing in Python 2.6
2
.py
py
bsd-3-clause
gmr/queries
1661
<NME> tornado_session.py <BEF> """ Tornado Session Adapter Use Queries asynchronously within the Tornado framework. Example Use: .. code:: python class NameListHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession(pool_max_size=60) @gen.coroutine def get(self): data = yield self.session.query('SELECT * FROM names') if data: self.finish({'names': data.items()}) data.free() else: self.set_status(500, 'Error querying the data') """ import logging import socket import warnings from tornado import concurrent, ioloop from psycopg2 import extras, extensions import psycopg2 from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) DEFAULT_MAX_POOL_SIZE = 25 class Results(results.Results): """A TornadoSession specific :py:class:`queries.Results` class that adds the :py:meth:`Results.free <queries.tornado_session.Results.free>` method. The :py:meth:`Results.free <queries.tornado_session.Results.free>` method **must** be called to free the connection that the results were generated on. `Results` objects that are not freed will cause the connections to remain locked and your application will eventually run out of connections in the pool. The following examples illustrate the various behaviors that the ::py:class:`queries.Results <queries.tornado_session.Requests>` class implements: **Using Results as an Iterator** .. code:: python results = yield session.query('SELECT * FROM foo') for row in results print row results.free() **Accessing an individual row by index** .. code:: python results = yield session.query('SELECT * FROM foo') print results[1] # Access the second row of the results results.free() **Casting single row results as a dict** .. code:: python results = yield session.query('SELECT * FROM foo LIMIT 1') print results.as_dict() results.free() **Checking to see if a query was successful** .. code:: python sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'" results = yield session.query(sql) if results: print 'Success' results.free() **Checking the number of rows by using len(Results)** .. code:: python results = yield session.query('SELECT * FROM foo') print '%i rows' % len(results) results.free() """ def __init__(self, cursor, cleanup, fd): self.cursor = cursor self._cleanup = cleanup self._fd = fd self._freed = False def free(self): """Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or the connection will not be able to be reused by other asynchronous requests. """ self._freed = True self._cleanup(self.cursor, self._fd) def __del__(self): if not self._freed: LOGGER.warning('Auto-freeing result on deletion') requests. """ yield self._cleanup(self.cursor, self._fd) class TornadoSession(session.Session): Utilizes connection pooling to ensure that multiple concurrent asynchronous queries do not block each other. Heavily trafficked services will require a higher ``max_pool_size`` to allow for greater connection concurrency. :py:meth:`TornadoSession.query <queries.TornadoSession.query>` and :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` must call :py:meth:`Results.free <queries.tornado_session.Results.free>` :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use """ def __init__(self, uri=session.DEFAULT_URI, cursor_factory=extras.RealDictCursor, pool_idle_ttl=pool.DEFAULT_IDLE_TTL, pool_max_size=DEFAULT_MAX_POOL_SIZE, io_loop=None): """Connect to a PostgreSQL server using the module wide connection and set the isolation level. :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use :param tornado.ioloop.IOLoop io_loop: IOLoop instance to use """ self._connections = dict() self._cleanup_callback = None self._cursor_factory = cursor_factory self._futures = dict() self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() self._pool_max_size = pool_max_size self._pool_idle_ttl = pool_idle_ttl self._uri = uri self._ensure_pool_exists() def _ensure_pool_exists(self): """Create the pool in the pool manager if it does not exist.""" if self.pid not in self._pool_manager: self._pool_manager.create(self.pid, self._pool_idle_ttl, self._pool_max_size, self._ioloop.time) @property def connection(self): """Do not use this directly with Tornado applications :return: """ return None @property def cursor(self): return None def callproc(self, name, args=None): """Call a stored procedure asynchronously on the server, passing in the arguments to be passed to the stored procedure, yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str name: The stored procedure name :param list args: An optional list of procedure arguments :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('callproc', name, args) def query(self, sql, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('execute', sql, parameters) def validate(self): """Validate the session can connect or has open connections to PostgreSQL. As of ``1.10.3`` .. deprecated:: 1.10.3 As of 1.10.3, this method only warns about Deprecation :rtype: bool """ warnings.warn( 'All functionality removed from this method', DeprecationWarning) def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool if possible, or by creating the new connection. :rtype: psycopg2.extensions.connection :raises: pool.NoIdleConnectionsError """ future = concurrent.Future() # Attempt to get a cached connection from the connection pool try: connection = self._pool_manager.get(self.pid, self) self._connections[connection.fileno()] = connection future.set_result(connection) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) except pool.NoIdleConnectionsError: self._create_connection(future) return future def _create_connection(self, future): """Create a new PostgreSQL connection :param tornado.concurrent.Future future: future for new conn result """ LOGGER.debug('Creating a new connection for %s', self.pid) # Create a new PostgreSQL connection kwargs = utils.uri_to_kwargs(self._uri) try: connection = self._psycopg2_connect(kwargs) except (psycopg2.Error, OSError, socket.error) as error: future.set_exception(error) return # Add the connection for use in _poll_connection fd = connection.fileno() self._connections[fd] = connection def on_connected(cf): """Invoked by the IOLoop when the future is complete for the connection :param Future cf: The future for the initial connection """ if cf.exception(): self._cleanup_fd(fd, True) future.set_exception(cf.exception()) else: try: # Add the connection to the pool LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) except (ValueError, pool.PoolException) as err: LOGGER.exception('Failed to add %r to the pool', self.pid) self._cleanup_fd(fd) future.set_exception(err) return self._pool_manager.lock(self.pid, connection, self) # Added in because psycopg2cffi connects and leaves the # connection in a weird state: consts.STATUS_DATESTYLE, # returning from Connection._setup without setting the state # as const.STATUS_OK if utils.PYPY: connection.status = extensions.STATUS_READY # Register the custom data types self._register_unicode(connection) self._register_uuid(connection) # Set the future result future.set_result(connection) # Add a future that fires once connected self._futures[fd] = concurrent.Future() self._ioloop.add_future(self._futures[fd], on_connected) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) def _execute(self, method, query, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. This function reduces duplicate code for callproc and query by getting the class attribute for the method passed in as the function to call. :param str method: The method attribute to use :param str query: The SQL statement or Stored Procedure name :param list|dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ future = concurrent.Future() def on_connected(cf): """Invoked by the future returned by self._connect""" if cf.exception(): future.set_exception(cf.exception()) return # Get the psycopg2 connection object and cursor conn = cf.result() cursor = self._get_cursor(conn) def completed(qf): """Invoked by the IOLoop when the future has completed""" if qf.exception(): self._incr_exceptions(conn) err = qf.exception() LOGGER.debug('Cleaning cursor due to exception: %r', err) self._exec_cleanup(cursor, conn.fileno()) future.set_exception(err) else: self._incr_executions(conn) value = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(value) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.Future() # Add the future to the IOLoop self._ioloop.add_future(self._futures[conn.fileno()], completed) # Get the cursor, execute the query func = getattr(cursor, method) try: func(query, parameters) except Exception as error: future.set_exception(error) # Ensure the pool exists for the connection self._ensure_pool_exists() # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. :param psycopg2.extensions.cursor cursor: The cursor to close :param int fd: The connection file descriptor """ LOGGER.debug('Closing cursor and cleaning %s', fd) try: cursor.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.debug('Error closing the cursor: %s', error) self._cleanup_fd(fd) # If the cleanup callback exists, remove it if self._cleanup_callback: self._ioloop.remove_timeout(self._cleanup_callback) # Create a new cleanup callback to clean the pool of idle connections self._cleanup_callback = self._ioloop.add_timeout( self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) def _cleanup_fd(self, fd, close=False): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. :param int fd: The fd # to cleanup """ self._ioloop.remove_handler(fd) if fd in self._connections: try: self._pool_manager.free(self.pid, self._connections[fd]) except pool.ConnectionNotFoundError: pass if close: self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd] def _incr_exceptions(self, conn): """Increment the number of exceptions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).exceptions += 1 def _incr_executions(self, conn): """Increment the number of executions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).executions += 1 def _on_io_events(self, fd=None, _events=None): """Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised """ if fd not in self._connections: LOGGER.warning('Received IO event for non-existing connection') return self._poll_connection(fd) def _poll_connection(self, fd): """Check with psycopg2 to see what action to take. If the state is POLL_OK, we should have a pending callback for that fd. :param int fd: The socket fd for the postgresql connection """ try: state = self._connections[fd].poll() except (OSError, socket.error) as error: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.OperationalError('Connection error (%s)' % error) ) except (psycopg2.Error, psycopg2.Warning) as error: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception(error) else: if state == extensions.POLL_OK: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_result(True) elif state == extensions.POLL_WRITE: self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE) elif state == extensions.POLL_READ: self._ioloop.update_handler(fd, ioloop.IOLoop.READ) elif state == extensions.POLL_ERROR: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.Error('Poll Error')) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. :param dict kwargs: Keyword connection args :rtype: psycopg2.extensions.connection """ kwargs['async'] = True return psycopg2.connect(**kwargs) <MSG> Update tornado_session.py _cleanup is not a coroutine and therefore shouldn't be yielded <DFF> @@ -118,7 +118,7 @@ class Results(results.Results): requests. """ - yield self._cleanup(self.cursor, self._fd) + self._cleanup(self.cursor, self._fd) class TornadoSession(session.Session):
1
Update tornado_session.py
1
.py
py
bsd-3-clause
gmr/queries
1662
<NME> tornado_session.py <BEF> """ Tornado Session Adapter Use Queries asynchronously within the Tornado framework. Example Use: .. code:: python class NameListHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession(pool_max_size=60) @gen.coroutine def get(self): data = yield self.session.query('SELECT * FROM names') if data: self.finish({'names': data.items()}) data.free() else: self.set_status(500, 'Error querying the data') """ import logging import socket import warnings from tornado import concurrent, ioloop from psycopg2 import extras, extensions import psycopg2 from queries import pool, results, session, utils LOGGER = logging.getLogger(__name__) DEFAULT_MAX_POOL_SIZE = 25 class Results(results.Results): """A TornadoSession specific :py:class:`queries.Results` class that adds the :py:meth:`Results.free <queries.tornado_session.Results.free>` method. The :py:meth:`Results.free <queries.tornado_session.Results.free>` method **must** be called to free the connection that the results were generated on. `Results` objects that are not freed will cause the connections to remain locked and your application will eventually run out of connections in the pool. The following examples illustrate the various behaviors that the ::py:class:`queries.Results <queries.tornado_session.Requests>` class implements: **Using Results as an Iterator** .. code:: python results = yield session.query('SELECT * FROM foo') for row in results print row results.free() **Accessing an individual row by index** .. code:: python results = yield session.query('SELECT * FROM foo') print results[1] # Access the second row of the results results.free() **Casting single row results as a dict** .. code:: python results = yield session.query('SELECT * FROM foo LIMIT 1') print results.as_dict() results.free() **Checking to see if a query was successful** .. code:: python sql = "UPDATE foo SET bar='baz' WHERE qux='corgie'" results = yield session.query(sql) if results: print 'Success' results.free() **Checking the number of rows by using len(Results)** .. code:: python results = yield session.query('SELECT * FROM foo') print '%i rows' % len(results) results.free() """ def __init__(self, cursor, cleanup, fd): self.cursor = cursor self._cleanup = cleanup self._fd = fd self._freed = False def free(self): """Release the results and connection lock from the TornadoSession object. This **must** be called after you finish processing the results from :py:meth:`TornadoSession.query <queries.TornadoSession.query>` or :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or the connection will not be able to be reused by other asynchronous requests. """ self._freed = True self._cleanup(self.cursor, self._fd) def __del__(self): if not self._freed: LOGGER.warning('Auto-freeing result on deletion') requests. """ yield self._cleanup(self.cursor, self._fd) class TornadoSession(session.Session): Utilizes connection pooling to ensure that multiple concurrent asynchronous queries do not block each other. Heavily trafficked services will require a higher ``max_pool_size`` to allow for greater connection concurrency. :py:meth:`TornadoSession.query <queries.TornadoSession.query>` and :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` must call :py:meth:`Results.free <queries.tornado_session.Results.free>` :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use """ def __init__(self, uri=session.DEFAULT_URI, cursor_factory=extras.RealDictCursor, pool_idle_ttl=pool.DEFAULT_IDLE_TTL, pool_max_size=DEFAULT_MAX_POOL_SIZE, io_loop=None): """Connect to a PostgreSQL server using the module wide connection and set the isolation level. :param str uri: PostgreSQL connection URI :param psycopg2.extensions.cursor: The cursor type to use :param int pool_idle_ttl: How long idle pools keep connections open :param int pool_max_size: The maximum size of the pool to use :param tornado.ioloop.IOLoop io_loop: IOLoop instance to use """ self._connections = dict() self._cleanup_callback = None self._cursor_factory = cursor_factory self._futures = dict() self._ioloop = io_loop or ioloop.IOLoop.current() self._pool_manager = pool.PoolManager.instance() self._pool_max_size = pool_max_size self._pool_idle_ttl = pool_idle_ttl self._uri = uri self._ensure_pool_exists() def _ensure_pool_exists(self): """Create the pool in the pool manager if it does not exist.""" if self.pid not in self._pool_manager: self._pool_manager.create(self.pid, self._pool_idle_ttl, self._pool_max_size, self._ioloop.time) @property def connection(self): """Do not use this directly with Tornado applications :return: """ return None @property def cursor(self): return None def callproc(self, name, args=None): """Call a stored procedure asynchronously on the server, passing in the arguments to be passed to the stored procedure, yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str name: The stored procedure name :param list args: An optional list of procedure arguments :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('callproc', name, args) def query(self, sql, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. You **must** free the results that are returned by this method to unlock the connection used to perform the query. Failure to do so will cause your Tornado application to run out of connections. :param str sql: The SQL statement :param dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ return self._execute('execute', sql, parameters) def validate(self): """Validate the session can connect or has open connections to PostgreSQL. As of ``1.10.3`` .. deprecated:: 1.10.3 As of 1.10.3, this method only warns about Deprecation :rtype: bool """ warnings.warn( 'All functionality removed from this method', DeprecationWarning) def _connect(self): """Connect to PostgreSQL, either by reusing a connection from the pool if possible, or by creating the new connection. :rtype: psycopg2.extensions.connection :raises: pool.NoIdleConnectionsError """ future = concurrent.Future() # Attempt to get a cached connection from the connection pool try: connection = self._pool_manager.get(self.pid, self) self._connections[connection.fileno()] = connection future.set_result(connection) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) except pool.NoIdleConnectionsError: self._create_connection(future) return future def _create_connection(self, future): """Create a new PostgreSQL connection :param tornado.concurrent.Future future: future for new conn result """ LOGGER.debug('Creating a new connection for %s', self.pid) # Create a new PostgreSQL connection kwargs = utils.uri_to_kwargs(self._uri) try: connection = self._psycopg2_connect(kwargs) except (psycopg2.Error, OSError, socket.error) as error: future.set_exception(error) return # Add the connection for use in _poll_connection fd = connection.fileno() self._connections[fd] = connection def on_connected(cf): """Invoked by the IOLoop when the future is complete for the connection :param Future cf: The future for the initial connection """ if cf.exception(): self._cleanup_fd(fd, True) future.set_exception(cf.exception()) else: try: # Add the connection to the pool LOGGER.debug('Connection established for %s', self.pid) self._pool_manager.add(self.pid, connection) except (ValueError, pool.PoolException) as err: LOGGER.exception('Failed to add %r to the pool', self.pid) self._cleanup_fd(fd) future.set_exception(err) return self._pool_manager.lock(self.pid, connection, self) # Added in because psycopg2cffi connects and leaves the # connection in a weird state: consts.STATUS_DATESTYLE, # returning from Connection._setup without setting the state # as const.STATUS_OK if utils.PYPY: connection.status = extensions.STATUS_READY # Register the custom data types self._register_unicode(connection) self._register_uuid(connection) # Set the future result future.set_result(connection) # Add a future that fires once connected self._futures[fd] = concurrent.Future() self._ioloop.add_future(self._futures[fd], on_connected) # Add the connection to the IOLoop self._ioloop.add_handler(connection.fileno(), self._on_io_events, ioloop.IOLoop.WRITE) def _execute(self, method, query, parameters=None): """Issue a query asynchronously on the server, mogrifying the parameters against the sql statement and yielding the results as a :py:class:`Results <queries.tornado_session.Results>` object. This function reduces duplicate code for callproc and query by getting the class attribute for the method passed in as the function to call. :param str method: The method attribute to use :param str query: The SQL statement or Stored Procedure name :param list|dict parameters: A dictionary of query parameters :rtype: Results :raises: queries.DataError :raises: queries.DatabaseError :raises: queries.IntegrityError :raises: queries.InternalError :raises: queries.InterfaceError :raises: queries.NotSupportedError :raises: queries.OperationalError :raises: queries.ProgrammingError """ future = concurrent.Future() def on_connected(cf): """Invoked by the future returned by self._connect""" if cf.exception(): future.set_exception(cf.exception()) return # Get the psycopg2 connection object and cursor conn = cf.result() cursor = self._get_cursor(conn) def completed(qf): """Invoked by the IOLoop when the future has completed""" if qf.exception(): self._incr_exceptions(conn) err = qf.exception() LOGGER.debug('Cleaning cursor due to exception: %r', err) self._exec_cleanup(cursor, conn.fileno()) future.set_exception(err) else: self._incr_executions(conn) value = Results(cursor, self._exec_cleanup, conn.fileno()) future.set_result(value) # Setup a callback to wait on the query result self._futures[conn.fileno()] = concurrent.Future() # Add the future to the IOLoop self._ioloop.add_future(self._futures[conn.fileno()], completed) # Get the cursor, execute the query func = getattr(cursor, method) try: func(query, parameters) except Exception as error: future.set_exception(error) # Ensure the pool exists for the connection self._ensure_pool_exists() # Grab a connection to PostgreSQL self._ioloop.add_future(self._connect(), on_connected) # Return the future for the query result return future def _exec_cleanup(self, cursor, fd): """Close the cursor, remove any references to the fd in internal state and remove the fd from the ioloop. :param psycopg2.extensions.cursor cursor: The cursor to close :param int fd: The connection file descriptor """ LOGGER.debug('Closing cursor and cleaning %s', fd) try: cursor.close() except (psycopg2.Error, psycopg2.Warning) as error: LOGGER.debug('Error closing the cursor: %s', error) self._cleanup_fd(fd) # If the cleanup callback exists, remove it if self._cleanup_callback: self._ioloop.remove_timeout(self._cleanup_callback) # Create a new cleanup callback to clean the pool of idle connections self._cleanup_callback = self._ioloop.add_timeout( self._ioloop.time() + self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid) def _cleanup_fd(self, fd, close=False): """Ensure the socket socket is removed from the IOLoop, the connection stack, and futures stack. :param int fd: The fd # to cleanup """ self._ioloop.remove_handler(fd) if fd in self._connections: try: self._pool_manager.free(self.pid, self._connections[fd]) except pool.ConnectionNotFoundError: pass if close: self._connections[fd].close() del self._connections[fd] if fd in self._futures: del self._futures[fd] def _incr_exceptions(self, conn): """Increment the number of exceptions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).exceptions += 1 def _incr_executions(self, conn): """Increment the number of executions for the current connection. :param psycopg2.extensions.connection conn: the psycopg2 connection """ self._pool_manager.get_connection(self.pid, conn).executions += 1 def _on_io_events(self, fd=None, _events=None): """Invoked by Tornado's IOLoop when there are events for the fd :param int fd: The file descriptor for the event :param int _events: The events raised """ if fd not in self._connections: LOGGER.warning('Received IO event for non-existing connection') return self._poll_connection(fd) def _poll_connection(self, fd): """Check with psycopg2 to see what action to take. If the state is POLL_OK, we should have a pending callback for that fd. :param int fd: The socket fd for the postgresql connection """ try: state = self._connections[fd].poll() except (OSError, socket.error) as error: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.OperationalError('Connection error (%s)' % error) ) except (psycopg2.Error, psycopg2.Warning) as error: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception(error) else: if state == extensions.POLL_OK: if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_result(True) elif state == extensions.POLL_WRITE: self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE) elif state == extensions.POLL_READ: self._ioloop.update_handler(fd, ioloop.IOLoop.READ) elif state == extensions.POLL_ERROR: self._ioloop.remove_handler(fd) if fd in self._futures and not self._futures[fd].done(): self._futures[fd].set_exception( psycopg2.Error('Poll Error')) def _psycopg2_connect(self, kwargs): """Return a psycopg2 connection for the specified kwargs. Extend for use in async session adapters. :param dict kwargs: Keyword connection args :rtype: psycopg2.extensions.connection """ kwargs['async'] = True return psycopg2.connect(**kwargs) <MSG> Update tornado_session.py _cleanup is not a coroutine and therefore shouldn't be yielded <DFF> @@ -118,7 +118,7 @@ class Results(results.Results): requests. """ - yield self._cleanup(self.cursor, self._fd) + self._cleanup(self.cursor, self._fd) class TornadoSession(session.Session):
1
Update tornado_session.py
1
.py
py
bsd-3-clause
gmr/queries
1663
<NME> simple-tornado.py <BEF> import logging import queries from tornado import gen, ioloop, web class ExampleHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession() @gen.coroutine def get(self): try: result = yield self.session.query('SELECT * FROM names') except queries.OperationalError as error: logging.error('Error connecting to the database: %s', error) raise web.HTTPError(503) self.finish({'data': result.items()}) result.free() application = web.Application([ (r'/', ExampleHandler), ]) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) application.listen(8888) ioloop.IOLoop.instance().start() <MSG> Add more functionality to the example <DFF> @@ -1,30 +1,46 @@ +import datetime import logging + +from queries import pool import queries from tornado import gen, ioloop, web class ExampleHandler(web.RequestHandler): - def initialize(self): - self.session = queries.TornadoSession() + SQL = 'SELECT * FROM pg_stat_activity' @gen.coroutine def get(self): try: - result = yield self.session.query('SELECT * FROM names') + result = yield self.application.session.query(self.SQL) except queries.OperationalError as error: logging.error('Error connecting to the database: %s', error) raise web.HTTPError(503) - self.finish({'data': result.items()}) + rows = [] + for row in result.items(): + row = dict([(k, v.isoformat() + if isinstance(v, datetime.datetime) else v) + for k, v in row.items()]) + rows.append(row) result.free() + self.finish({'pg_stat_activity': rows}) + + +class ReportHandler(web.RequestHandler): + @gen.coroutine + def get(self): + self.finish(pool.PoolManager.report()) -application = web.Application([ - (r'/', ExampleHandler), -]) if __name__ == '__main__': - logging.basicConfig(level=logging.INFO) - application.listen(8888) + logging.basicConfig(level=logging.DEBUG) + application = web.Application([ + (r'/', ExampleHandler), + (r'/report', ReportHandler) + ], debug=True) + application.session = queries.TornadoSession() + application.listen(8000) ioloop.IOLoop.instance().start()
25
Add more functionality to the example
9
.py
py
bsd-3-clause
gmr/queries
1664
<NME> simple-tornado.py <BEF> import logging import queries from tornado import gen, ioloop, web class ExampleHandler(web.RequestHandler): def initialize(self): self.session = queries.TornadoSession() @gen.coroutine def get(self): try: result = yield self.session.query('SELECT * FROM names') except queries.OperationalError as error: logging.error('Error connecting to the database: %s', error) raise web.HTTPError(503) self.finish({'data': result.items()}) result.free() application = web.Application([ (r'/', ExampleHandler), ]) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) application.listen(8888) ioloop.IOLoop.instance().start() <MSG> Add more functionality to the example <DFF> @@ -1,30 +1,46 @@ +import datetime import logging + +from queries import pool import queries from tornado import gen, ioloop, web class ExampleHandler(web.RequestHandler): - def initialize(self): - self.session = queries.TornadoSession() + SQL = 'SELECT * FROM pg_stat_activity' @gen.coroutine def get(self): try: - result = yield self.session.query('SELECT * FROM names') + result = yield self.application.session.query(self.SQL) except queries.OperationalError as error: logging.error('Error connecting to the database: %s', error) raise web.HTTPError(503) - self.finish({'data': result.items()}) + rows = [] + for row in result.items(): + row = dict([(k, v.isoformat() + if isinstance(v, datetime.datetime) else v) + for k, v in row.items()]) + rows.append(row) result.free() + self.finish({'pg_stat_activity': rows}) + + +class ReportHandler(web.RequestHandler): + @gen.coroutine + def get(self): + self.finish(pool.PoolManager.report()) -application = web.Application([ - (r'/', ExampleHandler), -]) if __name__ == '__main__': - logging.basicConfig(level=logging.INFO) - application.listen(8888) + logging.basicConfig(level=logging.DEBUG) + application = web.Application([ + (r'/', ExampleHandler), + (r'/report', ReportHandler) + ], debug=True) + application.session = queries.TornadoSession() + application.listen(8000) ioloop.IOLoop.instance().start()
25
Add more functionality to the example
9
.py
py
bsd-3-clause
gmr/queries
1665
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<3'] else: install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setup(name='queries', version='1.2.1', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]", maintainer='Gavin M. Roy', maintainer_email='[email protected]', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Bump the revision [ci skip] <DFF> @@ -14,7 +14,7 @@ if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setup(name='queries', - version='1.2.1', + version='1.3.0', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]",
1
Bump the revision
1
.py
py
bsd-3-clause
gmr/queries
1666
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<3'] else: install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setup(name='queries', version='1.2.1', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]", maintainer='Gavin M. Roy', maintainer_email='[email protected]', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Bump the revision [ci skip] <DFF> @@ -14,7 +14,7 @@ if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setup(name='queries', - version='1.2.1', + version='1.3.0', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]",
1
Bump the revision
1
.py
py
bsd-3-clause
gmr/queries
1667
<NME> integration_tests.py <BEF> import datetime try: import unittest2 as unittest except ImportError: import unittest import queries from tornado import testing class SessionIntegrationTests(unittest.TestCase): def setUp(self): uri = queries.uri('localhost', 5432, 'postgres', 'postgres') try: self.session = queries.Session(uri, pool_max_size=10) except queries.OperationalError as error: raise unittest.SkipTest(str(error).split('\n')[0]) def tearDown(self): self.session.close() def test_query_returns_results_object(self): self.assertIsInstance(self.session.query('SELECT 1 AS value'), queries.Results) def test_query_result_value(self): result = self.session.query('SELECT 1 AS value') self.assertDictEqual(result.as_dict(), {'value': 1}) def test_query_multirow_result_has_at_least_three_rows(self): result = self.session.query('SELECT * FROM pg_stat_database') self.assertGreaterEqual(result.count(), 3) def test_callproc_returns_results_object(self): timestamp = int(datetime.datetime.now().strftime('%s')) self.assertIsInstance(self.session.callproc('to_timestamp', [timestamp]), queries.Results) self.assertEqual(6 % 4, result[0]['mod']) class TornadoSessionIntegrationTests(testing.AsyncTestCase): def setUp(self): super(TornadoSessionIntegrationTests, self).setUp() self.session = queries.TornadoSession(queries.uri('localhost', 5432, 'postgres', 'postgres'), pool_max_size=10, io_loop=self.io_loop) @testing.gen_test def test_query_returns_results_object(self): try: result = yield self.session.query('SELECT 1 AS value') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertIsInstance(result, queries.Results) result.free() @testing.gen_test def test_query_result_value(self): try: @testing.gen_test def test_query_result_value(self): try: result = yield self.session.query('SELECT 1 AS value') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') @testing.gen_test def test_query_multirow_result_has_at_least_three_rows(self): try: result = yield self.session.query('SELECT * FROM pg_stat_database') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertGreaterEqual(result.count(), 3) except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertGreaterEqual(result.count(), 3) result.free() @testing.gen_test def test_callproc_returns_results_object(self): timestamp = int(datetime.datetime.now().strftime('%s')) try: result = yield self.session.callproc('to_timestamp', [timestamp]) except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertIsInstance(result, queries.Results) result.free() @testing.gen_test def test_callproc_mod_result_value(self): try: result = yield self.session.callproc('mod', [6, 4]) except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertEqual(6 % 4, result[0]['mod']) result.free() @testing.gen_test def test_polling_stops_after_connection_error(self): # Abort the test right away if postgres isn't running. yield self.assertPostgresConnected() # Use an invalid user to force an OperationalError during connection bad_uri = queries.uri(os.getenv('PGHOST', 'localhost'), int(os.getenv('PGPORT', '5432')), 'invalid') session = queries.TornadoSession(bad_uri) self.count = 0 real_poll_connection = session._poll_connection def count_polls(*args, **kwargs): self.count += 1 real_poll_connection(*args, **kwargs) session._poll_connection = count_polls with self.assertRaises(queries.OperationalError): yield session.query('SELECT 1') yield gen.sleep(0.05) self.assertLess(self.count, 20) <MSG> Refactor integration test structure for local docker <DFF> @@ -1,19 +1,25 @@ import datetime -try: - import unittest2 as unittest -except ImportError: - import unittest +import os +import unittest + +from tornado import gen, testing import queries -from tornado import testing -class SessionIntegrationTests(unittest.TestCase): +class URIMixin(object): + + @property + def pg_uri(self): + return queries.uri(os.getenv('PGHOST', 'localhost'), + int(os.getenv('PGPORT', '5432')), 'postgres') + + +class SessionIntegrationTests(URIMixin, unittest.TestCase): def setUp(self): - uri = queries.uri('localhost', 5432, 'postgres', 'postgres') try: - self.session = queries.Session(uri, pool_max_size=10) + self.session = queries.Session(self.pg_uri, pool_max_size=10) except queries.OperationalError as error: raise unittest.SkipTest(str(error).split('\n')[0]) @@ -40,26 +46,28 @@ class SessionIntegrationTests(unittest.TestCase): self.assertEqual(6 % 4, result[0]['mod']) -class TornadoSessionIntegrationTests(testing.AsyncTestCase): +class TornadoSessionIntegrationTests(URIMixin, testing.AsyncTestCase): def setUp(self): super(TornadoSessionIntegrationTests, self).setUp() - self.session = queries.TornadoSession(queries.uri('localhost', - 5432, - 'postgres', - 'postgres'), + self.session = queries.TornadoSession(self.pg_uri, pool_max_size=10, io_loop=self.io_loop) - @testing.gen_test - def test_query_returns_results_object(self): + @gen.coroutine + def assertPostgresConnected(self): try: result = yield self.session.query('SELECT 1 AS value') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertIsInstance(result, queries.Results) + self.assertEqual(len(result), 1) result.free() + @testing.gen_test + def test_successful_connection_and_query(self): + yield self.assertPostgresConnected() + @testing.gen_test def test_query_result_value(self): try: @@ -72,7 +80,7 @@ class TornadoSessionIntegrationTests(testing.AsyncTestCase): @testing.gen_test def test_query_multirow_result_has_at_least_three_rows(self): try: - result = yield self.session.query('SELECT * FROM pg_stat_database') + result = yield self.session.query('SELECT * FROM pg_class') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertGreaterEqual(result.count(), 3)
24
Refactor integration test structure for local docker
16
.py
py
bsd-3-clause
gmr/queries
1668
<NME> integration_tests.py <BEF> import datetime try: import unittest2 as unittest except ImportError: import unittest import queries from tornado import testing class SessionIntegrationTests(unittest.TestCase): def setUp(self): uri = queries.uri('localhost', 5432, 'postgres', 'postgres') try: self.session = queries.Session(uri, pool_max_size=10) except queries.OperationalError as error: raise unittest.SkipTest(str(error).split('\n')[0]) def tearDown(self): self.session.close() def test_query_returns_results_object(self): self.assertIsInstance(self.session.query('SELECT 1 AS value'), queries.Results) def test_query_result_value(self): result = self.session.query('SELECT 1 AS value') self.assertDictEqual(result.as_dict(), {'value': 1}) def test_query_multirow_result_has_at_least_three_rows(self): result = self.session.query('SELECT * FROM pg_stat_database') self.assertGreaterEqual(result.count(), 3) def test_callproc_returns_results_object(self): timestamp = int(datetime.datetime.now().strftime('%s')) self.assertIsInstance(self.session.callproc('to_timestamp', [timestamp]), queries.Results) self.assertEqual(6 % 4, result[0]['mod']) class TornadoSessionIntegrationTests(testing.AsyncTestCase): def setUp(self): super(TornadoSessionIntegrationTests, self).setUp() self.session = queries.TornadoSession(queries.uri('localhost', 5432, 'postgres', 'postgres'), pool_max_size=10, io_loop=self.io_loop) @testing.gen_test def test_query_returns_results_object(self): try: result = yield self.session.query('SELECT 1 AS value') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertIsInstance(result, queries.Results) result.free() @testing.gen_test def test_query_result_value(self): try: @testing.gen_test def test_query_result_value(self): try: result = yield self.session.query('SELECT 1 AS value') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') @testing.gen_test def test_query_multirow_result_has_at_least_three_rows(self): try: result = yield self.session.query('SELECT * FROM pg_stat_database') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertGreaterEqual(result.count(), 3) except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertGreaterEqual(result.count(), 3) result.free() @testing.gen_test def test_callproc_returns_results_object(self): timestamp = int(datetime.datetime.now().strftime('%s')) try: result = yield self.session.callproc('to_timestamp', [timestamp]) except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertIsInstance(result, queries.Results) result.free() @testing.gen_test def test_callproc_mod_result_value(self): try: result = yield self.session.callproc('mod', [6, 4]) except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertEqual(6 % 4, result[0]['mod']) result.free() @testing.gen_test def test_polling_stops_after_connection_error(self): # Abort the test right away if postgres isn't running. yield self.assertPostgresConnected() # Use an invalid user to force an OperationalError during connection bad_uri = queries.uri(os.getenv('PGHOST', 'localhost'), int(os.getenv('PGPORT', '5432')), 'invalid') session = queries.TornadoSession(bad_uri) self.count = 0 real_poll_connection = session._poll_connection def count_polls(*args, **kwargs): self.count += 1 real_poll_connection(*args, **kwargs) session._poll_connection = count_polls with self.assertRaises(queries.OperationalError): yield session.query('SELECT 1') yield gen.sleep(0.05) self.assertLess(self.count, 20) <MSG> Refactor integration test structure for local docker <DFF> @@ -1,19 +1,25 @@ import datetime -try: - import unittest2 as unittest -except ImportError: - import unittest +import os +import unittest + +from tornado import gen, testing import queries -from tornado import testing -class SessionIntegrationTests(unittest.TestCase): +class URIMixin(object): + + @property + def pg_uri(self): + return queries.uri(os.getenv('PGHOST', 'localhost'), + int(os.getenv('PGPORT', '5432')), 'postgres') + + +class SessionIntegrationTests(URIMixin, unittest.TestCase): def setUp(self): - uri = queries.uri('localhost', 5432, 'postgres', 'postgres') try: - self.session = queries.Session(uri, pool_max_size=10) + self.session = queries.Session(self.pg_uri, pool_max_size=10) except queries.OperationalError as error: raise unittest.SkipTest(str(error).split('\n')[0]) @@ -40,26 +46,28 @@ class SessionIntegrationTests(unittest.TestCase): self.assertEqual(6 % 4, result[0]['mod']) -class TornadoSessionIntegrationTests(testing.AsyncTestCase): +class TornadoSessionIntegrationTests(URIMixin, testing.AsyncTestCase): def setUp(self): super(TornadoSessionIntegrationTests, self).setUp() - self.session = queries.TornadoSession(queries.uri('localhost', - 5432, - 'postgres', - 'postgres'), + self.session = queries.TornadoSession(self.pg_uri, pool_max_size=10, io_loop=self.io_loop) - @testing.gen_test - def test_query_returns_results_object(self): + @gen.coroutine + def assertPostgresConnected(self): try: result = yield self.session.query('SELECT 1 AS value') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertIsInstance(result, queries.Results) + self.assertEqual(len(result), 1) result.free() + @testing.gen_test + def test_successful_connection_and_query(self): + yield self.assertPostgresConnected() + @testing.gen_test def test_query_result_value(self): try: @@ -72,7 +80,7 @@ class TornadoSessionIntegrationTests(testing.AsyncTestCase): @testing.gen_test def test_query_multirow_result_has_at_least_three_rows(self): try: - result = yield self.session.query('SELECT * FROM pg_stat_database') + result = yield self.session.query('SELECT * FROM pg_class') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertGreaterEqual(result.count(), 3)
24
Refactor integration test structure for local docker
16
.py
py
bsd-3-clause
gmr/queries
1669
<NME> .travis.yml <BEF> sudo: false language: python dist: xenial env: global: - PATH=$HOME/.local/bin:$PATH - AWS_DEFAULT_REGION=us-east-1 - 3.4 install: - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.txt; fi - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install psycopg2 unittest2 tornado python-coveralls; fi - if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install -r requirements.txt; fi - if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install -r requirements.txt; fi - if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install -r requirements.txt; fi - if [[ $TRAVIS_PYTHON_VERSION == '3.4' ]]; then pip install -r requirements.txt; fi script: nosetests --with-coverage --cover-package=queries after_success: install: - pip install awscli - pip install -r requires/testing.txt - python setup.py develop script: nosetests after_success: - aws s3 cp .coverage "s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/.coverage.${TRAVIS_PYTHON_VERSION}" jobs: include: - python: 2.7 - python: 3.4 - python: 3.5 - python: 3.6 - python: 3.7 - python: 3.8 - stage: coverage if: repo = gmr/queries services: [] python: 3.7 install: - pip install awscli coverage codecov script: - mkdir coverage - aws s3 cp --recursive s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/ coverage - cd coverage - coverage combine - cd .. - mv coverage/.coverage . - coverage report after_success: codecov - stage: deploy if: repo = gmr/queries python: 3.6 services: [] install: true script: true after_success: true deploy: distributions: sdist bdist_wheel provider: pypi user: crad on: tags: true all_branches: true password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= <MSG> Update requirements installation for travis <DFF> @@ -9,12 +9,12 @@ python: - 3.4 install: - - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.txt; fi - - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install psycopg2 unittest2 tornado python-coveralls; fi - - if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install -r requirements.txt; fi - - if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install -r requirements.txt; fi - - if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install -r requirements.txt; fi - - if [[ $TRAVIS_PYTHON_VERSION == '3.4' ]]; then pip install -r requirements.txt; fi + - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install -r requirements.txt; pip install psycopg2 unittest2; fi + - if [[ $TRAVIS_PYTHON_VERSION != '2.7' ]]; then pip install -r requirements.txt; pip install psycopg2; fi + - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.txt; pip install psycopg2ct; fi + - if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install -r requirements.txt; pip install psycopg2; fi + - if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install -r requirements.txt; pip install psycopg2; fi + - if [[ $TRAVIS_PYTHON_VERSION == '3.4' ]]; then pip install -r requirements.txt; pip install psycopg2; fi script: nosetests --with-coverage --cover-package=queries after_success:
6
Update requirements installation for travis
6
.yml
travis
bsd-3-clause
gmr/queries
1670
<NME> .travis.yml <BEF> sudo: false language: python dist: xenial env: global: - PATH=$HOME/.local/bin:$PATH - AWS_DEFAULT_REGION=us-east-1 - 3.4 install: - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.txt; fi - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install psycopg2 unittest2 tornado python-coveralls; fi - if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install -r requirements.txt; fi - if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install -r requirements.txt; fi - if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install -r requirements.txt; fi - if [[ $TRAVIS_PYTHON_VERSION == '3.4' ]]; then pip install -r requirements.txt; fi script: nosetests --with-coverage --cover-package=queries after_success: install: - pip install awscli - pip install -r requires/testing.txt - python setup.py develop script: nosetests after_success: - aws s3 cp .coverage "s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/.coverage.${TRAVIS_PYTHON_VERSION}" jobs: include: - python: 2.7 - python: 3.4 - python: 3.5 - python: 3.6 - python: 3.7 - python: 3.8 - stage: coverage if: repo = gmr/queries services: [] python: 3.7 install: - pip install awscli coverage codecov script: - mkdir coverage - aws s3 cp --recursive s3://com-gavinroy-travis/queries/$TRAVIS_BUILD_NUMBER/ coverage - cd coverage - coverage combine - cd .. - mv coverage/.coverage . - coverage report after_success: codecov - stage: deploy if: repo = gmr/queries python: 3.6 services: [] install: true script: true after_success: true deploy: distributions: sdist bdist_wheel provider: pypi user: crad on: tags: true all_branches: true password: secure: UWQWui+QhAL1cz6oW/vqjEEp6/EPn1YOlItNJcWHNOO/WMMOlaTVYVUuXp+y+m52B+8PtYZZCTHwKCUKe97Grh291FLxgd0RJCawA40f4v1gmOFYLNKyZFBGfbC69/amxvGCcDvOPtpChHAlTIeokS5EQneVcAhXg2jXct0HTfI= <MSG> Update requirements installation for travis <DFF> @@ -9,12 +9,12 @@ python: - 3.4 install: - - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.txt; fi - - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install psycopg2 unittest2 tornado python-coveralls; fi - - if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install -r requirements.txt; fi - - if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install -r requirements.txt; fi - - if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install -r requirements.txt; fi - - if [[ $TRAVIS_PYTHON_VERSION == '3.4' ]]; then pip install -r requirements.txt; fi + - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install -r requirements.txt; pip install psycopg2 unittest2; fi + - if [[ $TRAVIS_PYTHON_VERSION != '2.7' ]]; then pip install -r requirements.txt; pip install psycopg2; fi + - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install -r requirements.txt; pip install psycopg2ct; fi + - if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install -r requirements.txt; pip install psycopg2; fi + - if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install -r requirements.txt; pip install psycopg2; fi + - if [[ $TRAVIS_PYTHON_VERSION == '3.4' ]]; then pip install -r requirements.txt; pip install psycopg2; fi script: nosetests --with-coverage --cover-package=queries after_success:
6
Update requirements installation for travis
6
.yml
travis
bsd-3-clause
gmr/queries
1671
<NME> tornado_session_tests.py <BEF> """ Tests for functionality in the tornado_session module """ import mock import unittest from psycopg2 import extras from tornado import concurrent from tornado import gen class ResultsTests(unittest.TestCase): def setUp(self): self.cursor = mock.Mock() self.fd = 10 self.cleanup = mock.Mock() self.obj = tornado_session.Results(self.cursor, self.cleanup, self.fd) def test_cursor_is_assigned(self): self.assertEqual(self.obj.cursor, self.cursor) def test_fd_is_assigned(self): self.assertEqual(self.obj._fd, self.fd) def test_cleanup_is_assigned(self): self.assertEqual(self.obj._cleanup, self.cleanup) @gen.coroutine def test_free_invokes_cleanup(self): yield self.obj.free() self.cleanup.assert_called_once_with(self.cursor, self.fd) class SessionInitTests(unittest.TestCase): def setUp(self): self.obj = tornado_session.TornadoSession() def test_creates_empty_callback_dict(self): self.assertDictEqual(self.obj._futures, {}) def test_creates_empty_connections_dict(self): self.assertDictEqual(self.obj._connections, {}) def test_sets_default_cursor_factory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_sets_tornado_ioloop_instance(self): self.assertEqual(self.obj._ioloop, ioloop.IOLoop.instance()) def test_sets_poolmananger_instance(self): self.assertEqual(self.obj._pool_manager, pool.PoolManager.instance()) def test_sets_uri(self): self.assertEqual(self.obj._uri, tornado_session.session.DEFAULT_URI) def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) def test_connection_is_none(self): self.assertIsNone(self.obj.connection) def test_cursor_is_none(self): self.assertIsNone(self.obj.cursor) class SessionConnectTests(testing.AsyncTestCase): def setUp(self): super(SessionConnectTests, self).setUp() self.conn = mock.Mock() self.conn.fileno = mock.Mock(return_value=10) self.obj = tornado_session.TornadoSession(io_loop=self.io_loop) def create_connection(future): future.set_result(self.conn) self.obj._create_connection = create_connection @testing.gen_test def test_connect_returns_new_connection(self): conn = yield self.obj._connect() self.assertEqual(conn, self.conn) @testing.gen_test def test_connect_returns_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) second_result = yield self.obj._connect() self.assertEqual(second_result, conn) @testing.gen_test def test_connect_gets_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: with mock.patch.object(self.io_loop, 'add_handler'): yield self.obj._connect() get.assert_called_once_with(self.obj.pid, self.obj) @testing.gen_test def test_connect_pooled_connection_invokes_add_handler(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: get.return_value = self.conn with mock.patch.object(self.io_loop, 'add_handler') as add_handler: yield self.obj._connect() add_handler.assert_called_once_with(self.conn.fileno(), self.obj._on_io_events, ioloop.IOLoop.WRITE) def test_psycopg2_connect_invokes_psycopg2_connect(self): with mock.patch('psycopg2.connect') as connect: self.obj._psycopg2_connect({}) connect.assert_called_once_with(**{'async': True}) def test_on_io_events_returns_if_fd_not_present(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_not_called() def test_on_io_events_calls_poll_connection(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._connections[1337] = True self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_called_once_with(1337) def test_exec_cleanup_closes_cursor(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() cursor = mock.Mock() cursor.close = mock.Mock() self.obj._exec_cleanup(cursor, 14) cursor.close.assert_called_once_with() def test_exec_cleanup_frees_connection(self): with mock.patch.object(self.obj._pool_manager, 'free') as pm_free: with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = conn = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) pm_free.assert_called_once_with(self.obj.pid, conn) def test_exec_cleanup_remove_handler_invoked(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh: self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) rh.assert_called_once_with(14) def test_exec_removes_connection(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._connections) def test_exec_removes_future(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._futures[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._futures) def test_pool_manager_add_failures_are_propagated(self): futures = [] def add_future(future, callback): futures.append((future, callback)) obj = tornado_session.TornadoSession() obj._ioloop = mock.Mock() obj._ioloop.add_future = add_future future = concurrent.Future() with mock.patch.object(obj._pool_manager, 'add') as add_method: add_method.side_effect = pool.PoolFullError(mock.Mock()) obj._create_connection(future) self.assertEqual(len(futures), 1) connected_future, callback = futures.pop() connected_future.set_result(True) callback(connected_future) self.assertIs(future.exception(), add_method.side_effect) class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_callproc_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) @testing.gen_test def test_query_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) """ @testing.gen_test def test_query_error_key_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) @testing.gen_test def test_query_error_index_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): r = yield obj.query('SELECT * FROM foo WHERE bar=%s', []) """ <MSG> Conditional psycopg2cffi import for pypy3 <DFF> @@ -5,7 +5,10 @@ Tests for functionality in the tornado_session module import mock import unittest -from psycopg2 import extras +try: + from psycopg2cffi import extras +except ImportError: + from psycopg2 import extras from tornado import concurrent from tornado import gen
4
Conditional psycopg2cffi import for pypy3
1
.py
py
bsd-3-clause
gmr/queries
1672
<NME> tornado_session_tests.py <BEF> """ Tests for functionality in the tornado_session module """ import mock import unittest from psycopg2 import extras from tornado import concurrent from tornado import gen class ResultsTests(unittest.TestCase): def setUp(self): self.cursor = mock.Mock() self.fd = 10 self.cleanup = mock.Mock() self.obj = tornado_session.Results(self.cursor, self.cleanup, self.fd) def test_cursor_is_assigned(self): self.assertEqual(self.obj.cursor, self.cursor) def test_fd_is_assigned(self): self.assertEqual(self.obj._fd, self.fd) def test_cleanup_is_assigned(self): self.assertEqual(self.obj._cleanup, self.cleanup) @gen.coroutine def test_free_invokes_cleanup(self): yield self.obj.free() self.cleanup.assert_called_once_with(self.cursor, self.fd) class SessionInitTests(unittest.TestCase): def setUp(self): self.obj = tornado_session.TornadoSession() def test_creates_empty_callback_dict(self): self.assertDictEqual(self.obj._futures, {}) def test_creates_empty_connections_dict(self): self.assertDictEqual(self.obj._connections, {}) def test_sets_default_cursor_factory(self): self.assertEqual(self.obj._cursor_factory, extras.RealDictCursor) def test_sets_tornado_ioloop_instance(self): self.assertEqual(self.obj._ioloop, ioloop.IOLoop.instance()) def test_sets_poolmananger_instance(self): self.assertEqual(self.obj._pool_manager, pool.PoolManager.instance()) def test_sets_uri(self): self.assertEqual(self.obj._uri, tornado_session.session.DEFAULT_URI) def test_creates_pool_in_manager(self): self.assertIn(self.obj.pid, self.obj._pool_manager._pools) def test_connection_is_none(self): self.assertIsNone(self.obj.connection) def test_cursor_is_none(self): self.assertIsNone(self.obj.cursor) class SessionConnectTests(testing.AsyncTestCase): def setUp(self): super(SessionConnectTests, self).setUp() self.conn = mock.Mock() self.conn.fileno = mock.Mock(return_value=10) self.obj = tornado_session.TornadoSession(io_loop=self.io_loop) def create_connection(future): future.set_result(self.conn) self.obj._create_connection = create_connection @testing.gen_test def test_connect_returns_new_connection(self): conn = yield self.obj._connect() self.assertEqual(conn, self.conn) @testing.gen_test def test_connect_returns_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) second_result = yield self.obj._connect() self.assertEqual(second_result, conn) @testing.gen_test def test_connect_gets_pooled_connection(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: with mock.patch.object(self.io_loop, 'add_handler'): yield self.obj._connect() get.assert_called_once_with(self.obj.pid, self.obj) @testing.gen_test def test_connect_pooled_connection_invokes_add_handler(self): conn = yield self.obj._connect() self.obj._pool_manager.add(self.obj.pid, conn) with mock.patch.object(self.obj._pool_manager, 'get') as get: get.return_value = self.conn with mock.patch.object(self.io_loop, 'add_handler') as add_handler: yield self.obj._connect() add_handler.assert_called_once_with(self.conn.fileno(), self.obj._on_io_events, ioloop.IOLoop.WRITE) def test_psycopg2_connect_invokes_psycopg2_connect(self): with mock.patch('psycopg2.connect') as connect: self.obj._psycopg2_connect({}) connect.assert_called_once_with(**{'async': True}) def test_on_io_events_returns_if_fd_not_present(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_not_called() def test_on_io_events_calls_poll_connection(self): with mock.patch.object(self.obj, '_poll_connection') as poll: self.obj._connections[1337] = True self.obj._on_io_events(1337, ioloop.IOLoop.WRITE) poll.assert_called_once_with(1337) def test_exec_cleanup_closes_cursor(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() cursor = mock.Mock() cursor.close = mock.Mock() self.obj._exec_cleanup(cursor, 14) cursor.close.assert_called_once_with() def test_exec_cleanup_frees_connection(self): with mock.patch.object(self.obj._pool_manager, 'free') as pm_free: with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = conn = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) pm_free.assert_called_once_with(self.obj.pid, conn) def test_exec_cleanup_remove_handler_invoked(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler') as rh: self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) rh.assert_called_once_with(14) def test_exec_removes_connection(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._connections) def test_exec_removes_future(self): with mock.patch.object(self.obj._pool_manager, 'free'): with mock.patch.object(self.obj._ioloop, 'remove_handler'): self.obj._connections[14] = mock.Mock() self.obj._futures[14] = mock.Mock() self.obj._exec_cleanup(mock.Mock(), 14) self.assertNotIn(14, self.obj._futures) def test_pool_manager_add_failures_are_propagated(self): futures = [] def add_future(future, callback): futures.append((future, callback)) obj = tornado_session.TornadoSession() obj._ioloop = mock.Mock() obj._ioloop.add_future = add_future future = concurrent.Future() with mock.patch.object(obj._pool_manager, 'add') as add_method: add_method.side_effect = pool.PoolFullError(mock.Mock()) obj._create_connection(future) self.assertEqual(len(futures), 1) connected_future, callback = futures.pop() connected_future.set_result(True) callback(connected_future) self.assertIs(future.exception(), add_method.side_effect) class SessionPublicMethodTests(testing.AsyncTestCase): @testing.gen_test def test_callproc_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.callproc('foo', ['bar']) _execute.assert_called_once_with('callproc', 'foo', ['bar']) @testing.gen_test def test_query_invokes_execute(self): with mock.patch('queries.tornado_session.TornadoSession._execute') as \ _execute: future = concurrent.Future() future.set_result(True) _execute.return_value = future obj = tornado_session.TornadoSession(io_loop=self.io_loop) yield obj.query('SELECT 1') _execute.assert_called_once_with('execute', 'SELECT 1', None) """ @testing.gen_test def test_query_error_key_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): yield obj.query('SELECT * FROM foo WHERE bar=%(baz)s', {}) @testing.gen_test def test_query_error_index_error(self): obj = tornado_session.TornadoSession(io_loop=self.io_loop) with self.assertRaises(Exception): r = yield obj.query('SELECT * FROM foo WHERE bar=%s', []) """ <MSG> Conditional psycopg2cffi import for pypy3 <DFF> @@ -5,7 +5,10 @@ Tests for functionality in the tornado_session module import mock import unittest -from psycopg2 import extras +try: + from psycopg2cffi import extras +except ImportError: + from psycopg2 import extras from tornado import concurrent from tornado import gen
4
Conditional psycopg2cffi import for pypy3
1
.py
py
bsd-3-clause
gmr/queries
1673
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<3'] else: install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setuptools.setup( name='queries', version='2.1.0', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy', maintainer_email='[email protected]', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Topic :: Software Development :: Libraries'] setup(name='queries', version='1.7.2', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]", 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Merge pull request #10 from djt5019/fix-env-var Properly cast the environment variable as an integer <DFF> @@ -30,7 +30,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.7.2', + version='1.7.3', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]",
1
Merge pull request #10 from djt5019/fix-env-var
1
.py
py
bsd-3-clause
gmr/queries
1674
<NME> setup.py <BEF> import os import platform import setuptools # PYPY vs cpython if platform.python_implementation() == 'PyPy': install_requires = ['psycopg2cffi>=2.7.2,<3'] else: install_requires = ['psycopg2>=2.5.1,<3'] # Install tornado if generating docs on readthedocs if os.environ.get('READTHEDOCS', None) == 'True': install_requires.append('tornado') setuptools.setup( name='queries', version='2.1.0', description='Simplified PostgreSQL client built upon Psycopg2', long_description=open('README.rst').read(), maintainer='Gavin M. Roy', maintainer_email='[email protected]', url='https://github.com/gmr/queries', install_requires=install_requires, extras_require={'tornado': 'tornado<6'}, license='BSD', package_data={'': ['LICENSE', 'README.rst']}, packages=['queries'], classifiers=[ 'Topic :: Software Development :: Libraries'] setup(name='queries', version='1.7.2', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]", 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Database', 'Topic :: Software Development :: Libraries'], zip_safe=True) <MSG> Merge pull request #10 from djt5019/fix-env-var Properly cast the environment variable as an integer <DFF> @@ -30,7 +30,7 @@ classifiers = ['Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries'] setup(name='queries', - version='1.7.2', + version='1.7.3', description="Simplified PostgreSQL client built upon Psycopg2", maintainer="Gavin M. Roy", maintainer_email="[email protected]",
1
Merge pull request #10 from djt5019/fix-env-var
1
.py
py
bsd-3-clause
gmr/queries
1675
<NME> integration_tests.py <BEF> import datetime import os import unittest from tornado import gen, testing import queries class URIMixin(object): @property def pg_uri(self): return queries.uri(os.getenv('PGHOST', 'localhost'), int(os.getenv('PGPORT', '5432')), 'postgres') class SessionIntegrationTests(URIMixin, unittest.TestCase): def setUp(self): try: self.session = queries.Session(self.pg_uri, pool_max_size=10) except queries.OperationalError as error: raise unittest.SkipTest(str(error).split('\n')[0]) def tearDown(self): self.session.close() def test_query_returns_results_object(self): self.assertIsInstance(self.session.query('SELECT 1 AS value'), queries.Results) def test_query_result_value(self): result = self.session.query('SELECT 1 AS value') self.assertDictEqual(result.as_dict(), {'value': 1}) def test_query_multirow_result_has_at_least_three_rows(self): result = self.session.query('SELECT * FROM pg_stat_database') self.assertGreaterEqual(result.count(), 3) def test_callproc_returns_results_object(self): timestamp = int(datetime.datetime.now().strftime('%s')) self.assertIsInstance(self.session.callproc('to_timestamp', [timestamp]), queries.Results) def test_callproc_mod_result_value(self): result = self.session.callproc('mod', [6, 4]) self.assertEqual(6 % 4, result[0]['mod']) class TornadoSessionIntegrationTests(URIMixin, testing.AsyncTestCase): def setUp(self): super(TornadoSessionIntegrationTests, self).setUp() self.session = queries.TornadoSession(self.pg_uri, pool_max_size=10, io_loop=self.io_loop) @gen.coroutine def assertPostgresConnected(self): try: result = yield self.session.query('SELECT 1 AS value') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertIsInstance(result, queries.Results) self.assertEqual(len(result), 1) result.free() @testing.gen_test def test_successful_connection_and_query(self): yield self.assertPostgresConnected() @testing.gen_test def test_query_result_value(self): try: result = yield self.session.query('SELECT 1 AS value') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertDictEqual(result.as_dict(), {'value': 1}) result.free() @testing.gen_test def test_query_multirow_result_has_at_least_three_rows(self): try: result = yield self.session.query('SELECT * FROM pg_class') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertGreaterEqual(result.count(), 3) result.free() @testing.gen_test def test_callproc_returns_results_object(self): timestamp = int(datetime.datetime.now().strftime('%s')) try: result = yield self.session.callproc('to_timestamp', [timestamp]) except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertIsInstance(result, queries.Results) result.free() @testing.gen_test def test_callproc_mod_result_value(self): raise unittest.SkipTest('PostgreSQL is not running') self.assertEqual(6 % 4, result[0]['mod']) result.free() yield session.query('SELECT 1') yield gen.sleep(0.05) self.assertLess(self.count, 20) <MSG> Cleanup and fix related to errors connection errors (#28) <DFF> @@ -104,3 +104,26 @@ class TornadoSessionIntegrationTests(URIMixin, testing.AsyncTestCase): raise unittest.SkipTest('PostgreSQL is not running') self.assertEqual(6 % 4, result[0]['mod']) result.free() + + @testing.gen_test + def test_polling_stops_after_connection_error(self): + # Abort the test right away if postgres isn't running. + yield self.assertPostgresConnected() + + # Use an invalid user to force an OperationalError during connection + bad_uri = queries.uri(os.getenv('PGHOST', 'localhost'), + int(os.getenv('PGPORT', '5432')), 'invalid') + session = queries.TornadoSession(bad_uri) + + self.count = 0 + real_poll_connection = session._poll_connection + + def count_polls(*args, **kwargs): + self.count += 1 + real_poll_connection(*args, **kwargs) + session._poll_connection = count_polls + + with self.assertRaises(queries.OperationalError): + yield session.query('SELECT 1') + yield gen.sleep(0.05) + self.assertLess(self.count, 20)
23
Cleanup and fix related to errors connection errors (#28)
0
.py
py
bsd-3-clause
gmr/queries
1676
<NME> integration_tests.py <BEF> import datetime import os import unittest from tornado import gen, testing import queries class URIMixin(object): @property def pg_uri(self): return queries.uri(os.getenv('PGHOST', 'localhost'), int(os.getenv('PGPORT', '5432')), 'postgres') class SessionIntegrationTests(URIMixin, unittest.TestCase): def setUp(self): try: self.session = queries.Session(self.pg_uri, pool_max_size=10) except queries.OperationalError as error: raise unittest.SkipTest(str(error).split('\n')[0]) def tearDown(self): self.session.close() def test_query_returns_results_object(self): self.assertIsInstance(self.session.query('SELECT 1 AS value'), queries.Results) def test_query_result_value(self): result = self.session.query('SELECT 1 AS value') self.assertDictEqual(result.as_dict(), {'value': 1}) def test_query_multirow_result_has_at_least_three_rows(self): result = self.session.query('SELECT * FROM pg_stat_database') self.assertGreaterEqual(result.count(), 3) def test_callproc_returns_results_object(self): timestamp = int(datetime.datetime.now().strftime('%s')) self.assertIsInstance(self.session.callproc('to_timestamp', [timestamp]), queries.Results) def test_callproc_mod_result_value(self): result = self.session.callproc('mod', [6, 4]) self.assertEqual(6 % 4, result[0]['mod']) class TornadoSessionIntegrationTests(URIMixin, testing.AsyncTestCase): def setUp(self): super(TornadoSessionIntegrationTests, self).setUp() self.session = queries.TornadoSession(self.pg_uri, pool_max_size=10, io_loop=self.io_loop) @gen.coroutine def assertPostgresConnected(self): try: result = yield self.session.query('SELECT 1 AS value') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertIsInstance(result, queries.Results) self.assertEqual(len(result), 1) result.free() @testing.gen_test def test_successful_connection_and_query(self): yield self.assertPostgresConnected() @testing.gen_test def test_query_result_value(self): try: result = yield self.session.query('SELECT 1 AS value') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertDictEqual(result.as_dict(), {'value': 1}) result.free() @testing.gen_test def test_query_multirow_result_has_at_least_three_rows(self): try: result = yield self.session.query('SELECT * FROM pg_class') except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertGreaterEqual(result.count(), 3) result.free() @testing.gen_test def test_callproc_returns_results_object(self): timestamp = int(datetime.datetime.now().strftime('%s')) try: result = yield self.session.callproc('to_timestamp', [timestamp]) except queries.OperationalError: raise unittest.SkipTest('PostgreSQL is not running') self.assertIsInstance(result, queries.Results) result.free() @testing.gen_test def test_callproc_mod_result_value(self): raise unittest.SkipTest('PostgreSQL is not running') self.assertEqual(6 % 4, result[0]['mod']) result.free() yield session.query('SELECT 1') yield gen.sleep(0.05) self.assertLess(self.count, 20) <MSG> Cleanup and fix related to errors connection errors (#28) <DFF> @@ -104,3 +104,26 @@ class TornadoSessionIntegrationTests(URIMixin, testing.AsyncTestCase): raise unittest.SkipTest('PostgreSQL is not running') self.assertEqual(6 % 4, result[0]['mod']) result.free() + + @testing.gen_test + def test_polling_stops_after_connection_error(self): + # Abort the test right away if postgres isn't running. + yield self.assertPostgresConnected() + + # Use an invalid user to force an OperationalError during connection + bad_uri = queries.uri(os.getenv('PGHOST', 'localhost'), + int(os.getenv('PGPORT', '5432')), 'invalid') + session = queries.TornadoSession(bad_uri) + + self.count = 0 + real_poll_connection = session._poll_connection + + def count_polls(*args, **kwargs): + self.count += 1 + real_poll_connection(*args, **kwargs) + session._poll_connection = count_polls + + with self.assertRaises(queries.OperationalError): + yield session.query('SELECT 1') + yield gen.sleep(0.05) + self.assertLess(self.count, 20)
23
Cleanup and fix related to errors connection errors (#28)
0
.py
py
bsd-3-clause
gmr/queries
1677
<NME> RedisSessionDAOTest.java <BEF> package org.crazycake.shiro; import org.apache.shiro.session.InvalidSessionException; import org.apache.shiro.session.Session; import org.crazycake.shiro.exception.SerializationException; import org.crazycake.shiro.serializer.ObjectSerializer; import org.crazycake.shiro.serializer.StringSerializer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Set; public class RedisSessionDAOTest { private RedisSingletonManager redisManager; private RedisSessionDAO redisSessionDAO; private StringSerializer keySerializer; private String testKey; public class RedisSessionDAOTest { private IRedisManager redisManager; private StringSerializer keySerializer = new StringSerializer(); private ObjectSerializer valueSerializer = new ObjectSerializer(); @BeforeEach public void setUp() { redisManager = mock(IRedisManager.class); } private RedisSessionDAO mountRedisSessionDAO(Integer expire) { RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); if (expire != null) { redisSessionDAO.setExpire(expire); } redisSessionDAO.setKeyPrefix("student:"); redisSessionDAO.setRedisManager(redisManager); return redisSessionDAO; } @Test public void testUpdate() throws SerializationException { RedisSessionDAO sessionDAO = mountRedisSessionDAO(null); StudentSession session = new StudentSession(99, 2000); testValues.add(paulSession); billySession = new FakeSession(3, "billy"); testValues.add(billySession); redisManager = mock(RedisSingletonManager.class); when(redisManager.dbSize()).thenReturn(2L); when(redisManager.get(keySerializer.serialize(testPrefix + testKey))).thenReturn(valueSeralizer.serialize(testValue)); when(redisManager.keys(keySerializer.serialize(testPrefix + "*"))).thenReturn(testSet); StudentSession session = new StudentSession(98, 2000); sessionDAO.update(session); verify(redisManager).set(keySerializer.serialize("student:98"), valueSerializer.serialize(session), 3); } @Test public void testUpdateByNoExpire() throws SerializationException { RedisSessionDAO sessionDAO = mountRedisSessionDAO(-1); StudentSession session = new StudentSession(97, 2000); sessionDAO.update(session); verify(redisManager).set(keySerializer.serialize("student:97"), valueSerializer.serialize(session), -1); } @Test public void testDelete() throws SerializationException { RedisSessionDAO sessionDAO = mountRedisSessionDAO(null); StudentSession session = new StudentSession(96, 1000); sessionDAO.delete(session); verify(redisManager).del(keySerializer.serialize("student:96")); } @Test public void testGetActiveSessions() throws SerializationException { Set<byte[]> mockKeys = new HashSet<byte[]>(); mockKeys.add(keySerializer.serialize("student:1")); mockKeys.add(keySerializer.serialize("student:2")); when(redisManager.keys(keySerializer.serialize("student:*"))).thenReturn(mockKeys); StudentSession mockSession1 = new StudentSession(1, 2000); StudentSession mockSession2 = new StudentSession(2, 2000); when(redisManager.get(keySerializer.serialize("student:1"))).thenReturn(valueSerializer.serialize(mockSession1)); when(redisManager.get(keySerializer.serialize("student:2"))).thenReturn(valueSerializer.serialize(mockSession2)); RedisSessionDAO sessionDAO = mountRedisSessionDAO(null); assertThat(sessionDAO.getActiveSessions().size(), is(2)); } } class StudentSession implements Session, Serializable { private Integer id; private long timeout; public StudentSession(Integer id, long timeout) { this.id = id; this.timeout = timeout; } @Override public Serializable getId() { return id; } @Override public Date getStartTimestamp() { return null; } @Override public Date getLastAccessTime() { return null; } @Override public long getTimeout() throws InvalidSessionException { return timeout; } @Override public void setTimeout(long l) throws InvalidSessionException { } @Override public String getHost() { return null; } @Override public void touch() throws InvalidSessionException { } @Override public void stop() throws InvalidSessionException { } @Override public Collection<Object> getAttributeKeys() throws InvalidSessionException { return null; } @Override public Object getAttribute(Object o) throws InvalidSessionException { return null; } @Override public void setAttribute(Object o, Object o1) throws InvalidSessionException { } @Override public Object removeAttribute(Object o) throws InvalidSessionException { return null; } } <MSG> 2.8.0 release: 1. Add Redis Sentinel support 2. Using Scan to get keys 3. Some refactor <DFF> @@ -16,7 +16,7 @@ import static org.mockito.Mockito.when; public class RedisSessionDAOTest { - private RedisSingletonManager redisManager; + private RedisManager redisManager; private RedisSessionDAO redisSessionDAO; private StringSerializer keySerializer; private String testKey; @@ -47,7 +47,7 @@ public class RedisSessionDAOTest { testValues.add(paulSession); billySession = new FakeSession(3, "billy"); testValues.add(billySession); - redisManager = mock(RedisSingletonManager.class); + redisManager = mock(RedisManager.class); when(redisManager.dbSize()).thenReturn(2L); when(redisManager.get(keySerializer.serialize(testPrefix + testKey))).thenReturn(valueSeralizer.serialize(testValue)); when(redisManager.keys(keySerializer.serialize(testPrefix + "*"))).thenReturn(testSet);
2
2.8.0 release: 1. Add Redis Sentinel support 2. Using Scan to get keys 3. Some refactor
2
.java
java
mit
alexxiyang/shiro-redis
1678
<NME> RedisCacheTest.java <BEF> package org.crazycake.shiro; import org.apache.shiro.subject.PrincipalCollection; import org.crazycake.shiro.exception.SerializationException; import org.crazycake.shiro.serializer.ObjectSerializer; import org.crazycake.shiro.serializer.StringSerializer; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.*; import static org.mockito.Mockito.*; public class RedisCacheTest { private IRedisManager redisManager; private StringSerializer keySerializer = new StringSerializer(); private ObjectSerializer valueSerializer = new ObjectSerializer(); @BeforeEach public void setUp() { redisManager = mock(IRedisManager.class); } private RedisCache mountRedisCache() { return new RedisCache(redisManager, new StringSerializer(), new ObjectSerializer(), "employee:", 1, RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME); } @Test public void testInitialize() { Assertions.assertThrows(IllegalArgumentException.class, () -> new RedisCache<String, String>(null, null, null, "abc:", 1, RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME)); Assertions.assertThrows(IllegalArgumentException.class, () -> new RedisCache<String, String>(new RedisManager(), null, null, "abc:", 1, RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME)); Assertions.assertThrows(IllegalArgumentException.class, () -> new RedisCache<String, String>(new RedisManager(), new StringSerializer(), null, "abc:", 1, RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME)); } @Test public void testPut() throws SerializationException { RedisCache rc = mountRedisCache(); Object value = rc.put("foo", "bar"); assertThat(value, is("bar")); verify(redisManager).set(keySerializer.serialize("employee:foo"), valueSerializer.serialize("bar"), 1); PrincipalCollection principal = new EmployeePrincipal(3); rc.put(principal, "account information"); verify(redisManager).set(keySerializer.serialize("employee:3"), valueSerializer.serialize("account information"), 1); } when(redisManager.get(keySerializer.serialize(testPrefix + "tom"))).thenReturn(valueSerializer.serialize(tomSession)); when(redisManager.get(keySerializer.serialize(testPrefix + "paul"))).thenReturn(valueSerializer.serialize(paulSession)); when(redisManager.get(keySerializer.serialize(testPrefix + "billy"))).thenReturn(valueSerializer.serialize(billySession)); redisCache = new RedisCache<String, FakeSession>(redisManager, keySerializer, valueSerializer, testPrefix); } @Test public void testRedisCache() { try { new RedisCache<String, String>(null, keySerializer, valueSerializer); fail("Excepted exception to be thrown"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(),is("Cache argument cannot be null.")); } new RedisCache(new RedisManager(), keySerializer, valueSerializer); RedisCache rc = new RedisCache(new RedisManager(), keySerializer, valueSerializer, "testPrefix"); assertThat(rc.getKeyPrefix(), is("testPrefix")); } @Test } @Override public Employee getPrimaryPrincipal() { return this.primaryPrincipal; } @Override public <T> T oneByType(Class<T> aClass) { return null; } @Override public <T> Collection<T> byType(Class<T> aClass) { return null; } @Override public List asList() { return null; } @Override public Set asSet() { return null; } @Override public Collection fromRealm(String s) { return null; } @Override public Set<String> getRealmNames() { return null; } @Override public boolean isEmpty() { return false; } @Override public Iterator iterator() { return null; } } <MSG> Fix RedisCache keyprefix cannot be changed defect Set separate expire time of Session and Cache instead of only one expire time of RedisManager <DFF> @@ -53,22 +53,20 @@ public class RedisCacheTest { when(redisManager.get(keySerializer.serialize(testPrefix + "tom"))).thenReturn(valueSerializer.serialize(tomSession)); when(redisManager.get(keySerializer.serialize(testPrefix + "paul"))).thenReturn(valueSerializer.serialize(paulSession)); when(redisManager.get(keySerializer.serialize(testPrefix + "billy"))).thenReturn(valueSerializer.serialize(billySession)); - redisCache = new RedisCache<String, FakeSession>(redisManager, keySerializer, valueSerializer, testPrefix); + redisCache = new RedisCache<String, FakeSession>(redisManager, keySerializer, valueSerializer, testPrefix, 1); } @Test public void testRedisCache() { try { - new RedisCache<String, String>(null, keySerializer, valueSerializer); + new RedisCache<String, String>(null, keySerializer, valueSerializer, "abc:", 1); fail("Excepted exception to be thrown"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(),is("Cache argument cannot be null.")); } - new RedisCache(new RedisManager(), keySerializer, valueSerializer); - - RedisCache rc = new RedisCache(new RedisManager(), keySerializer, valueSerializer, "testPrefix"); - assertThat(rc.getKeyPrefix(), is("testPrefix")); + RedisCache rc = new RedisCache(new RedisManager(), keySerializer, valueSerializer, "abc", 1); + assertThat(rc.getKeyPrefix(), is("abc")); } @Test
4
Fix RedisCache keyprefix cannot be changed defect Set separate expire time of Session and Cache instead of only one expire time of RedisManager
6
.java
java
mit
alexxiyang/shiro-redis
1679
<NME> tested_on.rst <BEF> Tested on ========= Working on ---------- This is an list of environments that Hitch is tested on and been found to work. If you use one of these environments and you discover a problem, that's a bug. Please raise an issue. OSes: * Ubuntu 14.04 * Mac OS X Mavericks * Mac OS X Yosemite * Debian Jessie * Fedora 20 * CentOS 6.4 * Arch (latest rolling release) Additionally, the following environments have been tested with and seem to run Hitch okay: * Docker * Jenkins * Travis CI Not working on -------------- This is a list of other UNIX systems that Hitch will not currently work on, but might be made to function with with some work. If you really want one of these systems to run hitch, that's a feature request. It may happen if you raise an issue. * Mandriva * OpenSUSE * Mac OS X with macports * BSD * Gentoo * Mac OS X with no package manager * Slackware * LFS .. note:: 95% of getting these environments to work involves getting unixpackage to work with them. Please consider `helping out <https://github.com/unixpackage/unixpackage/blob/master/CONTRIBUTING.rst>`_ with it if you'd like to one of these flavors of UNIX / environments supported. This is a list of environments that probably aren't happening in the near future but may happen one day: * Cygwin * Windows Untested but should still work ------------------------------ This is a list of environments that Hitch has *not* been tested on, but hopefully should still work, but I'm not as confident about. If it doesn't work, that's a bug. Please raise an issue if you find a problem. If you have access to one of these, *please* try out the example project and submit a pull request adding your environment if it works or raise an issue if it doesn't: * Mac OS X El Capitan * Variations on Mac OS X Yosemite/Mavericks (e.g. with different versions of Xcode) * Red Hat * Ubuntu/Debian based distros like Trisquel, Kali or Mint * Red Hat based distros like Oracle Linux * Basically any Linux system not mentioned above * Any continuous integration system not mentioned above * Any Linux system mentioned above but a slightly different version <MSG> DOCS : Updated long out of date 'tested on' docs. <DFF> @@ -11,8 +11,10 @@ and you discover a problem, that's a bug. Please raise an issue. OSes: * Ubuntu 14.04 +* Ubuntu 15.10 * Mac OS X Mavericks * Mac OS X Yosemite +* Mac OS X Mavericks * Debian Jessie * Fedora 20 * CentOS 6.4 @@ -67,11 +69,8 @@ If you have access to one of these, *please* try out the example project and submit a pull request adding your environment if it works or raise an issue if it doesn't: -* Mac OS X El Capitan -* Variations on Mac OS X Yosemite/Mavericks (e.g. with different versions of Xcode) * Red Hat * Ubuntu/Debian based distros like Trisquel, Kali or Mint * Red Hat based distros like Oracle Linux -* Basically any Linux system not mentioned above +* Linux systems not mentioned above * Any continuous integration system not mentioned above -* Any Linux system mentioned above but a slightly different version
3
DOCS : Updated long out of date 'tested on' docs.
4
.rst
rst
agpl-3.0
hitchtest/hitch
1680
<NME> README.md <BEF> shiro-redis ============= [![Build Status](https://travis-ci.org/alexxiyang/shiro-redis.svg?branch=master)](https://travis-ci.org/alexxiyang/shiro-redis) shiro only provide the support of ehcache and concurrentHashMap. Here is an implement of redis cache can be used by shiro. Hope it will help you! # Download You use either of the following 2 ways to include `shiro-redis` into your project * use `git clone https://github.com/alexxiyang/shiro-redis.git` to clone project to your local workspace and build jar file by your self * add maven dependency ```xml <dependency> <groupId>org.crazycake</groupId> <artifactId>shiro-redis</artifactId> <version>3.3.1</version> </dependency> ``` > **Note:**\ > 3.3.0 is compiled in java11 by mistake. > Please use 3.3.1 which is compiled in java8 ## shiro-core/jedis Version Comparison Charts | shiro-redis | shiro | jedis | | :----------------:| :-------: | :-------: | | 3.2.3 | 1.3.2 | 2.9.0 | | 3.3.0 (java11) | 1.6.0 | 3.3.0 | | 3.3.1 (java8) | 1.6.0 | 3.3.0 | # Before use Here is the first thing you need to know. Shiro-redis needs an id field to identify your authorization object in Redis. So please make sure your principal class has a field which you can get unique id of this object. Please setting this id field name by `cacheManager.principalIdFieldName = <your id field name of principal object>` For example: If you create `SimpleAuthenticationInfo` like this: ```java @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token; UserInfo userInfo = new UserInfo(); userInfo.setUsername(usernamePasswordToken.getUsername()); return new SimpleAuthenticationInfo(userInfo, "123456", getName()); } ``` Then the `userInfo` object is your principal object. You need to make sure `UserInfo` has an unique field for Redis to identify it. Take `userId` as an example: ```java public class UserInfo implements Serializable{ private Integer userId private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getUserId() { return this.userId; } } ``` Put userId as the value of `cacheManager.principalIdFieldName`, like this: ```properties cacheManager.principalIdFieldName = userId ``` If you're using Spring, the configuration should be ```xml <property name="principalIdFieldName" value="userId" /> ``` Then `shiro-redis` will call `userInfo.getUserId()` to get the id for saving Redis object. # How to configure ? You can configure `shiro-redis` either in `shiro.ini` or in `spring-*.xml` ## shiro.ini Here is the configuration example for shiro.ini. ### Redis Standalone If you are running Redis in Standalone mode ```properties [main] #==================================== # shiro-redis configuration [start] #==================================== #=================================== # Redis Manager [start] #=================================== # Create redisManager redisManager = org.crazycake.shiro.RedisManager # Redis host. If you don't specify host the default value is 127.0.0.1:6379 redisManager.host = 127.0.0.1:6379 #=================================== # Redis Manager [end] #=================================== #========================================= # Redis session DAO [start] #========================================= # Create redisSessionDAO redisSessionDAO = org.crazycake.shiro.RedisSessionDAO # Use redisManager as cache manager redisSessionDAO.redisManager = $redisManager sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager sessionManager.sessionDAO = $redisSessionDAO securityManager.sessionManager = $sessionManager #========================================= # Redis session DAO [end] #========================================= #========================================== # Redis cache manager [start] #========================================== # Create cacheManager cacheManager = org.crazycake.shiro.RedisCacheManager # Principal id field name. The field which you can get unique id to identify this principal. # For example, if you use UserInfo as Principal class, the id field maybe `id`, `userId`, `email`, etc. # Remember to add getter to this id field. For example, `getId()`, `getUserId()`, `getEmail()`, etc. # Default value is id, that means your principal object must has a method called `getId()` cacheManager.principalIdFieldName = id # Use redisManager as cache manager cacheManager.redisManager = $redisManager securityManager.cacheManager = $cacheManager #========================================== # Redis cache manager [end] #========================================== #================================= # shiro-redis configuration [end] #================================= ``` For complete configurable options list, check [Configurable Options](#configurable-options). Here is a [tutorial project](https://github.com/alexxiyang/shiro-redis-tutorial) for you to understand how to configure `shiro-redis` in `shiro.ini`. ### Redis Sentinel if you're using Redis Sentinel, please replace the `redisManager` configuration of the standalone version into the following: ```properties #=================================== # Redis Manager [start] #=================================== # Create redisManager redisManager = org.crazycake.shiro.RedisSentinelManager # Sentinel host. If you don't specify host the default value is 127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381 redisManager.host = 127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381 # Sentinel master name redisManager.masterName = mymaster #=================================== # Redis Manager [end] #=================================== ``` For complete configurable options list, check [Configurable Options](#configurable-options). ### Redis Cluster If you're using redis cluster, please replace the `redisManager` configuration of the standalone version into the following: ```properties #=================================== # Redis Manager [start] #=================================== # Create redisManager redisManager = org.crazycake.shiro.RedisClusterManager # Redis host and port list redisManager.host = 192.168.21.3:7000,192.168.21.3:7001,192.168.21.3:7002,192.168.21.3:7003,192.168.21.3:7004,192.168.21.3:7005 #=================================== # Redis Manager [end] #=================================== ``` For complete configurable options list, check [Configurable Options](#configurable-options). ## Spring If you are using Spring ### Redis Standalone If you are running Redis in Standalone mode ```xml <!-- shiro-redis configuration [start] --> <!-- Redis Manager [start] --> <bean id="redisManager" class="org.crazycake.shiro.RedisManager"> <property name="host" value="127.0.0.1:6379"/> </bean> <!-- Redis Manager [end] --> <!-- Redis session DAO [start] --> <bean id="redisSessionDAO" class="org.crazycake.shiro.RedisSessionDAO"> <property name="redisManager" ref="redisManager" /> </bean> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <property name="sessionDAO" ref="redisSessionDAO" /> </bean> <!-- Redis session DAO [end] --> <!-- Redis cache manager [start] --> <bean id="cacheManager" class="org.crazycake.shiro.RedisCacheManager"> <property name="redisManager" ref="redisManager" /> </bean> <!-- Redis cache manager [end] --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="sessionManager" ref="sessionManager" /> <property name="cacheManager" ref="cacheManager" /> <!-- other configurations --> <property name="realm" ref="exampleRealm"/> <property name="rememberMeManager.cipherKey" value="kPH+bIxk5D2deZiIxcaaaA==" /> </bean> <!-- shiro-redis configuration [end] --> ``` For complete configurable options list, check [Configurable Options](#configurable-options). Here is a [tutorial project](https://github.com/alexxiyang/shiro-redis-spring-tutorial) for you to understand how to configure `shiro-redis` in spring configuration file. ### Redis Sentinel If you use redis sentinel, please replace the `redisManager` configuration of the standalone version into the following: ```xml <!-- shiro-redis configuration [start] --> <!-- shiro redisManager --> <bean id="redisManager" class="org.crazycake.shiro.RedisSentinelManager"> <property name="host" value="127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381"/> <property name="masterName" value="mymaster"/> </bean> ``` For complete configurable options list, check [Configurable Options](#configurable-options). ### Redis Cluster If you use redis cluster, please replace the `redisManager` configuration of the standalone version into the following: ```xml <!-- shiro-redis configuration [start] --> <!-- shiro redisManager --> <bean id="redisManager" class="org.crazycake.shiro.RedisClusterManager"> <property name="host" value="192.168.21.3:7000,192.168.21.3:7001,192.168.21.3:7002,192.168.21.3:7003,192.168.21.3:7004,192.168.21.3:7005"/> </bean> ``` For complete configurable options list, check [Configurable Options](#configurable-options). ## Serializer Since redis only accept `byte[]`, there comes a serializer problem. Shiro-redis is using `StringSerializer` as key serializer and `ObjectSerializer` as value serializer. You can use your own custom serializer, as long as this custom serializer implements `org.crazycake.shiro.serializer.RedisSerializer` For example, we can change the charset of keySerializer like this ```properties # If you want change charset of keySerializer or use your own custom serializer, you need to define serializer first # # cacheManagerKeySerializer = org.crazycake.shiro.serializer.StringSerializer # Supported encodings refer to https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html # UTF-8, UTF-16, UTF-32, ISO-8859-1, GBK, Big5, etc # # cacheManagerKeySerializer.charset = UTF-8 # cacheManager.keySerializer = $cacheManagerKeySerializer ``` These 4 options that you can replace them with your cutom serializers: - cacheManager.keySerializer - cacheManager.valueSerializer - redisSessionDAO.keySerializer - redisSessionDAO.valueSerializer ## Configurable Options Here are all the available options you can use in `shiro-redis` configuration file. ### RedisManager | Title | Default | Description | | :------------------| :------------------- | :---------------------------| | host | `127.0.0.1:6379` | Redis host. If you don't specify host the default value is `127.0.0.1:6379`. If you run redis in sentinel mode or cluster mode, separate host names with comma, like `127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381` | | masterName | `mymaster` | **Only used for sentinel mode**<br>The master node of Redis sentinel mode | | timeout | `2000` | Redis connect timeout. Timeout for jedis try to connect to redis server(In milliseconds) | | soTimeout | `2000` | **Only used for sentinel mode or cluster mode**<br>The timeout for jedis try to read data from redis server | | maxAttempts | `3` | **Only used for cluster mode**<br>Max attempts to connect to server | | password | | Redis password | | database | `0` | Redis database. Default value is 0 | | jedisPoolConfig | `new redis.clients.jedis.JedisPoolConfig()` | JedisPoolConfig. You can create your own JedisPoolConfig instance and set attributes as you wish<br>Most of time, you don't need to set jedisPoolConfig<br>Here is an example.<br>`jedisPoolConfig = redis.clients.jedis.JedisPoolConfig`<br>`jedisPoolConfig.testWhileIdle = false`<br>`redisManager.jedisPoolConfig = jedisPoolConfig` | | count | `100` | Scan count. Shiro-redis use Scan to get keys, so you can define the number of elements returned at every iteration. | | jedisPool | `null` | **Only used for sentinel mode or single mode**<br>You can create your own JedisPool instance and set attributes as you wish | ### RedisSessionDAO | Title | Default | Description | | :------------------| :------------------- | :---------------------------| | redisManager | | RedisManager which you just configured above (Required) | | expire | `-2` | Redis cache key/value expire time. The expire time is in second.<br>Special values:<br>`-1`: no expire<br>`-2`: the same timeout with session<br>Default value: `-2`<br>**Note**: Make sure expire time is longer than session timeout. | | keyPrefix | `shiro:session:` | Custom your redis key prefix for session management<br>**Note**: Remember to add colon at the end of prefix. | | sessionInMemoryTimeout | `1000` | When we do signin, `doReadSession(sessionId)` will be called by shiro about 10 times. So shiro-redis save Session in ThreadLocal to remit this problem. sessionInMemoryTimeout is expiration of Session in ThreadLocal. <br>Most of time, you don't need to change it. | | sessionInMemoryEnabled | `true` | Whether or not enable temporary save session in ThreadLocal | | keySerializer | `org.crazycake.shiro.serializer.StringSerializer` | The key serializer of cache manager<br>You can change the implement of key serializer or the encoding of StringSerializer.<br>Supported encodings refer to [Supported Encodings](https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html). Such as `UTF-8`, `UTF-16`, `UTF-32`, `ISO-8859-1`, `GBK`, `Big5`, etc<br>For more detail, check [Serializer](#serializer) | | valueSerializer | `org.crazycake.shiro.serializer.ObjectSerializer` | The value serializer of cache manager<br>You can change the implement of value serializer<br>For more detail, check [Serializer](#serializer) | ### CacheManager | Title | Default | Description | | :--------------------| :------------------- | :---------------------------| | redisManager | | RedisManager which you just configured above (Required) | | principalIdFieldName | `id` | Principal id field name. The field which you can get unique id to identify this principal.<br>For example, if you use UserInfo as Principal class, the id field maybe `id`, `userId`, `email`, etc.<br>Remember to add getter to this id field. For example, `getId()`, `getUserId(`), `getEmail()`, etc.<br>Default value is `id`, that means your principal object must has a method called `getId()` | | expire | `1800` | Redis cache key/value expire time. <br>The expire time is in second. | | keyPrefix | `shiro:cache:` | Custom your redis key prefix for cache management<br>**Note**: Remember to add colon at the end of prefix. | | keySerializer | `org.crazycake.shiro.serializer.StringSerializer` | The key serializer of cache manager<br>You can change the implement of key serializer or the encoding of StringSerializer.<br>Supported encodings refer to [Supported Encodings](https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html). Such as `UTF-8`, `UTF-16`, `UTF-32`, `ISO-8859-1`, `GBK`, `Big5`, etc<br>For more detail, check [Serializer](#serializer) | | valueSerializer | `org.crazycake.shiro.serializer.ObjectSerializer` | The value serializer of cache manager<br>You can change the implement of value serializer<br>For more detail, check [Serializer](#serializer) | # Spring boot starter Using `Spring-Boot` integration is the easiest way to integrate `shiro-redis` into a Spring-base application. > Note: `shiro-redis-spring-boot-starter` version `3.2.1` is based on `shiro-spring-boot-web-starter` version `1.4.0-RC2` First include the `shiro-redis` Spring boot starter dependency in you application classpath ```xml <dependency> <groupId>org.crazycake</groupId> <artifactId>shiro-redis-spring-boot-starter</artifactId> <version>3.3.1</version> </dependency> ``` The next step depends on whether you've created your own `SessionManager` or `SessionsSecurityManager`. ## If you haven't created your own `SessionManager` or `SessionsSecurityManager` If you don't have your own `SessionManager` or `SessionsSecurityManager` in your configuration, `shiro-redis-spring-boot-starter` will create `RedisSessionDAO` and `RedisCacheManager` for you. Then inject them into `SessionManager` and `SessionsSecurityManager` automatically. So, You are all set. Enjoy it! ## If you have created your own `SessionManager` or `SessionsSecurityManager` If you have created your own `SessionManager` or `SessionsSecurityManager` like this: ```java @Bean public SessionsSecurityManager securityManager(List<Realm> realms) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(realms); // other stuff... return securityManager; } ``` Then inject `redisSessionDAO` and `redisCacheManager` which created by `shiro-redis-spring-boot-starter` already ```java @Autowired RedisSessionDAO redisSessionDAO; @Autowired RedisCacheManager redisCacheManager; ``` Inject them into your own `SessionManager` and `SessionsSecurityManager` ```java @Bean public SessionManager sessionManager() { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); // inject redisSessionDAO sessionManager.setSessionDAO(redisSessionDAO); // other stuff... return sessionManager; } @Bean public SessionsSecurityManager securityManager(List<Realm> realms, SessionManager sessionManager) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(realms); //inject sessionManager securityManager.setSessionManager(sessionManager); // inject redisCacheManager securityManager.setCacheManager(redisCacheManager); // other stuff... return securityManager; } ``` For full example, see [shiro-redis-spring-boot-tutorial](https://github.com/alexxiyang/shiro-redis-spring-boot-tutorial) ### Configuration Properties Here are all available options you can use in Spring-boot starter configuration | Title | Default | Description | | :--------------------------------------------------| :------------------- | :---------------------------| | shiro-redis.enabled | `true` | Enables shiro-redis’s Spring module | | shiro-redis.redis-manager.deploy-mode | `standalone` | Redis deploy mode. Options: `standalone`, `sentinel`, 'cluster' | | shiro-redis.redis-manager.host | `127.0.0.1:6379` | Redis host. If you don't specify host the default value is `127.0.0.1:6379`. If you run redis in sentinel mode or cluster mode, separate host names with comma, like `127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381` | | shiro-redis.redis-manager.master-name | `mymaster` | **Only used for sentinel mode**<br>The master node of Redis sentinel mode | | shiro-redis.redis-manager.timeout | `2000` | Redis connect timeout. Timeout for jedis try to connect to redis server(In milliseconds) | | shiro-redis.redis-manager.so-timeout | `2000` | **Only used for sentinel mode or cluster mode**<br>The timeout for jedis try to read data from redis server | | shiro-redis.redis-manager.max-attempts | `3` | **Only used for cluster mode**<br>Max attempts to connect to server | | shiro-redis.redis-manager.password | | Redis password | | shiro-redis.redis-manager.database | `0` | Redis database. Default value is 0 | | shiro-redis.redis-manager.count | `100` | Scan count. Shiro-redis use Scan to get keys, so you can define the number of elements returned at every iteration. | | shiro-redis.session-dao.expire | `-2` | Redis cache key/value expire time. The expire time is in second.<br>Special values:<br>`-1`: no expire<br>`-2`: the same timeout with session<br>Default value: `-2`<br>**Note**: Make sure expire time is longer than session timeout. | | shiro-redis.session-dao.key-prefix | `shiro:session:` | Custom your redis key prefix for session management<br>**Note**: Remember to add colon at the end of prefix. | | shiro-redis.session-dao.session-in-memory-timeout | `1000` | When we do signin, `doReadSession(sessionId)` will be called by shiro about 10 times. So shiro-redis save Session in ThreadLocal to remit this problem. sessionInMemoryTimeout is expiration of Session in ThreadLocal. <br>Most of time, you don't need to change it. | | shiro-redis.session-dao.session-in-memory-enabled | `true` | Whether or not enable temporary save session in ThreadLocal | | shiro-redis.cache-manager.principal-id-field-name | `id` | Principal id field name. The field which you can get unique id to identify this principal.<br>For example, if you use UserInfo as Principal class, the id field maybe `id`, `userId`, `email`, etc.<br>Remember to add getter to this id field. For example, `getId()`, `getUserId(`), `getEmail()`, etc.<br>Default value is `id`, that means your principal object must has a method called `getId()` | | shiro-redis.cache-manager.expire | `1800` | Redis cache key/value expire time. <br>The expire time is in second. | | shiro-redis.cache-manager.key-prefix | `shiro:cache:` | Custom your redis key prefix for cache management<br>**Note**: Remember to add colon at the end of prefix. | ## Working with `spring-boot-devtools` If you are using `shiro-redis` with `spring-boot-devtools`. Please add this line to `resources/META-INF/spring-devtools.properties` (Create it if there is no this file): ```ini restart.include.shiro-redis=/shiro-[\\w-\\.]+jar ``` # If you found any bugs Please create the issue 可以用中文 <MSG> Add Maven badge <DFF> @@ -2,7 +2,7 @@ shiro-redis ============= [![Build Status](https://travis-ci.org/alexxiyang/shiro-redis.svg?branch=master)](https://travis-ci.org/alexxiyang/shiro-redis) - +[![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.crazycake/shiro-redis/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.crazycake/shiro-redis) shiro only provide the support of ehcache and concurrentHashMap. Here is an implement of redis cache can be used by shiro. Hope it will help you!
1
Add Maven badge
1
.md
md
mit
alexxiyang/shiro-redis
1681
<NME> RedisSessionDAOTest.java <BEF> package org.crazycake.shiro; import org.apache.shiro.session.InvalidSessionException; import org.apache.shiro.session.Session; import org.crazycake.shiro.exception.SerializationException; import org.crazycake.shiro.serializer.ObjectSerializer; import org.crazycake.shiro.serializer.StringSerializer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Set; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.*; public class RedisSessionDAOTest { private IRedisManager redisManager; private StringSerializer keySerializer = new StringSerializer(); private ObjectSerializer valueSerializer = new ObjectSerializer(); @BeforeEach public void setUp() { redisManager = mock(IRedisManager.class); } private RedisSessionDAO mountRedisSessionDAO(Integer expire) { RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); if (expire != null) { redisSessionDAO.setExpire(expire); } redisSessionDAO.setKeyPrefix("student:"); redisSessionDAO.setRedisManager(redisManager); return redisSessionDAO; } @Test public void testUpdate() throws SerializationException { RedisSessionDAO sessionDAO = mountRedisSessionDAO(null); StudentSession session = new StudentSession(99, 2000); sessionDAO.update(session); verify(redisManager).set(keySerializer.serialize("student:99"), valueSerializer.serialize(session), 2); } @Test public void testUpdateByCustomExpire() throws SerializationException { RedisSessionDAO sessionDAO = mountRedisSessionDAO(3); StudentSession session = new StudentSession(98, 2000); sessionDAO.update(session); verify(redisManager).set(keySerializer.serialize("student:98"), valueSerializer.serialize(session), 3); } @Test public void testUpdateByNoExpire() throws SerializationException { RedisSessionDAO sessionDAO = mountRedisSessionDAO(-1); StudentSession session = new StudentSession(97, 2000); sessionDAO.update(session); verify(redisManager).set(keySerializer.serialize("student:97"), valueSerializer.serialize(session), -1); } @Test public void testDelete() throws SerializationException { RedisSessionDAO sessionDAO = mountRedisSessionDAO(null); StudentSession session = new StudentSession(96, 1000); sessionDAO.delete(session); verify(redisManager).del(keySerializer.serialize("student:96")); } @Test public void testGetActiveSessions() throws SerializationException { Set<byte[]> mockKeys = new HashSet<byte[]>(); mockKeys.add(keySerializer.serialize("student:1")); mockKeys.add(keySerializer.serialize("student:2")); when(redisManager.keys(keySerializer.serialize("student:*"))).thenReturn(mockKeys); StudentSession mockSession1 = new StudentSession(1, 2000); StudentSession mockSession2 = new StudentSession(2, 2000); when(redisManager.get(keySerializer.serialize("student:1"))).thenReturn(valueSerializer.serialize(mockSession1)); when(redisManager.get(keySerializer.serialize("student:2"))).thenReturn(valueSerializer.serialize(mockSession2)); @Test public void testUpdate() { redisSessionDAO.doCreate(session1); doChangeSessionName(session1, name1); redisSessionDAO.update(session1); FakeSession actualSession = (FakeSession)redisSessionDAO.doReadSession(session1.getId()); } @Override public Date getStartTimestamp() { return null; } @Override public Date getLastAccessTime() { return null; } @Override public long getTimeout() throws InvalidSessionException { return timeout; } @Override public void setTimeout(long l) throws InvalidSessionException { } @Override public String getHost() { return null; } @Override public void touch() throws InvalidSessionException { } @Override public void stop() throws InvalidSessionException { } @Override public Collection<Object> getAttributeKeys() throws InvalidSessionException { return null; } @Override public Object getAttribute(Object o) throws InvalidSessionException { return null; } @Override public void setAttribute(Object o, Object o1) throws InvalidSessionException { } @Override public Object removeAttribute(Object o) throws InvalidSessionException { return null; } } <MSG> 1. Include sessionInMemory update in sessionDAO.doUpdate 2. Add sessionInMemoryEnabled to turn on/off sessionInMemory <DFF> @@ -86,6 +86,18 @@ public class RedisSessionDAOTest { @Test public void testUpdate() { redisSessionDAO.doCreate(session1); + redisSessionDAO.doReadSession(session1.getId()); + doChangeSessionName(session1, name1); + redisSessionDAO.update(session1); + FakeSession actualSession = (FakeSession)redisSessionDAO.doReadSession(session1.getId()); + assertEquals(actualSession.getName(), name1); + } + + @Test + public void testUpdateWithoutSessionInMemory() { + redisSessionDAO.setSessionInMemoryEnabled(false); + redisSessionDAO.doCreate(session1); + redisSessionDAO.doReadSession(session1.getId()); doChangeSessionName(session1, name1); redisSessionDAO.update(session1); FakeSession actualSession = (FakeSession)redisSessionDAO.doReadSession(session1.getId());
12
1. Include sessionInMemory update in sessionDAO.doUpdate 2. Add sessionInMemoryEnabled to turn on/off sessionInMemory
0
.java
java
mit
alexxiyang/shiro-redis
1682
<NME> hitchmysql.rst <BEF> HitchMySQL ========== .. note:: This documentation applies to the latest version of hitchmysql. HitchMySQL is a :doc:`/glossary/hitch_plugin` created to make testing applications that use MySQL easier. It contains: * A :doc:`/glossary/hitch_package` to download and install specified version(s) of MySQL. * A :doc:`/glossary/service` to set up an isolated MySQL environment and run it. Note: the MySQL service destroys and sets up a new database during each test run in order to provide strict :doc:`/glossary/isolation` for your tests. Installation ------------ First, install the the plugin in your tests directory:: $ hitch install hitchmysql Set up MySQL ------------ In your test, define the MySQL installation you want to test with: .. code-block:: python import hitchmysql mysql_package = hitchmysql.MySQLPackage( version="5.6.26" # Optional (default is the latest version of MySQL) ) # Downloads & installs MySQL to ~/.hitchpkg if not already installed by previous test mysql_package.build() To use, define the service after initializing the :doc:`/glossary/service_bundle` but before starting it: .. note:: See also: :doc:`/api/generic_service_api` .. code-block:: python # Define a MySQL user for your service to set up mysql_user = hitchmysql.MySQLUser("newpguser", "pguserpassword") # Define a MySQL database for your service to set up mysql_database = hitchmysql.MySQLDatabase( name="databasename", # Mandatory owner=mysql_user, # Mandatory dump="dumps/yourdump.sql" # Optional (default: create empty database) ) self.services['MySQL'] = hitchpostgres.PostgresService( mysql_package=mysql_package, # Mandatory port=13306, # Optional (default: 13306) users=[mysql_user, ], # Optional (default: no users) databases=[mysql_database, ] # Optional (default: no databases) ) Interacting with MySQL ---------------------- Once it is running, you can interact with the service and its databases:: In [1]: self.services['MySQL'].databases[0].mysql("SELECT * FROM yourtable;").run() [ Prints output ] In [2]: self.services['MySQL'].databases[0].mysql().run() [ Launches into mysql shell ] <MSG> DOCS : Fixed errant reference to Postgres -- https://github.com/hitchtest/hitchmysql/issues/1 (hat tip @kevindixon) <DFF> @@ -58,7 +58,7 @@ To use, define the service after initializing the :doc:`/glossary/service_bundle dump="dumps/yourdump.sql" # Optional (default: create empty database) ) - self.services['MySQL'] = hitchpostgres.PostgresService( + self.services['MySQL'] = hitchmysql.MySQLService( mysql_package=mysql_package, # Mandatory port=13306, # Optional (default: 13306) users=[mysql_user, ], # Optional (default: no users)
1
DOCS : Fixed errant reference to Postgres -- https://github.com/hitchtest/hitchmysql/issues/1 (hat tip @kevindixon)
1
.rst
rst
agpl-3.0
hitchtest/hitch
1683
<NME> RedisSentinelManager.java <BEF> package org.crazycake.shiro; import org.crazycake.shiro.common.WorkAloneRedisManager; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis.Protocol; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class RedisSentinelManager extends WorkAloneRedisManager implements IRedisManager { private static final String DEFAULT_HOST = "127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381"; private String host = DEFAULT_HOST; private static final String DEFAULT_MASTER_NAME = "mymaster"; private String masterName = DEFAULT_MASTER_NAME; // timeout for jedis try to connect to redis server, not expire time! In milliseconds private int timeout = Protocol.DEFAULT_TIMEOUT; // timeout for jedis try to read data from redis server private int soTimeout = Protocol.DEFAULT_TIMEOUT; private String password; private int database = Protocol.DEFAULT_DATABASE; private JedisSentinelPool jedisPool; @Override protected Jedis getJedis() { init(); } return jedisPool.getResource(); } private void init() { if (jedisPool == null) { synchronized (RedisSentinelManager.class) { if (jedisPool == null) { String[] sentinelHosts = host.split(",\\s*"); Set<String> sentinels = new HashSet<String>(); Collections.addAll(sentinels, sentinelHosts); jedisPool = new JedisSentinelPool(masterName, sentinels, getJedisPoolConfig(), timeout, soTimeout, password, database); } } } } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getDatabase() { return database; } public void setDatabase(int database) { this.database = database; } public String getMasterName() { return masterName; } public void setMasterName(String masterName) { this.masterName = masterName; } public int getSoTimeout() { return soTimeout; } public void setSoTimeout(int soTimeout) { this.soTimeout = soTimeout; } public JedisSentinelPool getJedisPool() { return jedisPool; } public void setJedisPool(JedisSentinelPool jedisPool) { this.jedisPool = jedisPool; } } <MSG> Merge branch 'master' of github.com:alexxiyang/shiro-redis <DFF> @@ -28,7 +28,7 @@ public class RedisSentinelManager extends WorkAloneRedisManager implements IRedi private int database = Protocol.DEFAULT_DATABASE; - private JedisSentinelPool jedisPool; + private volatile JedisSentinelPool jedisPool; @Override protected Jedis getJedis() {
1
Merge branch 'master' of github.com:alexxiyang/shiro-redis
1
.java
java
mit
alexxiyang/shiro-redis
1684
<NME> dense_concat_op.cc <BEF> ADDFILE <MSG> add custom concat op for densenet <DFF> @@ -0,0 +1,81 @@ +#include "operators/vision/dense_concat_op.h" +#include "core/workspace.h" +#include "utils/op_kernel.h" + +namespace dragon { + +template <class Context> +void DenseConcatOp<Context>::RunOnDevice() { + ConcatOp<Context>::RunOnDevice(); + input(0).Release(); // keep shape, just release mem +} + +DEPLOY_CPU(DenseConcat); +#ifdef WITH_CUDA +DEPLOY_CUDA(DenseConcat); +#endif +OPERATOR_SCHEMA(DenseConcat).NumInputs(2).NumOutputs(1); + +template <class Context> template <typename T> +void DenseConcatGradientOp<Context>::RunWithType() { + // restore X1 from Y + auto* Ydata = input(-2).template data<T, Context>(); + auto* Xdata = input(0).template mutable_data<T, Context>(); + this->x_concat_dim = input(0).dim(this->axis); + TIndex count = input(0).count(); + this->concat_dims = input(-1).dims(); + this->y_concat_dim = this->concat_dims[this->axis]; + this->outer_dim = input(-1).count(0, this->axis); + this->inner_dim = input(-1).count(this->axis + 1); + kernel::ConcatGrad<T, Context>(count, + this->outer_dim, + this->inner_dim, + this->x_concat_dim, + this->y_concat_dim, + 0, + Ydata, + Xdata, + &ctx()); +} + +template <class Context> +void DenseConcatGradientOp<Context>::RunOnDevice() { + if (input(0).template IsType<float>()) RunWithType<float>(); + else if (input(0).template IsType<float16>()) RunWithType<float16>(); + else LOG(FATAL) << "unsupported input types."; + + ConcatGradientOp<Context>::RunOnDevice(); +} + +template <class Context> +void DenseConcatGradientOp<Context>::ShareBeforeRun() { + Tensor* dX = ws()->GetBuffer(); + if (dX != nullptr) output(0)->Replace(*dX); +} + +template <class Context> +void DenseConcatGradientOp<Context>::ClearAfterRun() { + Tensor* dY = &input(-1); + Tensor* Y = &input(-2); + ws()->ReleaseBuffer(dY); + ws()->ReleaseBuffer(Y, true); +} + +DEPLOY_CPU(DenseConcatGradient); +#ifdef WITH_CUDA +DEPLOY_CUDA(DenseConcatGradient); +#endif +OPERATOR_SCHEMA(DenseConcatGradient).NumInputs(4).NumOutputs(2); + +class GetDenseConcatGradient : public GradientMakerBase { +public: + GRADIENT_MAKER_CTOR(GetDenseConcatGradient); + vector<OperatorDef> MakeDefs() override { + return SingleDef(def.type() + "Gradient", "", + vector<string> {I(0), I(1), O(0), GO(0)}, + vector<string> {GI(0), GI(1)}); + } +}; +REGISTER_GRADIENT(DenseConcat, GetDenseConcatGradient); + +} // namespace dragon \ No newline at end of file
81
add custom concat op for densenet
0
.cc
cc
bsd-2-clause
neopenx/Dragon
1685
<NME> dense_concat_op.cc <BEF> ADDFILE <MSG> add custom concat op for densenet <DFF> @@ -0,0 +1,81 @@ +#include "operators/vision/dense_concat_op.h" +#include "core/workspace.h" +#include "utils/op_kernel.h" + +namespace dragon { + +template <class Context> +void DenseConcatOp<Context>::RunOnDevice() { + ConcatOp<Context>::RunOnDevice(); + input(0).Release(); // keep shape, just release mem +} + +DEPLOY_CPU(DenseConcat); +#ifdef WITH_CUDA +DEPLOY_CUDA(DenseConcat); +#endif +OPERATOR_SCHEMA(DenseConcat).NumInputs(2).NumOutputs(1); + +template <class Context> template <typename T> +void DenseConcatGradientOp<Context>::RunWithType() { + // restore X1 from Y + auto* Ydata = input(-2).template data<T, Context>(); + auto* Xdata = input(0).template mutable_data<T, Context>(); + this->x_concat_dim = input(0).dim(this->axis); + TIndex count = input(0).count(); + this->concat_dims = input(-1).dims(); + this->y_concat_dim = this->concat_dims[this->axis]; + this->outer_dim = input(-1).count(0, this->axis); + this->inner_dim = input(-1).count(this->axis + 1); + kernel::ConcatGrad<T, Context>(count, + this->outer_dim, + this->inner_dim, + this->x_concat_dim, + this->y_concat_dim, + 0, + Ydata, + Xdata, + &ctx()); +} + +template <class Context> +void DenseConcatGradientOp<Context>::RunOnDevice() { + if (input(0).template IsType<float>()) RunWithType<float>(); + else if (input(0).template IsType<float16>()) RunWithType<float16>(); + else LOG(FATAL) << "unsupported input types."; + + ConcatGradientOp<Context>::RunOnDevice(); +} + +template <class Context> +void DenseConcatGradientOp<Context>::ShareBeforeRun() { + Tensor* dX = ws()->GetBuffer(); + if (dX != nullptr) output(0)->Replace(*dX); +} + +template <class Context> +void DenseConcatGradientOp<Context>::ClearAfterRun() { + Tensor* dY = &input(-1); + Tensor* Y = &input(-2); + ws()->ReleaseBuffer(dY); + ws()->ReleaseBuffer(Y, true); +} + +DEPLOY_CPU(DenseConcatGradient); +#ifdef WITH_CUDA +DEPLOY_CUDA(DenseConcatGradient); +#endif +OPERATOR_SCHEMA(DenseConcatGradient).NumInputs(4).NumOutputs(2); + +class GetDenseConcatGradient : public GradientMakerBase { +public: + GRADIENT_MAKER_CTOR(GetDenseConcatGradient); + vector<OperatorDef> MakeDefs() override { + return SingleDef(def.type() + "Gradient", "", + vector<string> {I(0), I(1), O(0), GO(0)}, + vector<string> {GI(0), GI(1)}); + } +}; +REGISTER_GRADIENT(DenseConcat, GetDenseConcatGradient); + +} // namespace dragon \ No newline at end of file
81
add custom concat op for densenet
0
.cc
cc
bsd-2-clause
neopenx/Dragon
1686
<NME> RedisCacheTest.java <BEF> package org.crazycake.shiro; import org.apache.shiro.subject.PrincipalCollection; import org.crazycake.shiro.exception.SerializationException; import org.crazycake.shiro.serializer.ObjectSerializer; import org.crazycake.shiro.serializer.StringSerializer; import org.junit.jupiter.api.Assertions; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RedisCacheTest { import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.*; import static org.mockito.Mockito.*; public class RedisCacheTest { private IRedisManager redisManager; private StringSerializer keySerializer = new StringSerializer(); private ObjectSerializer valueSerializer = new ObjectSerializer(); private FakeSession tomSession; private FakeSession paulSession; private FakeSession billySession; @Before public void setUp() throws SerializationException, NoSuchFieldException, IllegalAccessException { return new RedisCache(redisManager, new StringSerializer(), new ObjectSerializer(), "employee:", 1, RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME); } @Test public void testInitialize() { Assertions.assertThrows(IllegalArgumentException.class, () -> new RedisCache<String, String>(null, null, null, "abc:", 1, RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME)); Assertions.assertThrows(IllegalArgumentException.class, () -> new RedisCache<String, String>(new RedisManager(), null, null, "abc:", 1, RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME)); Assertions.assertThrows(IllegalArgumentException.class, () -> new RedisCache<String, String>(new RedisManager(), new StringSerializer(), null, "abc:", 1, RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME)); } @Test public void testPut() throws SerializationException { RedisCache rc = mountRedisCache(); Object value = rc.put("foo", "bar"); assertThat(value, is("bar")); verify(redisManager).set(keySerializer.serialize("employee:foo"), valueSerializer.serialize("bar"), 1); PrincipalCollection principal = new EmployeePrincipal(3); rc.put(principal, "account information"); verify(redisManager).set(keySerializer.serialize("employee:3"), valueSerializer.serialize("account information"), 1); } } when(redisManager.get(keySerializer.serialize(testPrefix + "paul"))).thenReturn(valueSerializer.serialize(paulSession)); when(redisManager.get(keySerializer.serialize(testPrefix + "billy"))).thenReturn(valueSerializer.serialize(billySession)); redisCache = new RedisCache<String, FakeSession>(redisManager, keySerializer, valueSerializer, testPrefix, 1); } @Test public int getId() { return this.id; } } class EmployeePrincipal implements PrincipalCollection { private Employee primaryPrincipal; public EmployeePrincipal(int id) { this.primaryPrincipal = new Employee(id); } @Override public Employee getPrimaryPrincipal() { return this.primaryPrincipal; } @Override public <T> T oneByType(Class<T> aClass) { return null; } @Override public <T> Collection<T> byType(Class<T> aClass) { return null; } @Override public List asList() { @Test public void testPut() { redisCache.put(null, null); redisCache.put(null, new FakeSession()); redisCache.put(testKey, testValue); } @Override public Collection fromRealm(String s) { return null; } @Override public Set<String> getRealmNames() { return null; } @Override public boolean isEmpty() { return false; } @Override public Iterator iterator() { return null; } } <MSG> Enhance unit test <DFF> @@ -8,8 +8,7 @@ import java.util.*; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; public class RedisCacheTest { @@ -25,6 +24,7 @@ public class RedisCacheTest { private FakeSession tomSession; private FakeSession paulSession; private FakeSession billySession; + private byte[] nullValueByte; @Before public void setUp() throws SerializationException, NoSuchFieldException, IllegalAccessException { @@ -54,6 +54,8 @@ public class RedisCacheTest { when(redisManager.get(keySerializer.serialize(testPrefix + "paul"))).thenReturn(valueSerializer.serialize(paulSession)); when(redisManager.get(keySerializer.serialize(testPrefix + "billy"))).thenReturn(valueSerializer.serialize(billySession)); redisCache = new RedisCache<String, FakeSession>(redisManager, keySerializer, valueSerializer, testPrefix, 1); + + nullValueByte = new byte[0]; } @Test @@ -90,6 +92,7 @@ public class RedisCacheTest { @Test public void testPut() { redisCache.put(null, null); + verify(redisManager, times(1)).set(null, nullValueByte, 1); redisCache.put(null, new FakeSession()); redisCache.put(testKey, testValue); }
5
Enhance unit test
2
.java
java
mit
alexxiyang/shiro-redis
1687
<NME> RedisCacheManager.java <BEF> package org.crazycake.shiro; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheException; import org.apache.shiro.cache.CacheManager; import org.crazycake.shiro.serializer.ObjectSerializer; import org.crazycake.shiro.serializer.RedisSerializer; import org.crazycake.shiro.serializer.StringSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class RedisCacheManager implements CacheManager { private final Logger logger = LoggerFactory.getLogger(RedisCacheManager.class); // fast lookup by name map private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<>(); private RedisSerializer keySerializer = new StringSerializer(); private RedisSerializer valueSerializer = new ObjectSerializer(); /** * The Redis key prefix for caches */ private String keyPrefix = "shiro:cache:"; @Override public <K, V> Cache<K, V> getCache(String name) throws CacheException { * The Redis key prefix for caches */ public static final String DEFAULT_CACHE_KEY_PREFIX = "shiro:cache:"; private String keyPrefix = DEFAULT_CACHE_KEY_PREFIX; public static final String DEFAULT_PRINCIPAL_ID_FIELD_NAME = "id"; private String principalIdFieldName = DEFAULT_PRINCIPAL_ID_FIELD_NAME; @Override public <K, V> Cache<K, V> getCache(String name) throws CacheException { logger.debug("get cache, name=" + name); Cache<K, V> cache = caches.get(name); if (cache == null) { cache = new RedisCache<K, V>(redisManager, keySerializer, valueSerializer, keyPrefix + name + ":", expire, principalIdFieldName); caches.put(name, cache); } return cache; } public IRedisManager getRedisManager() { return redisManager; } public void setRedisManager(IRedisManager redisManager) { this.redisManager = redisManager; } public String getKeyPrefix() { return keyPrefix; } public void setKeyPrefix(String keyPrefix) { this.keyPrefix = keyPrefix; } public RedisSerializer getKeySerializer() { return keySerializer; } public void setKeySerializer(RedisSerializer keySerializer) { this.keySerializer = keySerializer; } public RedisSerializer getValueSerializer() { return valueSerializer; } public void setValueSerializer(RedisSerializer valueSerializer) { this.valueSerializer = valueSerializer; } public int getExpire() { return expire; } public void setExpire(int expire) { this.expire = expire; } public String getPrincipalIdFieldName() { return principalIdFieldName; } public void setPrincipalIdFieldName(String principalIdFieldName) { this.principalIdFieldName = principalIdFieldName; } } <MSG> Move cache key prefix to redisCacheManager <DFF> @@ -23,7 +23,8 @@ public class RedisCacheManager implements CacheManager { /** * The Redis key prefix for caches */ - private String keyPrefix = "shiro:cache:"; + public static final String DEFAULT_CACHE_KEY_PREFIX = "shiro:cache:"; + private String keyPrefix = DEFAULT_CACHE_KEY_PREFIX; @Override public <K, V> Cache<K, V> getCache(String name) throws CacheException {
2
Move cache key prefix to redisCacheManager
1
.java
java
mit
alexxiyang/shiro-redis
1688
<NME> README.md <BEF> shiro-redis ============= ## Introduction shiro only provide the support of ehcache and concurrentHashMap. Here is an implement of redis cache can be used by shiro. Hope it will help you! ## Documentation Official documentation [is located here](http://alexxiyang.github.io/shiro-redis/). <dependency> <groupId>org.crazycake</groupId> <artifactId>shiro-redis</artifactId> <version>3.1.0</version> </dependency> ``` <MSG> Update README.md Release 3.2.0 <DFF> @@ -16,7 +16,7 @@ You can choose these 2 ways to include shiro-redis into your project <dependency> <groupId>org.crazycake</groupId> <artifactId>shiro-redis</artifactId> - <version>3.1.0</version> + <version>3.2.0</version> </dependency> ```
1
Update README.md
1
.md
md
mit
alexxiyang/shiro-redis
1689
<NME> RedisCache.java <BEF> package org.crazycake.shiro; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheException; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.CollectionUtils; import org.crazycake.shiro.exception.CacheManagerPrincipalIdNotAssignedException; import org.crazycake.shiro.exception.PrincipalIdNullException; import org.crazycake.shiro.exception.PrincipalInstanceException; import org.crazycake.shiro.exception.SerializationException; import org.crazycake.shiro.serializer.RedisSerializer; import org.crazycake.shiro.serializer.StringSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** * Used for setting/getting authorization information from Redis * @param <K> * @param <V> */ public class RedisCache<K, V> implements Cache<K, V> { private static Logger logger = LoggerFactory.getLogger(RedisCache.class); private RedisSerializer keySerializer; private String principalIdFieldName = RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME; /** * Construction * @param redisManager */ public RedisCache(IRedisManager redisManager, RedisSerializer keySerializer, RedisSerializer valueSerializer, String prefix, int expire, String principalIdFieldName) { if (redisManager == null) { * @param principalIdFieldName id field name of principal object */ public RedisCache(IRedisManager redisManager, RedisSerializer keySerializer, RedisSerializer valueSerializer, String prefix, int expire, String principalIdFieldName) { if (redisManager == null) { throw new IllegalArgumentException("redisManager cannot be null."); } this.redisManager = redisManager; if (keySerializer == null) { throw new IllegalArgumentException("keySerializer cannot be null."); } this.keySerializer = keySerializer; if (valueSerializer == null) { throw new IllegalArgumentException("valueSerializer cannot be null."); } this.valueSerializer = valueSerializer; if (prefix != null && !"".equals(prefix)) { this.keyPrefix = prefix; } this.expire = expire; /** * get shiro authorization redis key-value * @param key * @return * @throws CacheException */ @Override public V get(K key) throws CacheException { * @throws CacheException get cache exception */ @Override public V get(K key) throws CacheException { logger.debug("get key [" + key + "]"); if (key == null) { return null; } try { Object redisCacheKey = getRedisCacheKey(key); byte[] rawValue = redisManager.get(keySerializer.serialize(redisCacheKey)); if (rawValue == null) { return null; } V value = (V) valueSerializer.deserialize(rawValue); return value; } catch (SerializationException e) { throw new CacheException(e); } } @Override public V put(K key, V value) throws CacheException { if (key == null) { logger.warn("Saving a null key is meaningless, return value directly without call Redis."); return value; } try { Object redisCacheKey = getRedisCacheKey(key); logger.debug("put key [" + redisCacheKey + "]"); redisManager.set(keySerializer.serialize(redisCacheKey), value != null ? valueSerializer.serialize(value) : null, expire); return value; } catch (SerializationException e) { throw new CacheException(e); } } @Override public V remove(K key) throws CacheException { logger.debug("remove key [" + key + "]"); if (key == null) { return null; } try { Object redisCacheKey = getRedisCacheKey(key); byte[] rawValue = redisManager.get(keySerializer.serialize(redisCacheKey)); V previous = (V) valueSerializer.deserialize(rawValue); redisManager.del(keySerializer.serialize(redisCacheKey)); return previous; } catch (SerializationException e) { throw new CacheException(e); } } /** * get the full Redis key including prefix by Redis key * @param key * @return */ private Object getRedisCacheKey(K key) { if (key == null) { return null; } if (keySerializer instanceof StringSerializer) { return this.keyPrefix + getStringRedisKey(key); } return key; } /** * get Redis key (not including prefix) * @param key * @return */ private String getStringRedisKey(K key) { String redisKey; if (key instanceof PrincipalCollection) { redisKey = getRedisKeyFromPrincipalIdField((PrincipalCollection) key); } else { redisKey = key.toString(); } return redisKey; } /** * get the Redis key (not including prefix) by PrincipalCollection * @param key * @return */ private String getRedisKeyFromPrincipalIdField(PrincipalCollection key) { Object principalObject = key.getPrimaryPrincipal(); if (principalObject instanceof String) { return principalObject.toString(); } Method pincipalIdGetter = getPrincipalIdGetter(principalObject); return getIdObj(principalObject, pincipalIdGetter); } private String getIdObj(Object principalObject, Method pincipalIdGetter) { String redisKey; try { Object idObj = pincipalIdGetter.invoke(principalObject); if (idObj == null) { throw new PrincipalIdNullException(principalObject.getClass(), this.principalIdFieldName); } redisKey = idObj.toString(); } catch (IllegalAccessException e) { throw new PrincipalInstanceException(principalObject.getClass(), this.principalIdFieldName, e); } catch (InvocationTargetException e) { throw new PrincipalInstanceException(principalObject.getClass(), this.principalIdFieldName, e); } return redisKey; } private Method getPrincipalIdGetter(Object principalObject) { Method pincipalIdGetter = null; String principalIdMethodName = this.getPrincipalIdMethodName(); try { pincipalIdGetter = principalObject.getClass().getMethod(principalIdMethodName); } catch (NoSuchMethodException e) { throw new PrincipalInstanceException(principalObject.getClass(), this.principalIdFieldName); } return pincipalIdGetter; } private String getPrincipalIdMethodName() { if (this.principalIdFieldName == null || "".equals(this.principalIdFieldName)) { /** * get all authorization key-value quantity * @return */ @Override public int size() { public void clear() throws CacheException { logger.debug("clear cache"); Set<byte[]> keys = null; try { keys = redisManager.keys(keySerializer.serialize(this.keyPrefix + "*")); } catch (SerializationException e) { logger.error("get keys error", e); } if (keys == null || keys.size() == 0) { return; } for (byte[] key: keys) { redisManager.del(key); } } /** * get all authorization key-value quantity * @return key-value size */ @Override public int size() { Long longSize = 0L; try { longSize = new Long(redisManager.dbSize(keySerializer.serialize(this.keyPrefix + "*"))); } catch (SerializationException e) { logger.error("get keys error", e); } return longSize.intValue(); } @SuppressWarnings("unchecked") @Override public Set<K> keys() { Set<byte[]> keys = null; try { keys = redisManager.keys(keySerializer.serialize(this.keyPrefix + "*")); } catch (SerializationException e) { logger.error("get keys error", e); return Collections.emptySet(); } if (CollectionUtils.isEmpty(keys)) { return Collections.emptySet(); } Set<K> convertedKeys = new HashSet<K>(); for (byte[] key:keys) { try { convertedKeys.add((K) keySerializer.deserialize(key)); } catch (SerializationException e) { logger.error("deserialize keys error", e); } } return convertedKeys; } @Override public Collection<V> values() { Set<byte[]> keys = null; try { keys = redisManager.keys(keySerializer.serialize(this.keyPrefix + "*")); } catch (SerializationException e) { logger.error("get values error", e); return Collections.emptySet(); } if (CollectionUtils.isEmpty(keys)) { return Collections.emptySet(); } List<V> values = new ArrayList<V>(keys.size()); for (byte[] key : keys) { V value = null; try { value = (V) valueSerializer.deserialize(redisManager.get(key)); } catch (SerializationException e) { logger.error("deserialize values= error", e); } if (value != null) { values.add(value); } } return Collections.unmodifiableList(values); } public String getKeyPrefix() { return keyPrefix; } public void setKeyPrefix(String keyPrefix) { this.keyPrefix = keyPrefix; } public String getPrincipalIdFieldName() { return principalIdFieldName; } public void setPrincipalIdFieldName(String principalIdFieldName) { this.principalIdFieldName = principalIdFieldName; } } <MSG> Fix checkstyle error <DFF> @@ -30,8 +30,13 @@ public class RedisCache<K, V> implements Cache<K, V> { private String principalIdFieldName = RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME; /** - * Construction - * @param redisManager + * + * @param redisManager redisManager + * @param keySerializer keySerializer + * @param valueSerializer valueSerializer + * @param prefix authorization prefix + * @param expire expire + * @param principalIdFieldName id field name of principal object */ public RedisCache(IRedisManager redisManager, RedisSerializer keySerializer, RedisSerializer valueSerializer, String prefix, int expire, String principalIdFieldName) { if (redisManager == null) { @@ -57,9 +62,9 @@ public class RedisCache<K, V> implements Cache<K, V> { /** * get shiro authorization redis key-value - * @param key - * @return - * @throws CacheException + * @param key key + * @return value + * @throws CacheException get cache exception */ @Override public V get(K key) throws CacheException { @@ -195,7 +200,7 @@ public class RedisCache<K, V> implements Cache<K, V> { /** * get all authorization key-value quantity - * @return + * @return key-value size */ @Override public int size() {
11
Fix checkstyle error
6
.java
java
mit
alexxiyang/shiro-redis
1690
<NME> README.md <BEF> shiro-redis ============= ## Introduction shiro only provide the support of ehcache and concurrentHashMap. Here is an implement of redis cache can be used by shiro. Hope it will help you! ## Documentation Official documentation [is located here](http://alexxiyang.github.io/shiro-redis/). ## If you haven't created your own `SessionManager` or `SessionsSecurityManager` You are good to go. ## If you have created your own `SessionManager` or `SessionsSecurityManager` <MSG> Update README.md <DFF> @@ -364,7 +364,7 @@ You will have to inject them by yourself. for more deail, see below ## If you haven't created your own `SessionManager` or `SessionsSecurityManager` -You are good to go. +You are all set. ## If you have created your own `SessionManager` or `SessionsSecurityManager`
1
Update README.md
1
.md
md
mit
alexxiyang/shiro-redis
1691
<NME> hitchnode.rst <BEF> ADDFILE <MSG> add doc for basic usage of hitchnode <DFF> @@ -0,0 +1,59 @@ +HitchNode +========== + +.. note:: + + This documentation applies to the latest version of hitchnode. + +HitchNode is a :doc:`/glossary/hitch_plugin` created to make testing applications that use Node easier. + +It contains: + +* A :doc:`/glossary/hitch_package` to download and install specified version(s) of Node. +* A :doc:`/glossary/service` to set up an isolated Node environment and run it. + +Note: the Node service destroys and sets up a new node environment during each test run in order +to provide strict :doc:`/glossary/isolation` for your tests. + +Installation +------------ + +First, install the the plugin in your tests directory:: + + $ hitch install hitchnode + + +Set up Node +------------ + +In your test, define the Node installation you want to test with: + +.. code-block:: python + + import hitchnode + + node_package = hitchnode.NodePackage( + version="5.0.0" # Optional (default is the latest version of Node) + ) + + # Downloads & installs Node to ~/.hitchpkg if not already installed by previous test + node_package.build() + + +To use, define the service after initializing the :doc:`/glossary/service_bundle` but before starting it: + +.. note:: + + See also: :doc:`/api/generic_service_api` + +.. code-block:: python + + # Check if a package (e.g. less) is already installed: + import hitchtest + if not path.exists(path.join( + hitchtest.utils.get_hitch_directory(), + "node_modules", "less", "bin", "lessc" + )): + # Install the package is not found: + chdir(hitchtest.utils.get_hitch_directory()) + check_call([node_package.npm, "install", "less"])
59
add doc for basic usage of hitchnode
0
.rst
rst
agpl-3.0
hitchtest/hitch
1692
<NME> README.md <BEF> shiro-redis ============= ## Introduction shiro only provide the support of ehcache and concurrentHashMap. Here is an implement of redis cache can be used by shiro. Hope it will help you! ## Documentation Official documentation [is located here](http://alexxiyang.github.io/shiro-redis/). ## If you haven't created your own `SessionManager` or `SessionsSecurityManager` You are good to go. ## If you have created your own `SessionManager` or `SessionsSecurityManager` <MSG> Merge remote-tracking branch 'origin/master' <DFF> @@ -364,7 +364,7 @@ You will have to inject them by yourself. for more deail, see below ## If you haven't created your own `SessionManager` or `SessionsSecurityManager` -You are good to go. +You are all set. Enjoy it! ## If you have created your own `SessionManager` or `SessionsSecurityManager`
1
Merge remote-tracking branch 'origin/master'
1
.md
md
mit
alexxiyang/shiro-redis
1693
<NME> RedisCacheTest.java <BEF> package org.crazycake.shiro; import org.apache.shiro.subject.PrincipalCollection; import org.crazycake.shiro.exception.SerializationException; import org.crazycake.shiro.serializer.ObjectSerializer; import org.crazycake.shiro.serializer.StringSerializer; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.*; import static org.mockito.Mockito.*; public class RedisCacheTest { private IRedisManager redisManager; private StringSerializer keySerializer = new StringSerializer(); private ObjectSerializer valueSerializer = new ObjectSerializer(); @BeforeEach public void setUp() { redisManager = mock(IRedisManager.class); } private RedisCache mountRedisCache() { return new RedisCache(redisManager, new StringSerializer(), new ObjectSerializer(), "employee:", 1, RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME); } @Test public void testInitialize() { Assertions.assertThrows(IllegalArgumentException.class, () -> new RedisCache<String, String>(null, null, null, "abc:", 1, RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME)); Assertions.assertThrows(IllegalArgumentException.class, () -> new RedisCache<String, String>(new RedisManager(), null, null, "abc:", 1, RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME)); Assertions.assertThrows(IllegalArgumentException.class, () -> new RedisCache<String, String>(new RedisManager(), new StringSerializer(), null, "abc:", 1, RedisCacheManager.DEFAULT_PRINCIPAL_ID_FIELD_NAME)); } @Test public void testPut() throws SerializationException { RedisCache rc = mountRedisCache(); Object value = rc.put("foo", "bar"); assertThat(value, is("bar")); verify(redisManager).set(keySerializer.serialize("employee:foo"), valueSerializer.serialize("bar"), 1); PrincipalCollection principal = new EmployeePrincipal(3); rc.put(principal, "account information"); verify(redisManager).set(keySerializer.serialize("employee:3"), valueSerializer.serialize("account information"), 1); } } class Employee { private int id; public Employee(int id) { this.id = id; } public int getId() { return this.id; } } class EmployeePrincipal implements PrincipalCollection { private Employee primaryPrincipal; public EmployeePrincipal(int id) { this.primaryPrincipal = new Employee(id); } @Override public Employee getPrimaryPrincipal() { return this.primaryPrincipal; } @Override public <T> T oneByType(Class<T> aClass) { return null; } @Override public <T> Collection<T> byType(Class<T> aClass) { return null; } @Override public List asList() { return null; } @Override public Set asSet() { return null; } public void testSize() throws InterruptedException { doPutAuth(redisCache, user1); doPutAuth(redisCache, user2); Thread.sleep(200); assertEquals(redisCache.size(), 2); } public Set<String> getRealmNames() { return null; } @Override public boolean isEmpty() { return false; } @Override public Iterator iterator() { return null; } } <MSG> Release 3.2.1. Add shiro-redis-spring-boot-starter. <DFF> @@ -99,7 +99,7 @@ public class RedisCacheTest { public void testSize() throws InterruptedException { doPutAuth(redisCache, user1); doPutAuth(redisCache, user2); - Thread.sleep(200); + Thread.sleep(500); assertEquals(redisCache.size(), 2); }
1
Release 3.2.1. Add shiro-redis-spring-boot-starter.
1
.java
java
mit
alexxiyang/shiro-redis
1694
<NME> RedisSentinelManager.java <BEF> package org.crazycake.shiro; import org.crazycake.shiro.common.WorkAloneRedisManager; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis.Protocol; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class RedisSentinelManager extends WorkAloneRedisManager implements IRedisManager { private static final String DEFAULT_HOST = "127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381"; private String host = DEFAULT_HOST; private static final String DEFAULT_MASTER_NAME = "mymaster"; // timeout for jedis try to connect to redis server, not expire time! In milliseconds private int timeout = Protocol.DEFAULT_TIMEOUT; private String password; private int database = Protocol.DEFAULT_DATABASE; private String password; private int database = Protocol.DEFAULT_DATABASE; private volatile JedisSentinelPool jedisPool; @Override protected Jedis getJedis() { if (jedisPool == null) { init(); } return jedisPool.getResource(); } private void init() { if (jedisPool == null) { init(); } } public String getHost() { return host; } } } } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getDatabase() { return database; } public void setDatabase(int database) { this.database = database; } public String getMasterName() { return masterName; } public void setMasterName(String masterName) { this.masterName = masterName; } public int getSoTimeout() { return soTimeout; } public void setSoTimeout(int soTimeout) { this.soTimeout = soTimeout; } public JedisSentinelPool getJedisPool() { return jedisPool; } public void setJedisPool(JedisSentinelPool jedisPool) { this.jedisPool = jedisPool; } } <MSG> Merge branch 'master' of https://github.com/alexxiyang/shiro-redis # Conflicts: # src/main/java/org/crazycake/shiro/IRedisManager.java # src/main/java/org/crazycake/shiro/RedisCache.java # src/main/java/org/crazycake/shiro/RedisManager.java # src/main/java/org/crazycake/shiro/RedisSentinelManager.java <DFF> @@ -18,7 +18,7 @@ public class RedisSentinelManager extends BaseRedisManager implements IRedisMana // timeout for jedis try to connect to redis server, not expire time! In milliseconds private int timeout = Protocol.DEFAULT_TIMEOUT; - + private String password; private int database = Protocol.DEFAULT_DATABASE; @@ -42,7 +42,7 @@ public class RedisSentinelManager extends BaseRedisManager implements IRedisMana init(); } } - + public String getHost() { return host; }
2
Merge branch 'master' of https://github.com/alexxiyang/shiro-redis
2
.java
java
mit
alexxiyang/shiro-redis
1695
<NME> README.md <BEF> shiro-redis ============= ## Introduction shiro only provide the support of ehcache and concurrentHashMap. Here is an implement of redis cache can be used by shiro. Hope it will help you! ## Documentation Official documentation [is located here](http://alexxiyang.github.io/shiro-redis/). spring.xml: ```xml <!-- shiro redisManager --> <bean id="redisManager" class="org.crazycake.shiro.RedisManager"> <property name="host" value="127.0.0.1"/> <property name="port" value="6379"/> <property name="expire" value="1800"/> <!-- optional properties: <property name="timeout" value="10000"/> <property name="password" value="123456"/> <property name="database" value="1"/> --> </bean> <!-- redisSessionDAO --> <bean id="redisSessionDAO" class="org.crazycake.shiro.RedisSessionDAO"> <property name="redisManager" ref="redisManager" /> </bean> <!-- sessionManager --> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> <property name="sessionDAO" ref="redisSessionDAO" /> </bean> <!-- cacheManager --> <bean id="cacheManager" class="org.crazycake.shiro.RedisCacheManager"> <property name="redisManager" ref="redisManager" /> </bean> <!-- shiro securityManager --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <!-- sessionManager --> <property name="sessionManager" ref="sessionManager" /> <!-- cacheManager --> <property name="cacheManager" ref="cacheManager" /> </bean> <!-- shiro filter --> <bean id="ShiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager"/> <!-- other shiro configuration --> </bean> ``` ## Serializer Since redis only accept `byte[]`, there comes to a serializer problem. <MSG> Add shiro-redis-spring-tutorial project <DFF> @@ -89,47 +89,44 @@ Here is a [tutorial project](https://github.com/alexxiyang/shiro-redis-tutorial) spring.xml: ```xml +<!-- shiro-redis configuration [start] --> <!-- shiro redisManager --> <bean id="redisManager" class="org.crazycake.shiro.RedisManager"> - <property name="host" value="127.0.0.1"/> - <property name="port" value="6379"/> - <property name="expire" value="1800"/> - <!-- optional properties: - <property name="timeout" value="10000"/> - <property name="password" value="123456"/> - <property name="database" value="1"/> - --> + <property name="host" value="127.0.0.1"/> + <property name="port" value="6379"/> + <property name="expire" value="1800"/> + <!-- optional properties: + <property name="timeout" value="10000"/> + <property name="password" value="123456"/> + <property name="database" value="1"/> + --> </bean> -<!-- redisSessionDAO --> +<!-- Redis-based session configuration --> <bean id="redisSessionDAO" class="org.crazycake.shiro.RedisSessionDAO"> - <property name="redisManager" ref="redisManager" /> + <property name="redisManager" ref="redisManager" /> + <property name="keyPrefix" value="shiro:session:" /> </bean> - -<!-- sessionManager --> <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> - <property name="sessionDAO" ref="redisSessionDAO" /> + <property name="sessionDAO" ref="redisSessionDAO" /> </bean> -<!-- cacheManager --> +<!-- Redis-based cache configuration --> <bean id="cacheManager" class="org.crazycake.shiro.RedisCacheManager"> - <property name="redisManager" ref="redisManager" /> + <property name="redisManager" ref="redisManager" /> + <property name="keyPrefix" value="shiro:cache:" /> </bean> -<!-- shiro securityManager --> +<!-- securityManager --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> - <!-- sessionManager --> - <property name="sessionManager" ref="sessionManager" /> - <!-- cacheManager --> - <property name="cacheManager" ref="cacheManager" /> -</bean> - -<!-- shiro filter --> -<bean id="ShiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> - <property name="securityManager" ref="securityManager"/> - <!-- other shiro configuration --> + <property name="realm" ref="exampleRealm"/> + <property name="rememberMeManager.cipherKey" value="kPH+bIxk5D2deZiIxcaaaA==" /> + <property name="sessionManager" ref="sessionManager" /> + <property name="cacheManager" ref="cacheManager" /> </bean> +<!-- shiro-redis configuration [end] --> ``` +Here is a [tutorial project](https://github.com/alexxiyang/shiro-redis-spring-tutorial) for you to understand how to configure `shiro-redis` in spring configuration file. ## Serializer Since redis only accept `byte[]`, there comes to a serializer problem.
23
Add shiro-redis-spring-tutorial project
26
.md
md
mit
alexxiyang/shiro-redis
1696
<NME> README.md <BEF> shiro-redis ============= ## Introduction shiro only provide the support of ehcache and concurrentHashMap. Here is an implement of redis cache can be used by shiro. Hope it will help you! ## Documentation Official documentation [is located here](http://alexxiyang.github.io/shiro-redis/). ```properties #required cacheManager = org.yqr.shiro.RedisCacheManager #optional if you don't specify host the default value is 127.0.0.1 cacheManager.host=127.0.0.1 #optional , default value: 6379 <MSG> Update README.md <DFF> @@ -12,7 +12,7 @@ edit in shiro.ini ```properties #required -cacheManager = org.yqr.shiro.RedisCacheManager +cacheManager = org.crazycake.shiro.RedisCacheManager #optional if you don't specify host the default value is 127.0.0.1 cacheManager.host=127.0.0.1 #optional , default value: 6379
1
Update README.md
1
.md
md
mit
alexxiyang/shiro-redis
1697
<NME> RedisSentinelManager.java <BEF> package org.crazycake.shiro; import org.crazycake.shiro.common.WorkAloneRedisManager; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis.Protocol; import java.util.HashSet; import java.util.Set; public class RedisSentinelManager extends BaseRedisManager implements IRedisManager { private static final String DEFAULT_HOST = "127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381"; private String host = DEFAULT_HOST; private String host = DEFAULT_HOST; private static final String DEFAULT_MASTER_NAME = "mymaster"; private String masterName = DEFAULT_MASTER_NAME; // timeout for jedis try to connect to redis server, not expire time! In milliseconds private int timeout = Protocol.DEFAULT_TIMEOUT; // timeout for jedis try to read data from redis server private int soTimeout = Protocol.DEFAULT_TIMEOUT; private String password; private int database = Protocol.DEFAULT_DATABASE; private volatile JedisSentinelPool jedisPool; @Override protected Jedis getJedis() { if (jedisPool == null) { init(); } return jedisPool.getResource(); } private void init() { if (jedisPool == null) { synchronized (RedisSentinelManager.class) { if (jedisPool == null) { String[] sentinelHosts = host.split(",\\s*"); Set<String> sentinels = new HashSet<String>(); Collections.addAll(sentinels, sentinelHosts); jedisPool = new JedisSentinelPool(masterName, sentinels, getJedisPoolConfig(), timeout, soTimeout, password, database); } } } } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getDatabase() { return database; } public void setDatabase(int database) { this.database = database; } public String getMasterName() { return masterName; } public void setMasterName(String masterName) { this.masterName = masterName; } public int getSoTimeout() { return soTimeout; } public void setSoTimeout(int soTimeout) { this.soTimeout = soTimeout; } public JedisSentinelPool getJedisPool() { return jedisPool; } public void setJedisPool(JedisSentinelPool jedisPool) { this.jedisPool = jedisPool; } } <MSG> Change BaseRedisManager into WorkAloneRedisManager. Remove port from RedisManager. Remove AuthCachePrincipal <DFF> @@ -8,7 +8,7 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; -public class RedisSentinelManager extends BaseRedisManager implements IRedisManager { +public class RedisSentinelManager extends WorkAloneRedisManager implements IRedisManager { private static final String DEFAULT_HOST = "127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381"; private String host = DEFAULT_HOST;
1
Change BaseRedisManager into WorkAloneRedisManager. Remove port from RedisManager. Remove AuthCachePrincipal
1
.java
java
mit
alexxiyang/shiro-redis
1698
<NME> README.md <BEF> ADDFILE <MSG> Add docs folder <DFF> @@ -0,0 +1,435 @@ +shiro-redis +============= + +[![Build Status](https://travis-ci.org/alexxiyang/shiro-redis.svg?branch=master)](https://travis-ci.org/alexxiyang/shiro-redis) + + +shiro only provide the support of ehcache and concurrentHashMap. Here is an implement of redis cache can be used by shiro. Hope it will help you! + +# Download + +You can choose these 2 ways to include shiro-redis into your project +* use "git clone https://github.com/alexxiyang/shiro-redis.git" to clone project to your local workspace and build jar file by your self +* add maven dependency + +```xml +<dependency> + <groupId>org.crazycake</groupId> + <artifactId>shiro-redis</artifactId> + <version>3.2.2</version> +</dependency> +``` + +> **Note:**\ +> Do not use version < 3.1.0\ +> **注意**:\ +> 请不要使用3.1.0以下版本 + +# Before use +Here is the first thing you need to know. Shiro-redis needs an id field to identify your authorization object in Redis. So please make sure your principal class has a field which you can get unique id of this object. Please setting this id field name by `cacheManager.principalIdFieldName = <your id field name of principal object>` + +For example: + +If you create SimpleAuthenticationInfo like the following: +```java +@Override +protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { + UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token; + UserInfo userInfo = new UserInfo(); + userInfo.setUsername(usernamePasswordToken.getUsername()); + return new SimpleAuthenticationInfo(userInfo, "123456", getName()); +} +``` + +Then the userInfo object is your principal object. You need to make sure `UserInfo` has an unique field to identify it in Redis. Take userId as an example: +```java +public class UserInfo implements Serializable{ + + private Integer userId + + private String username; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Integer getUserId() { + return this.userId; + } +} +``` + +Put userId as the value of `cacheManager.principalIdFieldName`, like this: +```properties +cacheManager.principalIdFieldName = userId +``` + +If you're using Spring, the configuration should be +```xml +<property name="principalIdFieldName" value="userId" /> +``` + +Then shiro-redis will call `userInfo.getUserId()` to get the id for storing Redis object. + +# How to configure ? + +You can configure shiro-redis either in `shiro.ini` or in `spring-*.xml` + +## shiro.ini +Here is the configuration for shiro.ini. + +### Redis Standalone + +```properties +[main] +#==================================== +# shiro-redis configuration [start] +#==================================== + +#=================================== +# Redis Manager [start] +#=================================== + +# Create redisManager +redisManager = org.crazycake.shiro.RedisManager + +# Redis host. If you don't specify host the default value is 127.0.0.1:6379 +redisManager.host = 127.0.0.1:6379 + +#=================================== +# Redis Manager [end] +#=================================== + +#========================================= +# Redis session DAO [start] +#========================================= + +# Create redisSessionDAO +redisSessionDAO = org.crazycake.shiro.RedisSessionDAO + +# Use redisManager as cache manager +redisSessionDAO.redisManager = $redisManager + +sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager + +sessionManager.sessionDAO = $redisSessionDAO + +securityManager.sessionManager = $sessionManager + +#========================================= +# Redis session DAO [end] +#========================================= + +#========================================== +# Redis cache manager [start] +#========================================== + +# Create cacheManager +cacheManager = org.crazycake.shiro.RedisCacheManager + +# Principal id field name. The field which you can get unique id to identify this principal. +# For example, if you use UserInfo as Principal class, the id field maybe `id`, `userId`, `email`, etc. +# Remember to add getter to this id field. For example, `getId()`, `getUserId()`, `getEmail()`, etc. +# Default value is id, that means your principal object must has a method called `getId()` +# +cacheManager.principalIdFieldName = id + +# Use redisManager as cache manager +cacheManager.redisManager = $redisManager + +securityManager.cacheManager = $cacheManager + +#========================================== +# Redis cache manager [end] +#========================================== + +#================================= +# shiro-redis configuration [end] +#================================= +``` + +For complete configurable options list, check [Configurable Options](#configurable-options). + +Here is a [tutorial project](https://github.com/alexxiyang/shiro-redis-tutorial) for you to understand how to configure `shiro-redis` in `shiro.ini`. + +### Redis Sentinel +if you're using Redis Sentinel, please change the redisManager configuration into the following: +```properties +#=================================== +# Redis Manager [start] +#=================================== + +# Create redisManager +redisManager = org.crazycake.shiro.RedisSentinelManager + +# Sentinel host. If you don't specify host the default value is 127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381 +redisManager.host = 127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381 + +# Sentinel master name +redisManager.masterName = mymaster + +#=================================== +# Redis Manager [end] +#=================================== +``` + +For complete configurable options list, check [Configurable Options](#configurable-options). + +### Redis Cluster +If you're using redis cluster, here is an example of configuration : + +```properties +#=================================== +# Redis Manager [start] +#=================================== + +# Create redisManager +redisManager = org.crazycake.shiro.RedisClusterManager + +# Redis host and port list +redisManager.host = 192.168.21.3:7000,192.168.21.3:7001,192.168.21.3:7002,192.168.21.3:7003,192.168.21.3:7004,192.168.21.3:7005 + +#=================================== +# Redis Manager [end] +#=================================== +``` + +For complete configurable options list, check [Configurable Options](#configurable-options). + +## Spring + +### Redis Standalone +spring.xml: +```xml +<!-- shiro-redis configuration [start] --> + +<!-- Redis Manager [start] --> +<bean id="redisManager" class="org.crazycake.shiro.RedisManager"> + <property name="host" value="127.0.0.1:6379"/> +</bean> +<!-- Redis Manager [end] --> + +<!-- Redis session DAO [start] --> +<bean id="redisSessionDAO" class="org.crazycake.shiro.RedisSessionDAO"> + <property name="redisManager" ref="redisManager" /> +</bean> +<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> + <property name="sessionDAO" ref="redisSessionDAO" /> +</bean> +<!-- Redis session DAO [end] --> + +<!-- Redis cache manager [start] --> +<bean id="cacheManager" class="org.crazycake.shiro.RedisCacheManager"> + <property name="redisManager" ref="redisManager" /> +</bean> +<!-- Redis cache manager [end] --> + +<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> + <property name="sessionManager" ref="sessionManager" /> + <property name="cacheManager" ref="cacheManager" /> + + <!-- other configurations --> + <property name="realm" ref="exampleRealm"/> + <property name="rememberMeManager.cipherKey" value="kPH+bIxk5D2deZiIxcaaaA==" /> +</bean> + +<!-- shiro-redis configuration [end] --> +``` + +For complete configurable options list, check [Configurable Options](#configurable-options). + +Here is a [tutorial project](https://github.com/alexxiyang/shiro-redis-spring-tutorial) for you to understand how to configure `shiro-redis` in spring configuration file. + +### Redis Sentinel +If you use redis sentinel, here is an example of configuration : +```xml +<!-- shiro-redis configuration [start] --> +<!-- shiro redisManager --> +<bean id="redisManager" class="org.crazycake.shiro.RedisSentinelManager"> + <property name="host" value="127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381"/> + <property name="masterName" value="mymaster"/> +</bean> +``` + +For complete configurable options list, check [Configurable Options](#configurable-options). + +### Redis Cluster +If you use redis cluster, here is an example of configuration : +```xml +<!-- shiro-redis configuration [start] --> +<!-- shiro redisManager --> +<bean id="redisManager" class="org.crazycake.shiro.RedisClusterManager"> + <property name="host" value="192.168.21.3:7000,192.168.21.3:7001,192.168.21.3:7002,192.168.21.3:7003,192.168.21.3:7004,192.168.21.3:7005"/> +</bean> +``` + +For complete configurable options list, check [Configurable Options](#configurable-options). + +## Serializer +Since redis only accept `byte[]`, there comes to a serializer problem. +Shiro-redis is using StringSerializer as key serializer and ObjectSerializer as value serializer. +You can use your own custom serializer, as long as this custom serializer implemens `org.crazycake.shiro.serializer.RedisSerializer` + +For example, let's change the charset of keySerializer. +```properties +# If you want change charset of keySerializer or use your own custom serializer, you need to define serializer first +# +# cacheManagerKeySerializer = org.crazycake.shiro.serializer.StringSerializer + +# Supported encodings refer to https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html +# UTF-8, UTF-16, UTF-32, ISO-8859-1, GBK, Big5, etc +# +# cacheManagerKeySerializer.charset = UTF-8 + +# cacheManager.keySerializer = $cacheManagerKeySerializer +``` + +These 4 Serializers are replaceable: +- cacheManager.keySerializer +- cacheManager.valueSerializer +- redisSessionDAO.keySerializer +- redisSessionDAO.valueSerializer + +## Configurable Options + +### RedisManager + +| Title | Default | Description | +| :------------------| :------------------- | :---------------------------| +| host | `127.0.0.1:6379` | Redis host. If you don't specify host the default value is `127.0.0.1:6379`. If you run redis in sentinel mode or cluster mode, separate host names with comma, like `127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381` | +| masterName | `mymaster` | **Only used for sentinel mode**<br>The master node of Redis sentinel mode | +| timeout | `2000` | Redis connect timeout. Timeout for jedis try to connect to redis server(In milliseconds) | +| soTimeout | `2000` | **Only used for sentinel mode or cluster mode**<br>The timeout for jedis try to read data from redis server | +| maxAttempts | `3` | **Only used for cluster mode**<br>Max attempts to connect to server | +| password | | Redis password | +| database | `0` | Redis database. Default value is 0 | +| jedisPoolConfig | `new redis.clients.jedis.JedisPoolConfig()` | JedisPoolConfig. You can create your own JedisPoolConfig and set attributes as you wish<br>Most of time, you don't need to set jedisPoolConfig<br>Here is an example.<br>`jedisPoolConfig = redis.clients.jedis.JedisPoolConfig`<br>`jedisPoolConfig.testWhileIdle = false`<br>`redisManager.jedisPoolConfig = jedisPoolConfig` | +| count | `100` | Scan count. Shiro-redis use Scan to get keys, so you can define the number of elements returned at every iteration. | + +### RedisSessionDAO + +| Title | Default | Description | +| :------------------| :------------------- | :---------------------------| +| redisManager | | RedisManager which you just configured above (Required) | +| expire | `-2` | Redis cache key/value expire time. The expire time is in second.<br>Special values:<br>`-1`: no expire<br>`-2`: the same timeout with session<br>Default value: `-2`<br>**Note**: Make sure expire time is longer than session timeout. | +| keyPrefix | `shiro:session:` | Custom your redis key prefix for session management<br>**Note**: Remember to add colon at the end of prefix. | +| sessionInMemoryTimeout | `1000` | When we do signin, `doReadSession(sessionId)` will be called by shiro about 10 times. So shiro-redis save Session in ThreadLocal to remit this problem. sessionInMemoryTimeout is expiration of Session in ThreadLocal. <br>Most of time, you don't need to change it. | +| sessionInMemoryEnabled | `true` | Whether or not enable temporary save session in ThreadLocal | +| keySerializer | `org.crazycake.shiro.serializer.StringSerializer` | The key serializer of cache manager<br>You can change the implement of key serializer or the encoding of StringSerializer.<br>Supported encodings refer to [Supported Encodings](https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html). Such as `UTF-8`, `UTF-16`, `UTF-32`, `ISO-8859-1`, `GBK`, `Big5`, etc<br>For more detail, check [Serializer](#serializer) | +| valueSerializer | `org.crazycake.shiro.serializer.ObjectSerializer` | The value serializer of cache manager<br>You can change the implement of value serializer<br>For more detail, check [Serializer](#serializer) | + +### CacheManager + +| Title | Default | Description | +| :--------------------| :------------------- | :---------------------------| +| redisManager | | RedisManager which you just configured above (Required) | +| principalIdFieldName | `id` | Principal id field name. The field which you can get unique id to identify this principal.<br>For example, if you use UserInfo as Principal class, the id field maybe `id`, `userId`, `email`, etc.<br>Remember to add getter to this id field. For example, `getId()`, `getUserId(`), `getEmail()`, etc.<br>Default value is `id`, that means your principal object must has a method called `getId()` | +| expire | `1800` | Redis cache key/value expire time. <br>The expire time is in second. | +| keyPrefix | `shiro:cache:` | Custom your redis key prefix for cache management<br>**Note**: Remember to add colon at the end of prefix. | +| keySerializer | `org.crazycake.shiro.serializer.StringSerializer` | The key serializer of cache manager<br>You can change the implement of key serializer or the encoding of StringSerializer.<br>Supported encodings refer to [Supported Encodings](https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html). Such as `UTF-8`, `UTF-16`, `UTF-32`, `ISO-8859-1`, `GBK`, `Big5`, etc<br>For more detail, check [Serializer](#serializer) | +| valueSerializer | `org.crazycake.shiro.serializer.ObjectSerializer` | The value serializer of cache manager<br>You can change the implement of value serializer<br>For more detail, check [Serializer](#serializer) | + +# Spring boot starter + +Shiro-redis’s Spring-Boot integration is the easiest way to integrate Shiro-redis into a Spring-base application. + +> Note: `shiro-redis-spring-boot-starter` version `3.2.1` is based on `shiro-spring-boot-web-starter` version `1.4.0-RC2` + +First include the Shiro-redis Spring boot starter dependency in you application classpath + +```xml +<dependency> + <groupId>org.crazycake</groupId> + <artifactId>shiro-redis-spring-boot-starter</artifactId> + <version>3.2.1</version> +</dependency> +``` + +The next step depends on whether you've created your own `SessionManager` or `SessionsSecurityManager`. +Because `shiro-redis-spring-boot-starter` will create `RedisSessionDAO` and `RedisCacheManager` for you. Then inject them into `SessionManager` and `SessionsSecurityManager` automatically. + +But if you've created your own `SessionManager` or `SessionsSecurityManager` as below: +```java +@Bean +public SessionsSecurityManager securityManager(List<Realm> realms) { + DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(realms); + // other stuff + return securityManager; +} +``` +You will have to inject them by yourself. for more deail, see below + +## If you haven't created your own `SessionManager` or `SessionsSecurityManager` + +You are all set. Enjoy it! + +## If you have created your own `SessionManager` or `SessionsSecurityManager` + +Inject `redisSessionDAO` and `redisCacheManager` which created by `shiro-redis-spring-boot-starter` already +```java +@Autowired +RedisSessionDAO redisSessionDAO; + +@Autowired +RedisCacheManager redisCacheManager; +``` + +Inject them into `SessionManager` and `SessionsSecurityManager` + +```java +@Bean +public SessionManager sessionManager() { + DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); + + // inject redisSessionDAO + sessionManager.setSessionDAO(redisSessionDAO); + return sessionManager; +} + +@Bean +public SessionsSecurityManager securityManager(List<Realm> realms, SessionManager sessionManager) { + DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(realms); + + //inject sessionManager + securityManager.setSessionManager(sessionManager); + + // inject redisCacheManager + securityManager.setCacheManager(redisCacheManager); + return securityManager; +} +``` + +For full example, see [shiro-redis-spring-boot-tutorial](https://github.com/alexxiyang/shiro-redis-spring-boot-tutorial) + +### Configuration Properties + +| Title | Default | Description | +| :--------------------------------------------------| :------------------- | :---------------------------| +| shiro-redis.enabled | `true` | Enables shiro-redis’s Spring module | +| shiro-redis.redis-manager.deploy-mode | `standalone` | Redis deploy mode. Options: `standalone`, `sentinel`, 'cluster' | +| shiro-redis.redis-manager.host | `127.0.0.1:6379` | Redis host. If you don't specify host the default value is `127.0.0.1:6379`. If you run redis in sentinel mode or cluster mode, separate host names with comma, like `127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381` | +| shiro-redis.redis-manager.master-name | `mymaster` | **Only used for sentinel mode**<br>The master node of Redis sentinel mode | +| shiro-redis.redis-manager.timeout | `2000` | Redis connect timeout. Timeout for jedis try to connect to redis server(In milliseconds) | +| shiro-redis.redis-manager.so-timeout | `2000` | **Only used for sentinel mode or cluster mode**<br>The timeout for jedis try to read data from redis server | +| shiro-redis.redis-manager.max-attempts | `3` | **Only used for cluster mode**<br>Max attempts to connect to server | +| shiro-redis.redis-manager.password | | Redis password | +| shiro-redis.redis-manager.database | `0` | Redis database. Default value is 0 | +| shiro-redis.redis-manager.count | `100` | Scan count. Shiro-redis use Scan to get keys, so you can define the number of elements returned at every iteration. | +| shiro-redis.session-dao.expire | `-2` | Redis cache key/value expire time. The expire time is in second.<br>Special values:<br>`-1`: no expire<br>`-2`: the same timeout with session<br>Default value: `-2`<br>**Note**: Make sure expire time is longer than session timeout. | +| shiro-redis.session-dao.key-prefix | `shiro:session:` | Custom your redis key prefix for session management<br>**Note**: Remember to add colon at the end of prefix. | +| shiro-redis.session-dao.session-in-memory-timeout | `1000` | When we do signin, `doReadSession(sessionId)` will be called by shiro about 10 times. So shiro-redis save Session in ThreadLocal to remit this problem. sessionInMemoryTimeout is expiration of Session in ThreadLocal. <br>Most of time, you don't need to change it. | +| shiro-redis.session-dao.session-in-memory-enabled | `true` | Whether or not enable temporary save session in ThreadLocal | +| shiro-redis.cache-manager.principal-id-field-name | `id` | Principal id field name. The field which you can get unique id to identify this principal.<br>For example, if you use UserInfo as Principal class, the id field maybe `id`, `userId`, `email`, etc.<br>Remember to add getter to this id field. For example, `getId()`, `getUserId(`), `getEmail()`, etc.<br>Default value is `id`, that means your principal object must has a method called `getId()` | +| shiro-redis.cache-manager.expire | `1800` | Redis cache key/value expire time. <br>The expire time is in second. | +| shiro-redis.cache-manager.key-prefix | `shiro:cache:` | Custom your redis key prefix for cache management<br>**Note**: Remember to add colon at the end of prefix. | + + +# If you found any bugs + +Please send email to [email protected] + +可以用中文
435
Add docs folder
0
.md
md
mit
alexxiyang/shiro-redis
1699
<NME> RedisSessionDAOTest.java <BEF> package org.crazycake.shiro; import org.apache.shiro.session.InvalidSessionException; import org.apache.shiro.session.Session; import org.crazycake.shiro.exception.SerializationException; import org.crazycake.shiro.serializer.ObjectSerializer; import org.crazycake.shiro.serializer.StringSerializer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Set; public class RedisSessionDAOTest { private RedisManager redisManager; private RedisSessionDAO redisSessionDAO; private StringSerializer keySerializer; private String testKey; public class RedisSessionDAOTest { private IRedisManager redisManager; private StringSerializer keySerializer = new StringSerializer(); private ObjectSerializer valueSerializer = new ObjectSerializer(); @BeforeEach public void setUp() { redisManager = mock(IRedisManager.class); } private RedisSessionDAO mountRedisSessionDAO(Integer expire) { RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); if (expire != null) { redisSessionDAO.setExpire(expire); } redisSessionDAO.setKeyPrefix("student:"); redisSessionDAO.setRedisManager(redisManager); return redisSessionDAO; } @Test public void testUpdate() throws SerializationException { RedisSessionDAO sessionDAO = mountRedisSessionDAO(null); StudentSession session = new StudentSession(99, 2000); testValues.add(paulSession); billySession = new FakeSession(3, "billy"); testValues.add(billySession); redisManager = mock(RedisManager.class); when(redisManager.dbSize()).thenReturn(2L); when(redisManager.get(keySerializer.serialize(testPrefix + testKey))).thenReturn(valueSeralizer.serialize(testValue)); when(redisManager.keys(keySerializer.serialize(testPrefix + "*"))).thenReturn(testSet); StudentSession session = new StudentSession(98, 2000); sessionDAO.update(session); verify(redisManager).set(keySerializer.serialize("student:98"), valueSerializer.serialize(session), 3); } @Test public void testUpdateByNoExpire() throws SerializationException { RedisSessionDAO sessionDAO = mountRedisSessionDAO(-1); StudentSession session = new StudentSession(97, 2000); sessionDAO.update(session); verify(redisManager).set(keySerializer.serialize("student:97"), valueSerializer.serialize(session), -1); } @Test public void testDelete() throws SerializationException { RedisSessionDAO sessionDAO = mountRedisSessionDAO(null); StudentSession session = new StudentSession(96, 1000); sessionDAO.delete(session); verify(redisManager).del(keySerializer.serialize("student:96")); } @Test public void testGetActiveSessions() throws SerializationException { Set<byte[]> mockKeys = new HashSet<byte[]>(); mockKeys.add(keySerializer.serialize("student:1")); mockKeys.add(keySerializer.serialize("student:2")); when(redisManager.keys(keySerializer.serialize("student:*"))).thenReturn(mockKeys); StudentSession mockSession1 = new StudentSession(1, 2000); StudentSession mockSession2 = new StudentSession(2, 2000); when(redisManager.get(keySerializer.serialize("student:1"))).thenReturn(valueSerializer.serialize(mockSession1)); when(redisManager.get(keySerializer.serialize("student:2"))).thenReturn(valueSerializer.serialize(mockSession2)); RedisSessionDAO sessionDAO = mountRedisSessionDAO(null); assertThat(sessionDAO.getActiveSessions().size(), is(2)); } } class StudentSession implements Session, Serializable { private Integer id; private long timeout; public StudentSession(Integer id, long timeout) { this.id = id; this.timeout = timeout; } @Override public Serializable getId() { return id; } @Override public Date getStartTimestamp() { return null; } @Override public Date getLastAccessTime() { return null; } @Override public long getTimeout() throws InvalidSessionException { return timeout; } @Override public void setTimeout(long l) throws InvalidSessionException { } @Override public String getHost() { return null; } @Override public void touch() throws InvalidSessionException { } @Override public void stop() throws InvalidSessionException { } @Override public Collection<Object> getAttributeKeys() throws InvalidSessionException { return null; } @Override public Object getAttribute(Object o) throws InvalidSessionException { return null; } @Override public void setAttribute(Object o, Object o1) throws InvalidSessionException { } @Override public Object removeAttribute(Object o) throws InvalidSessionException { return null; } } <MSG> Merge branch 'master' of https://github.com/alexxiyang/shiro-redis # Conflicts: # src/main/java/org/crazycake/shiro/RedisManager.java # src/main/java/org/crazycake/shiro/RedisSentinelManager.java <DFF> @@ -16,7 +16,7 @@ import static org.mockito.Mockito.when; public class RedisSessionDAOTest { - private RedisManager redisManager; + private RedisSingletonManager redisManager; private RedisSessionDAO redisSessionDAO; private StringSerializer keySerializer; private String testKey; @@ -47,7 +47,7 @@ public class RedisSessionDAOTest { testValues.add(paulSession); billySession = new FakeSession(3, "billy"); testValues.add(billySession); - redisManager = mock(RedisManager.class); + redisManager = mock(RedisSingletonManager.class); when(redisManager.dbSize()).thenReturn(2L); when(redisManager.get(keySerializer.serialize(testPrefix + testKey))).thenReturn(valueSeralizer.serialize(testValue)); when(redisManager.keys(keySerializer.serialize(testPrefix + "*"))).thenReturn(testSet);
2
Merge branch 'master' of https://github.com/alexxiyang/shiro-redis
2
.java
java
mit
alexxiyang/shiro-redis