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
|
---|---|---|---|---|---|---|---|---|
1400 | <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 URLParseTestCase(unittest.TestCase):
URI = 'pgsql://foo:bar@baz:5444/qux'
def test_urlparse_hostname(self):
"""hostname should match expectation"""
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 = ('pgsql://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_urlparse_password(self):
"""password should match expectation"""
self.assertEqual(utils.urlparse(self.URI).password, 'bar')
class URIToKWargsTestCase(unittest.TestCase):
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"""
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> Change the pgsql scheme to postgresql
Match the standard for the URI scheme in PostgreSQL.
<DFF> @@ -22,7 +22,7 @@ class GetCurrentUserTests(unittest.TestCase):
class URLParseTestCase(unittest.TestCase):
- URI = 'pgsql://foo:bar@baz:5444/qux'
+ URI = 'postgresql://foo:bar@baz:5444/qux'
def test_urlparse_hostname(self):
"""hostname should match expectation"""
@@ -47,8 +47,8 @@ class URLParseTestCase(unittest.TestCase):
class URIToKWargsTestCase(unittest.TestCase):
- URI = ('pgsql://foo:bar@baz:5444/qux?options=foo&options=bar&keepalives=1&'
- 'invalid=true')
+ 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"""
| 3 | Change the pgsql scheme to postgresql | 3 | .py | py | bsd-3-clause | gmr/queries |
1401 | <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
: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.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
def __str__(self):
return 'Pool %s is at its maximum capacity' % self.pid
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> Whitespace cleanup
<DFF> @@ -596,4 +596,3 @@ class PoolFullError(Exception):
def __str__(self):
return 'Pool %s is at its maximum capacity' % self.pid
-
| 0 | Whitespace cleanup | 1 | .py | py | bsd-3-clause | gmr/queries |
1402 | <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
: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.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
def __str__(self):
return 'Pool %s is at its maximum capacity' % self.pid
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> Whitespace cleanup
<DFF> @@ -596,4 +596,3 @@ class PoolFullError(Exception):
def __str__(self):
return 'Pool %s is at its maximum capacity' % self.pid
-
| 0 | Whitespace cleanup | 1 | .py | py | bsd-3-clause | gmr/queries |
1403 | <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'],
'Topic :: Software Development :: Libraries']
setup(name='queries',
version='1.9.0',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
'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> Handle exceptions raised when creating async connection
<DFF> @@ -29,7 +29,7 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Topic :: Software Development :: Libraries']
setup(name='queries',
- version='1.9.0',
+ version='1.9.1',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
| 1 | Handle exceptions raised when creating async connection | 1 | .py | py | bsd-3-clause | gmr/queries |
1404 | <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'],
'Topic :: Software Development :: Libraries']
setup(name='queries',
version='1.9.0',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
'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> Handle exceptions raised when creating async connection
<DFF> @@ -29,7 +29,7 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Topic :: Software Development :: Libraries']
setup(name='queries',
- version='1.9.0',
+ version='1.9.1',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
| 1 | Handle exceptions raised when creating async connection | 1 | .py | py | bsd-3-clause | gmr/queries |
1405 | <NME> pool_manager_tests.py
<BEF> ADDFILE
<MSG> start the pool manager tests
<DFF> @@ -0,0 +1,37 @@
+"""
+Tests for Manager class in the pool module
+
+"""
+import mock
+try:
+ import unittest2 as unittest
+except ImportError:
+ import unittest
+import uuid
+
+from queries import pool
+
+
+class ManagerTests(unittest.TestCase):
+
+
+ def setUp(self):
+ self.manager = pool.PoolManager.instance()
+
+ def test_singleton_behavior(self):
+ self.assertEqual(pool.PoolManager.instance(), self.manager)
+
+ def test_has_pool_false(self):
+ self.assertNotIn(mock.Mock(), self.manager)
+
+ def test_has_pool_true(self):
+ pid = str(uuid.uuid4())
+ self.manager.create(pid)
+ self.assertIn(pid, self.manager)
+
+ def test_adding_to_pool(self):
+ pid = str(uuid.uuid4())
+ self.manager.create(pid)
+ psycopg2_conn = mock.Mock()
+ self.manager.add(pid, psycopg2_conn)
+ self.assertIn(psycopg2_conn, self.manager._pools[pid])
| 37 | start the pool manager tests | 0 | .py | py | bsd-3-clause | gmr/queries |
1406 | <NME> pool_manager_tests.py
<BEF> ADDFILE
<MSG> start the pool manager tests
<DFF> @@ -0,0 +1,37 @@
+"""
+Tests for Manager class in the pool module
+
+"""
+import mock
+try:
+ import unittest2 as unittest
+except ImportError:
+ import unittest
+import uuid
+
+from queries import pool
+
+
+class ManagerTests(unittest.TestCase):
+
+
+ def setUp(self):
+ self.manager = pool.PoolManager.instance()
+
+ def test_singleton_behavior(self):
+ self.assertEqual(pool.PoolManager.instance(), self.manager)
+
+ def test_has_pool_false(self):
+ self.assertNotIn(mock.Mock(), self.manager)
+
+ def test_has_pool_true(self):
+ pid = str(uuid.uuid4())
+ self.manager.create(pid)
+ self.assertIn(pid, self.manager)
+
+ def test_adding_to_pool(self):
+ pid = str(uuid.uuid4())
+ self.manager.create(pid)
+ psycopg2_conn = mock.Mock()
+ self.manager.add(pid, psycopg2_conn)
+ self.assertIn(psycopg2_conn, self.manager._pools[pid])
| 37 | start the pool manager tests | 0 | .py | py | bsd-3-clause | gmr/queries |
1407 | <NME> pool_manager_tests.py
<BEF> """
Tests for Manager class in the pool module
"""
import unittest
import uuid
import mock
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 ManagerTests(unittest.TestCase):
def setUp(self):
self.manager = pool.PoolManager.instance()
def tearDown(self):
self.manager.shutdown()
def test_singleton_behavior(self):
self.assertEqual(pool.PoolManager.instance(), self.manager)
def test_has_pool_false(self):
self.assertNotIn(mock.Mock(), self.manager)
def test_has_pool_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertIn(pid, self.manager)
def test_adding_to_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock_connection()
self.manager.add(pid, psycopg2_conn)
self.assertIn(psycopg2_conn, self.manager._pools[pid])
def test_adding_to_pool_ensures_pool_exists(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock.Mock()
self.assertRaises(KeyError, self.manager.add, pid, psycopg2_conn)
def test_ensures_pool_exists_raises_key_error(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager._ensure_pool_exists, pid)
def test_clean_ensures_pool_exists_catches_key_error(self):
pid = str(uuid.uuid4())
self.assertIsNone(self.manager.clean(pid))
def test_clean_invokes_pool_clean(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.manager._pools[pid].clean = clean = mock.Mock()
self.manager.clean(pid)
clean.assert_called_once_with()
def test_clean_removes_pool(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.manager.clean(pid)
def test_create_prevents_duplicate_pool_id(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager.create(pid, 10, 10, Pool)
self.assertRaises(KeyError, self.manager.create, pid, 10, 10, Pool)
def test_create_created_default_pool_type(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertIsInstance(self.manager._pools[pid], pool.Pool)
def test_create_created_passed_in_pool_type(self):
pid = str(uuid.uuid4())
class FooPool(pool.Pool):
bar = True
self.manager.create(pid, 10, 10, FooPool)
self.assertIsInstance(self.manager._pools[pid], FooPool)
def test_create_passes_in_idle_ttl(self):
pid = str(uuid.uuid4())
def test_create_passes_in_idle_ttl(self):
pid = str(uuid.uuid4())
self.manager.create(pid, 12)
self.assertEqual(self.manager._pools[pid].idle_ttl, 12)
def test_create_passes_in_max_size(self):
pid = str(uuid.uuid4())
self.manager.create(pid, 10, 16)
self.assertEqual(self.manager._pools[pid].max_size, 16)
def test_get_ensures_pool_exists(self):
pid = str(uuid.uuid4())
session = mock.Mock()
self.assertRaises(KeyError, self.manager.get, pid, session)
def test_get_invokes_pool_get(self):
pid = str(uuid.uuid4())
session = mock.Mock()
self.manager.create(pid)
self.manager._pools[pid].get = get = mock.Mock()
self.manager.get(pid, session)
get.assert_called_once_with(session)
def test_free_ensures_pool_exists(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock_connection()
self.assertRaises(KeyError, self.manager.free, pid, psycopg2_conn)
def test_free_invokes_pool_free(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock_connection()
self.manager.create(pid)
self.manager._pools[pid].free = free = mock.Mock()
self.manager.free(pid, psycopg2_conn)
free.assert_called_once_with(psycopg2_conn)
def test_has_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.has_connection, pid, None)
def test_has_idle_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.has_idle_connection, pid)
def test_has_connection_returns_false(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertFalse(self.manager.has_connection(pid, mock.Mock()))
def test_has_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock_connection()
self.manager.add(pid, psycopg2_conn)
self.assertTrue(self.manager.has_connection(pid, psycopg2_conn))
self.manager.remove(pid)
def test_has_idle_connection_returns_false(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.idle_connections',
new_callable=mock.PropertyMock) as idle_connections:
idle_connections.return_value = 0
self.assertFalse(self.manager.has_idle_connection(pid))
def test_has_idle_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.idle_connections',
new_callable=mock.PropertyMock) as idle_connections:
idle_connections.return_value = 5
self.assertTrue(self.manager.has_idle_connection(pid))
def test_is_full_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.is_full, pid)
def test_is_full_invokes_pool_is_full(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.is_full',
new_callable=mock.PropertyMock) as is_full:
self.manager.is_full(pid)
is_full.assert_called_once_with()
def test_lock_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.lock, pid, None, None)
def test_lock_invokes_pool_lock(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].lock = lock = mock.Mock()
psycopg2_conn = mock.Mock()
session = mock.Mock()
self.manager.lock(pid, psycopg2_conn, session)
lock.assert_called_once_with(psycopg2_conn, session)
def test_remove_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.remove, pid)
def test_remove_invokes_pool_close(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].close = method = mock.Mock()
self.manager.remove(pid)
method.assert_called_once_with()
def test_remove_deletes_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].close = mock.Mock()
self.manager.remove(pid)
self.assertNotIn(pid, self.manager._pools)
def test_remove_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.remove_connection, pid, None)
def test_remove_connection_invokes_pool_remove(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].remove = remove = mock.Mock()
psycopg2_conn = mock.Mock()
self.manager.remove_connection(pid, psycopg2_conn)
remove.assert_called_once_with(psycopg2_conn)
def test_size_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.size, pid)
def test_size_returns_pool_length(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertEqual(self.manager.size(pid), len(self.manager._pools[pid]))
def test_set_idle_ttl_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.set_idle_ttl, pid, None)
def test_set_idle_ttl_invokes_pool_set_idle_ttl(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].set_idle_ttl = set_idle_ttl = mock.Mock()
self.manager.set_idle_ttl(pid, 256)
set_idle_ttl.assert_called_once_with(256)
def test_set_max_size_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.set_idle_ttl, pid, None)
def test_set_max_size_invokes_pool_set_max_size(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].set_max_size = set_max_size = mock.Mock()
self.manager.set_max_size(pid, 128)
set_max_size.assert_called_once_with(128)
def test_shutdown_closes_all(self):
pid1, pid2 = str(uuid.uuid4()), str(uuid.uuid4())
self.manager.create(pid1)
self.manager._pools[pid1].shutdown = method1 = mock.Mock()
self.manager.create(pid2)
self.manager._pools[pid2].shutdown = method2 = mock.Mock()
self.manager.shutdown()
method1.assert_called_once_with()
method2.assert_called_once_with()
<MSG> Remove future-proofing with pool_type
The idea behind the pool type was to allow for different pooling behaviors. Since it's been over a year and I've not created any others, let's remove this. It's easy enough to add back in should it be needed.
<DFF> @@ -73,22 +73,8 @@ class ManagerTests(unittest.TestCase):
def test_create_prevents_duplicate_pool_id(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
- self.manager.create(pid, 10, 10, Pool)
- self.assertRaises(KeyError, self.manager.create, pid, 10, 10, Pool)
-
- def test_create_created_default_pool_type(self):
- pid = str(uuid.uuid4())
- self.manager.create(pid)
- self.assertIsInstance(self.manager._pools[pid], pool.Pool)
-
- def test_create_created_passed_in_pool_type(self):
- pid = str(uuid.uuid4())
-
- class FooPool(pool.Pool):
- bar = True
-
- self.manager.create(pid, 10, 10, FooPool)
- self.assertIsInstance(self.manager._pools[pid], FooPool)
+ self.manager.create(pid, 10, 10)
+ self.assertRaises(KeyError, self.manager.create, pid, 10, 10)
def test_create_passes_in_idle_ttl(self):
pid = str(uuid.uuid4())
| 2 | Remove future-proofing with pool_type | 16 | .py | py | bsd-3-clause | gmr/queries |
1408 | <NME> pool_manager_tests.py
<BEF> """
Tests for Manager class in the pool module
"""
import unittest
import uuid
import mock
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 ManagerTests(unittest.TestCase):
def setUp(self):
self.manager = pool.PoolManager.instance()
def tearDown(self):
self.manager.shutdown()
def test_singleton_behavior(self):
self.assertEqual(pool.PoolManager.instance(), self.manager)
def test_has_pool_false(self):
self.assertNotIn(mock.Mock(), self.manager)
def test_has_pool_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertIn(pid, self.manager)
def test_adding_to_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock_connection()
self.manager.add(pid, psycopg2_conn)
self.assertIn(psycopg2_conn, self.manager._pools[pid])
def test_adding_to_pool_ensures_pool_exists(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock.Mock()
self.assertRaises(KeyError, self.manager.add, pid, psycopg2_conn)
def test_ensures_pool_exists_raises_key_error(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager._ensure_pool_exists, pid)
def test_clean_ensures_pool_exists_catches_key_error(self):
pid = str(uuid.uuid4())
self.assertIsNone(self.manager.clean(pid))
def test_clean_invokes_pool_clean(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.manager._pools[pid].clean = clean = mock.Mock()
self.manager.clean(pid)
clean.assert_called_once_with()
def test_clean_removes_pool(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager._pools[pid] = Pool()
self.manager.clean(pid)
def test_create_prevents_duplicate_pool_id(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
self.manager.create(pid, 10, 10, Pool)
self.assertRaises(KeyError, self.manager.create, pid, 10, 10, Pool)
def test_create_created_default_pool_type(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertIsInstance(self.manager._pools[pid], pool.Pool)
def test_create_created_passed_in_pool_type(self):
pid = str(uuid.uuid4())
class FooPool(pool.Pool):
bar = True
self.manager.create(pid, 10, 10, FooPool)
self.assertIsInstance(self.manager._pools[pid], FooPool)
def test_create_passes_in_idle_ttl(self):
pid = str(uuid.uuid4())
def test_create_passes_in_idle_ttl(self):
pid = str(uuid.uuid4())
self.manager.create(pid, 12)
self.assertEqual(self.manager._pools[pid].idle_ttl, 12)
def test_create_passes_in_max_size(self):
pid = str(uuid.uuid4())
self.manager.create(pid, 10, 16)
self.assertEqual(self.manager._pools[pid].max_size, 16)
def test_get_ensures_pool_exists(self):
pid = str(uuid.uuid4())
session = mock.Mock()
self.assertRaises(KeyError, self.manager.get, pid, session)
def test_get_invokes_pool_get(self):
pid = str(uuid.uuid4())
session = mock.Mock()
self.manager.create(pid)
self.manager._pools[pid].get = get = mock.Mock()
self.manager.get(pid, session)
get.assert_called_once_with(session)
def test_free_ensures_pool_exists(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock_connection()
self.assertRaises(KeyError, self.manager.free, pid, psycopg2_conn)
def test_free_invokes_pool_free(self):
pid = str(uuid.uuid4())
psycopg2_conn = mock_connection()
self.manager.create(pid)
self.manager._pools[pid].free = free = mock.Mock()
self.manager.free(pid, psycopg2_conn)
free.assert_called_once_with(psycopg2_conn)
def test_has_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.has_connection, pid, None)
def test_has_idle_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.has_idle_connection, pid)
def test_has_connection_returns_false(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertFalse(self.manager.has_connection(pid, mock.Mock()))
def test_has_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
psycopg2_conn = mock_connection()
self.manager.add(pid, psycopg2_conn)
self.assertTrue(self.manager.has_connection(pid, psycopg2_conn))
self.manager.remove(pid)
def test_has_idle_connection_returns_false(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.idle_connections',
new_callable=mock.PropertyMock) as idle_connections:
idle_connections.return_value = 0
self.assertFalse(self.manager.has_idle_connection(pid))
def test_has_idle_connection_returns_true(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.idle_connections',
new_callable=mock.PropertyMock) as idle_connections:
idle_connections.return_value = 5
self.assertTrue(self.manager.has_idle_connection(pid))
def test_is_full_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.is_full, pid)
def test_is_full_invokes_pool_is_full(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
with mock.patch('queries.pool.Pool.is_full',
new_callable=mock.PropertyMock) as is_full:
self.manager.is_full(pid)
is_full.assert_called_once_with()
def test_lock_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.lock, pid, None, None)
def test_lock_invokes_pool_lock(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].lock = lock = mock.Mock()
psycopg2_conn = mock.Mock()
session = mock.Mock()
self.manager.lock(pid, psycopg2_conn, session)
lock.assert_called_once_with(psycopg2_conn, session)
def test_remove_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.remove, pid)
def test_remove_invokes_pool_close(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].close = method = mock.Mock()
self.manager.remove(pid)
method.assert_called_once_with()
def test_remove_deletes_pool(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].close = mock.Mock()
self.manager.remove(pid)
self.assertNotIn(pid, self.manager._pools)
def test_remove_connection_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.remove_connection, pid, None)
def test_remove_connection_invokes_pool_remove(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].remove = remove = mock.Mock()
psycopg2_conn = mock.Mock()
self.manager.remove_connection(pid, psycopg2_conn)
remove.assert_called_once_with(psycopg2_conn)
def test_size_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.size, pid)
def test_size_returns_pool_length(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.assertEqual(self.manager.size(pid), len(self.manager._pools[pid]))
def test_set_idle_ttl_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.set_idle_ttl, pid, None)
def test_set_idle_ttl_invokes_pool_set_idle_ttl(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].set_idle_ttl = set_idle_ttl = mock.Mock()
self.manager.set_idle_ttl(pid, 256)
set_idle_ttl.assert_called_once_with(256)
def test_set_max_size_ensures_pool_exists(self):
pid = str(uuid.uuid4())
self.assertRaises(KeyError, self.manager.set_idle_ttl, pid, None)
def test_set_max_size_invokes_pool_set_max_size(self):
pid = str(uuid.uuid4())
self.manager.create(pid)
self.manager._pools[pid].set_max_size = set_max_size = mock.Mock()
self.manager.set_max_size(pid, 128)
set_max_size.assert_called_once_with(128)
def test_shutdown_closes_all(self):
pid1, pid2 = str(uuid.uuid4()), str(uuid.uuid4())
self.manager.create(pid1)
self.manager._pools[pid1].shutdown = method1 = mock.Mock()
self.manager.create(pid2)
self.manager._pools[pid2].shutdown = method2 = mock.Mock()
self.manager.shutdown()
method1.assert_called_once_with()
method2.assert_called_once_with()
<MSG> Remove future-proofing with pool_type
The idea behind the pool type was to allow for different pooling behaviors. Since it's been over a year and I've not created any others, let's remove this. It's easy enough to add back in should it be needed.
<DFF> @@ -73,22 +73,8 @@ class ManagerTests(unittest.TestCase):
def test_create_prevents_duplicate_pool_id(self):
pid = str(uuid.uuid4())
with mock.patch('queries.pool.Pool') as Pool:
- self.manager.create(pid, 10, 10, Pool)
- self.assertRaises(KeyError, self.manager.create, pid, 10, 10, Pool)
-
- def test_create_created_default_pool_type(self):
- pid = str(uuid.uuid4())
- self.manager.create(pid)
- self.assertIsInstance(self.manager._pools[pid], pool.Pool)
-
- def test_create_created_passed_in_pool_type(self):
- pid = str(uuid.uuid4())
-
- class FooPool(pool.Pool):
- bar = True
-
- self.manager.create(pid, 10, 10, FooPool)
- self.assertIsInstance(self.manager._pools[pid], FooPool)
+ self.manager.create(pid, 10, 10)
+ self.assertRaises(KeyError, self.manager.create, pid, 10, 10)
def test_create_passes_in_idle_ttl(self):
pid = str(uuid.uuid4())
| 2 | Remove future-proofing with pool_type | 16 | .py | py | bsd-3-clause | gmr/queries |
1409 | <NME> tornado_session.py
<BEF> """
Tornado Session Adapter
Use Queries asynchronously within the Tornado framework.
"""
import logging
"""
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__)
class TornadoSession(session.Session):
"""Session class for Tornado asynchronous applications. Uses
``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.
.. code:: python
class ExampleHandler(web.RequestHandler):
def initialize(self):
self.session = queries.TornadoSession()
@gen.coroutine
def get(self):
data = yield self.session.query('SELECT * FROM names')
self.finish({'data': data})
.. Note:: Unlike `queries.Session.query` and `queries.Session.callproc`,
the `TornadoSession.query` and `TornadoSession.callproc` methods are not
iterators and return the full result set
using `psycopg2.cursor.fetchall()`.
:param str uri: PostgreSQL connection URI
:param psycopg2.cursor: The cursor type to use
.. code:: python
results = yield session.query('SELECT * FROM foo')
for row in results
print row
results.free()
**Accessing an individual row by index**
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.cursor: The cursor type to use
:param bool use_pool: Use the connection pool
:param int max_pool_size: Max number of connections for a single URI
.. 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'
as a list. If no results are returned, the method will return None
instead.
.. code:: python
data = yield session.callproc('char', [65])
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,
"""Listen for notifications from PostgreSQL on the specified channel,
passing in a callback to receive the notifications.
..code:: python
class ListenHandler(web.RequestHandler):
def initialize(self):
self.channel = 'example'
self.session = queries.TornadoSession()
@gen.coroutine
def get(self, *args, **kwargs):
yield self.session.listen(self.channel, self.on_notification)
self.finish()
def on_connection_close(self):
if self.channel:
self.session.unlisten(self.channel)
self.channel = None
@gen.coroutine
def on_notification(self, channel, pid, payload):
self.write('Payload: %s\n' % payload)
yield gen.Task(self.flush)
See the documentation at https://queries.readthedocs.org for a more
complete example.
:param str channel: The channel to stop listening on
:param method callback: The method to call on each notification
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.
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results as list.
.. code:: python
data = yield session.query('SELECT * FROM foo WHERE bar=%(bar)s',
: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
def unlisten(self, channel):
"""Cancel a listening on a channel.
..code:: python
yield self.session.unlisten('channel-name')
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:
"""Connect to PostgreSQL and setup a few variables and data structures
to reduce code in the coroutine methods.
:rtype: tuple(psycopg2._psycopg.connection, int, int)
"""
connection = super(TornadoSession, self)._connect()
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,
"""Close the cursor, remove any references to the fd in internal state
and remove the fd from the ioloop.
:param psycopg2.cursor cursor: The cursor to close
:param int fd: The connection file descriptor
"""
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)
def _get_cursor(self, connection):
"""Return a cursor for the given connection.
:param psycopg2._psycopg.connection connection: The connection to use
:rtype: psycopg2.extensions.cursor
"""
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)
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.connection
"""
kwargs['async'] = True
# 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> Documentation updates
<DFF> @@ -3,6 +3,20 @@ Tornado Session Adapter
Use Queries asynchronously within the Tornado framework.
+Example Use:
+
+.. code:: python
+
+ class ExampleHandler(web.RequestHandler):
+
+ def initialize(self):
+ self.session = queries.TornadoSession()
+
+ @gen.coroutine
+ def get(self):
+ data = yield self.session.query('SELECT * FROM names')
+ self.finish({'data': data})
+
"""
import logging
@@ -22,28 +36,18 @@ LOGGER = logging.getLogger(__name__)
class TornadoSession(session.Session):
"""Session class for Tornado asynchronous applications. Uses
- ``tornado.gen.coroutine`` to wrap API methods for use in Tornado.
+ :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.
-
- .. code:: python
-
- class ExampleHandler(web.RequestHandler):
+ a higher ``max_pool_size`` to allow for greater connection concurrency.
- def initialize(self):
- self.session = queries.TornadoSession()
-
- @gen.coroutine
- def get(self):
- data = yield self.session.query('SELECT * FROM names')
- self.finish({'data': data})
-
- .. Note:: Unlike `queries.Session.query` and `queries.Session.callproc`,
- the `TornadoSession.query` and `TornadoSession.callproc` methods are not
- iterators and return the full result set
- using `psycopg2.cursor.fetchall()`.
+ .. Note:: Unlike :py:meth:`Session.query <queries.Session.query>` and
+ :py:meth:`Session.callproc <queries.Session.callproc>`, the
+ :py:meth:`TornadoSession.query <queries.TornadoSession.query>` and
+ :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>`
+ methods are not iterators and will return the full result set using
+ :py:meth:`cursor.fetchall`.
:param str uri: PostgreSQL connection URI
:param psycopg2.cursor: The cursor type to use
@@ -60,7 +64,7 @@ class TornadoSession(session.Session):
set the isolation level.
:param str uri: PostgreSQL connection URI
- :param psycopg2.cursor: The cursor type to use
+ :param psycopg2.extensions.cursor: The cursor type to use
:param bool use_pool: Use the connection pool
:param int max_pool_size: Max number of connections for a single URI
@@ -82,6 +86,8 @@ class TornadoSession(session.Session):
as a list. If no results are returned, the method will return None
instead.
+ Example:
+
.. code:: python
data = yield session.callproc('char', [65])
@@ -135,31 +141,31 @@ class TornadoSession(session.Session):
"""Listen for notifications from PostgreSQL on the specified channel,
passing in a callback to receive the notifications.
- ..code:: python
+ Example:
- class ListenHandler(web.RequestHandler):
+ .. code:: python
- def initialize(self):
- self.channel = 'example'
- self.session = queries.TornadoSession()
+ class ListenHandler(web.RequestHandler):
- @gen.coroutine
- def get(self, *args, **kwargs):
- yield self.session.listen(self.channel, self.on_notification)
- self.finish()
+ def initialize(self):
+ self.channel = 'example'
+ self.session = queries.TornadoSession()
- def on_connection_close(self):
- if self.channel:
- self.session.unlisten(self.channel)
- self.channel = None
+ @gen.coroutine
+ def get(self, *args, **kwargs):
+ yield self.session.listen(self.channel,
+ self.on_notification)
+ self.finish()
- @gen.coroutine
- def on_notification(self, channel, pid, payload):
- self.write('Payload: %s\n' % payload)
- yield gen.Task(self.flush)
+ def on_connection_close(self):
+ if self.channel:
+ self.session.unlisten(self.channel)
+ self.channel = None
- See the documentation at https://queries.readthedocs.org for a more
- complete example.
+ @gen.coroutine
+ def on_notification(self, channel, pid, payload):
+ self.write('Payload: %s\\n' % payload)
+ yield gen.Task(self.flush)
:param str channel: The channel to stop listening on
:param method callback: The method to call on each notification
@@ -210,6 +216,8 @@ class TornadoSession(session.Session):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results as list.
+ Example:
+
.. code:: python
data = yield session.query('SELECT * FROM foo WHERE bar=%(bar)s',
@@ -263,7 +271,9 @@ class TornadoSession(session.Session):
def unlisten(self, channel):
"""Cancel a listening on a channel.
- ..code:: python
+ Example:
+
+ .. code:: python
yield self.session.unlisten('channel-name')
@@ -292,7 +302,7 @@ class TornadoSession(session.Session):
"""Connect to PostgreSQL and setup a few variables and data structures
to reduce code in the coroutine methods.
- :rtype: tuple(psycopg2._psycopg.connection, int, int)
+ :return tuple: psycopg2.extensions.connection, int, int
"""
connection = super(TornadoSession, self)._connect()
@@ -307,7 +317,7 @@ class TornadoSession(session.Session):
"""Close the cursor, remove any references to the fd in internal state
and remove the fd from the ioloop.
- :param psycopg2.cursor cursor: The cursor to close
+ :param psycopg2.extensions.cursor cursor: The cursor to close
:param int fd: The connection file descriptor
"""
@@ -323,7 +333,7 @@ class TornadoSession(session.Session):
def _get_cursor(self, connection):
"""Return a cursor for the given connection.
- :param psycopg2._psycopg.connection connection: The connection to use
+ :param psycopg2.extensions.connection connection: The connection to use
:rtype: psycopg2.extensions.cursor
"""
@@ -370,7 +380,7 @@ class TornadoSession(session.Session):
use in async session adapters.
:param dict kwargs: Keyword connection args
- :rtype: psycopg2.connection
+ :rtype: psycopg2.extensions.connection
"""
kwargs['async'] = True
| 53 | Documentation updates | 43 | .py | py | bsd-3-clause | gmr/queries |
1410 | <NME> tornado_session.py
<BEF> """
Tornado Session Adapter
Use Queries asynchronously within the Tornado framework.
"""
import logging
"""
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__)
class TornadoSession(session.Session):
"""Session class for Tornado asynchronous applications. Uses
``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.
.. code:: python
class ExampleHandler(web.RequestHandler):
def initialize(self):
self.session = queries.TornadoSession()
@gen.coroutine
def get(self):
data = yield self.session.query('SELECT * FROM names')
self.finish({'data': data})
.. Note:: Unlike `queries.Session.query` and `queries.Session.callproc`,
the `TornadoSession.query` and `TornadoSession.callproc` methods are not
iterators and return the full result set
using `psycopg2.cursor.fetchall()`.
:param str uri: PostgreSQL connection URI
:param psycopg2.cursor: The cursor type to use
.. code:: python
results = yield session.query('SELECT * FROM foo')
for row in results
print row
results.free()
**Accessing an individual row by index**
set the isolation level.
:param str uri: PostgreSQL connection URI
:param psycopg2.cursor: The cursor type to use
:param bool use_pool: Use the connection pool
:param int max_pool_size: Max number of connections for a single URI
.. 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'
as a list. If no results are returned, the method will return None
instead.
.. code:: python
data = yield session.callproc('char', [65])
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,
"""Listen for notifications from PostgreSQL on the specified channel,
passing in a callback to receive the notifications.
..code:: python
class ListenHandler(web.RequestHandler):
def initialize(self):
self.channel = 'example'
self.session = queries.TornadoSession()
@gen.coroutine
def get(self, *args, **kwargs):
yield self.session.listen(self.channel, self.on_notification)
self.finish()
def on_connection_close(self):
if self.channel:
self.session.unlisten(self.channel)
self.channel = None
@gen.coroutine
def on_notification(self, channel, pid, payload):
self.write('Payload: %s\n' % payload)
yield gen.Task(self.flush)
See the documentation at https://queries.readthedocs.org for a more
complete example.
:param str channel: The channel to stop listening on
:param method callback: The method to call on each notification
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.
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results as list.
.. code:: python
data = yield session.query('SELECT * FROM foo WHERE bar=%(bar)s',
: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
def unlisten(self, channel):
"""Cancel a listening on a channel.
..code:: python
yield self.session.unlisten('channel-name')
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:
"""Connect to PostgreSQL and setup a few variables and data structures
to reduce code in the coroutine methods.
:rtype: tuple(psycopg2._psycopg.connection, int, int)
"""
connection = super(TornadoSession, self)._connect()
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,
"""Close the cursor, remove any references to the fd in internal state
and remove the fd from the ioloop.
:param psycopg2.cursor cursor: The cursor to close
:param int fd: The connection file descriptor
"""
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)
def _get_cursor(self, connection):
"""Return a cursor for the given connection.
:param psycopg2._psycopg.connection connection: The connection to use
:rtype: psycopg2.extensions.cursor
"""
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)
use in async session adapters.
:param dict kwargs: Keyword connection args
:rtype: psycopg2.connection
"""
kwargs['async'] = True
# 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> Documentation updates
<DFF> @@ -3,6 +3,20 @@ Tornado Session Adapter
Use Queries asynchronously within the Tornado framework.
+Example Use:
+
+.. code:: python
+
+ class ExampleHandler(web.RequestHandler):
+
+ def initialize(self):
+ self.session = queries.TornadoSession()
+
+ @gen.coroutine
+ def get(self):
+ data = yield self.session.query('SELECT * FROM names')
+ self.finish({'data': data})
+
"""
import logging
@@ -22,28 +36,18 @@ LOGGER = logging.getLogger(__name__)
class TornadoSession(session.Session):
"""Session class for Tornado asynchronous applications. Uses
- ``tornado.gen.coroutine`` to wrap API methods for use in Tornado.
+ :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.
-
- .. code:: python
-
- class ExampleHandler(web.RequestHandler):
+ a higher ``max_pool_size`` to allow for greater connection concurrency.
- def initialize(self):
- self.session = queries.TornadoSession()
-
- @gen.coroutine
- def get(self):
- data = yield self.session.query('SELECT * FROM names')
- self.finish({'data': data})
-
- .. Note:: Unlike `queries.Session.query` and `queries.Session.callproc`,
- the `TornadoSession.query` and `TornadoSession.callproc` methods are not
- iterators and return the full result set
- using `psycopg2.cursor.fetchall()`.
+ .. Note:: Unlike :py:meth:`Session.query <queries.Session.query>` and
+ :py:meth:`Session.callproc <queries.Session.callproc>`, the
+ :py:meth:`TornadoSession.query <queries.TornadoSession.query>` and
+ :py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>`
+ methods are not iterators and will return the full result set using
+ :py:meth:`cursor.fetchall`.
:param str uri: PostgreSQL connection URI
:param psycopg2.cursor: The cursor type to use
@@ -60,7 +64,7 @@ class TornadoSession(session.Session):
set the isolation level.
:param str uri: PostgreSQL connection URI
- :param psycopg2.cursor: The cursor type to use
+ :param psycopg2.extensions.cursor: The cursor type to use
:param bool use_pool: Use the connection pool
:param int max_pool_size: Max number of connections for a single URI
@@ -82,6 +86,8 @@ class TornadoSession(session.Session):
as a list. If no results are returned, the method will return None
instead.
+ Example:
+
.. code:: python
data = yield session.callproc('char', [65])
@@ -135,31 +141,31 @@ class TornadoSession(session.Session):
"""Listen for notifications from PostgreSQL on the specified channel,
passing in a callback to receive the notifications.
- ..code:: python
+ Example:
- class ListenHandler(web.RequestHandler):
+ .. code:: python
- def initialize(self):
- self.channel = 'example'
- self.session = queries.TornadoSession()
+ class ListenHandler(web.RequestHandler):
- @gen.coroutine
- def get(self, *args, **kwargs):
- yield self.session.listen(self.channel, self.on_notification)
- self.finish()
+ def initialize(self):
+ self.channel = 'example'
+ self.session = queries.TornadoSession()
- def on_connection_close(self):
- if self.channel:
- self.session.unlisten(self.channel)
- self.channel = None
+ @gen.coroutine
+ def get(self, *args, **kwargs):
+ yield self.session.listen(self.channel,
+ self.on_notification)
+ self.finish()
- @gen.coroutine
- def on_notification(self, channel, pid, payload):
- self.write('Payload: %s\n' % payload)
- yield gen.Task(self.flush)
+ def on_connection_close(self):
+ if self.channel:
+ self.session.unlisten(self.channel)
+ self.channel = None
- See the documentation at https://queries.readthedocs.org for a more
- complete example.
+ @gen.coroutine
+ def on_notification(self, channel, pid, payload):
+ self.write('Payload: %s\\n' % payload)
+ yield gen.Task(self.flush)
:param str channel: The channel to stop listening on
:param method callback: The method to call on each notification
@@ -210,6 +216,8 @@ class TornadoSession(session.Session):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results as list.
+ Example:
+
.. code:: python
data = yield session.query('SELECT * FROM foo WHERE bar=%(bar)s',
@@ -263,7 +271,9 @@ class TornadoSession(session.Session):
def unlisten(self, channel):
"""Cancel a listening on a channel.
- ..code:: python
+ Example:
+
+ .. code:: python
yield self.session.unlisten('channel-name')
@@ -292,7 +302,7 @@ class TornadoSession(session.Session):
"""Connect to PostgreSQL and setup a few variables and data structures
to reduce code in the coroutine methods.
- :rtype: tuple(psycopg2._psycopg.connection, int, int)
+ :return tuple: psycopg2.extensions.connection, int, int
"""
connection = super(TornadoSession, self)._connect()
@@ -307,7 +317,7 @@ class TornadoSession(session.Session):
"""Close the cursor, remove any references to the fd in internal state
and remove the fd from the ioloop.
- :param psycopg2.cursor cursor: The cursor to close
+ :param psycopg2.extensions.cursor cursor: The cursor to close
:param int fd: The connection file descriptor
"""
@@ -323,7 +333,7 @@ class TornadoSession(session.Session):
def _get_cursor(self, connection):
"""Return a cursor for the given connection.
- :param psycopg2._psycopg.connection connection: The connection to use
+ :param psycopg2.extensions.connection connection: The connection to use
:rtype: psycopg2.extensions.cursor
"""
@@ -370,7 +380,7 @@ class TornadoSession(session.Session):
use in async session adapters.
:param dict kwargs: Keyword connection args
- :rtype: psycopg2.connection
+ :rtype: psycopg2.extensions.connection
"""
kwargs['async'] = True
| 53 | Documentation updates | 43 | .py | py | bsd-3-clause | gmr/queries |
1411 | <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
Requirements
------------
- psycopg2 (for cpython support)
- psycopg2ct (for PyPy support)
Example
-------
------------
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> Remove indent
<DFF> @@ -23,8 +23,8 @@ pip install pgsql_wrapper
Requirements
------------
- - psycopg2 (for cpython support)
- - psycopg2ct (for PyPy support)
+- psycopg2 (for cpython support)
+- psycopg2ct (for PyPy support)
Example
-------
| 2 | Remove indent | 2 | .rst | rst | bsd-3-clause | gmr/queries |
1412 | <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
Requirements
------------
- psycopg2 (for cpython support)
- psycopg2ct (for PyPy support)
Example
-------
------------
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> Remove indent
<DFF> @@ -23,8 +23,8 @@ pip install pgsql_wrapper
Requirements
------------
- - psycopg2 (for cpython support)
- - psycopg2ct (for PyPy support)
+- psycopg2 (for cpython support)
+- psycopg2ct (for PyPy support)
Example
-------
| 2 | Remove indent | 2 | .rst | rst | bsd-3-clause | gmr/queries |
1413 | <NME> tornado_multiple.rst
<BEF> ADDFILE
<MSG> Add a concurrent query example
<DFF> @@ -0,0 +1,34 @@
+Concurrent Queries in Tornado
+=============================
+The following example issues multiple concurrent queries in a single asynchronous
+request and will wait until all queries are complete before progressing:
+
+.. code:: python
+
+ from tornado import gen, ioloop, web
+ import queries
+
+
+ class RequestHandler(web.RequestHandler):
+
+ def initialize(self):
+ self.session = queries.TornadoSession()
+
+ @gen.coroutine
+ def get(self, *args, **kwargs):
+
+ # Issue the three queries and wait for them to finish before progressing
+ q1result, q2result = yield [self.session.query('SELECT * FROM foo'),
+ self.session.query('SELECT * FROM bar'),
+ self.session.query('INSERT INTO requests VALUES (%s, %s, %s)',
+ [self.remote_ip,
+ self.request_uri,
+ self.headers.get('User-Agent', '')])]
+ # Close the connection
+ self.finish({'q1result': q1result, 'q2result': q2result})
+
+ if __name__ == "__main__":
+ application = web.Application([
+ (r"/", RequestHandler)
+ ]).listen(8888)
+ ioloop.IOLoop.instance().start()
\ No newline at end of file
| 34 | Add a concurrent query example | 0 | .rst | rst | bsd-3-clause | gmr/queries |
1414 | <NME> tornado_multiple.rst
<BEF> ADDFILE
<MSG> Add a concurrent query example
<DFF> @@ -0,0 +1,34 @@
+Concurrent Queries in Tornado
+=============================
+The following example issues multiple concurrent queries in a single asynchronous
+request and will wait until all queries are complete before progressing:
+
+.. code:: python
+
+ from tornado import gen, ioloop, web
+ import queries
+
+
+ class RequestHandler(web.RequestHandler):
+
+ def initialize(self):
+ self.session = queries.TornadoSession()
+
+ @gen.coroutine
+ def get(self, *args, **kwargs):
+
+ # Issue the three queries and wait for them to finish before progressing
+ q1result, q2result = yield [self.session.query('SELECT * FROM foo'),
+ self.session.query('SELECT * FROM bar'),
+ self.session.query('INSERT INTO requests VALUES (%s, %s, %s)',
+ [self.remote_ip,
+ self.request_uri,
+ self.headers.get('User-Agent', '')])]
+ # Close the connection
+ self.finish({'q1result': q1result, 'q2result': q2result})
+
+ if __name__ == "__main__":
+ application = web.Application([
+ (r"/", RequestHandler)
+ ]).listen(8888)
+ ioloop.IOLoop.instance().start()
\ No newline at end of file
| 34 | Add a concurrent query example | 0 | .rst | rst | bsd-3-clause | gmr/queries |
1415 | <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| |License|
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())
...
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 is an example of using Queries in a Tornado_ web
application.
.. code:: python
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.listen(8888)
ioloop.IOLoop.instance().start()
.. [*] The Queries simple API methods are synchronous only and should not be used
in an asynchronous Tornado application.
Inspiration
-----------
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> Update the TornadoSession information a bit
[ci skip]
<DFF> @@ -118,8 +118,8 @@ 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 is an example of using Queries in a Tornado_ web
-application.
+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
@@ -145,8 +145,7 @@ application.
application.listen(8888)
ioloop.IOLoop.instance().start()
-.. [*] The Queries simple API methods are synchronous only and should not be used
-in an asynchronous Tornado application.
+.. [*] Simple API methods are not asynchronous and should not be used in an asynchronous Tornado application.
Inspiration
-----------
| 3 | Update the TornadoSession information a bit | 4 | .rst | rst | bsd-3-clause | gmr/queries |
1416 | <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| |License|
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())
...
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 is an example of using Queries in a Tornado_ web
application.
.. code:: python
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.listen(8888)
ioloop.IOLoop.instance().start()
.. [*] The Queries simple API methods are synchronous only and should not be used
in an asynchronous Tornado application.
Inspiration
-----------
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> Update the TornadoSession information a bit
[ci skip]
<DFF> @@ -118,8 +118,8 @@ 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 is an example of using Queries in a Tornado_ web
-application.
+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
@@ -145,8 +145,7 @@ application.
application.listen(8888)
ioloop.IOLoop.instance().start()
-.. [*] The Queries simple API methods are synchronous only and should not be used
-in an asynchronous Tornado application.
+.. [*] Simple API methods are not asynchronous and should not be used in an asynchronous Tornado application.
Inspiration
-----------
| 3 | Update the TornadoSession information a bit | 4 | .rst | rst | bsd-3-clause | gmr/queries |
1417 | <NME> setup.py
<BEF> import os
import platform
import setuptools
# PYPY vs cpython
if platform.python_implementation() == 'PyPy':
else:
install_requires = ['psycopg2']
setup(name='pgsql_wrapper',
version='1.1.2',
description="PostgreSQL / psycopg2 caching wrapper class",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
url="http://github.com/MeetMe/pgsql_wrapper",
install_requires=install_requires,
py_modules=['pgsql_wrapper'],
zip_safe=True)
'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> Updates to distribution support files
<DFF> @@ -8,12 +8,30 @@ if target == 'PyPy':
else:
install_requires = ['psycopg2']
+
setup(name='pgsql_wrapper',
- version='1.1.2',
+ version='1.2.0',
description="PostgreSQL / psycopg2 caching wrapper class",
maintainer="Gavin M. Roy",
- maintainer_email="[email protected]",
- url="http://github.com/MeetMe/pgsql_wrapper",
+ maintainer_email="[email protected]",
+ url="https://github.com/gmr/pgsql_wrapper",
install_requires=install_requires,
+ license=open('LICENSE').read(),
+ package_data={'': ['LICENSE', 'README.md']},
py_modules=['pgsql_wrapper'],
+ 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.6',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.2',
+ 'Programming Language :: Python :: 3.3',
+ 'Programming Language :: Python :: 3.4',
+ 'Programming Language :: Python :: Implementation :: CPython',
+ 'Programming Language :: Python :: Implementation :: PyPy',
+ 'Topic :: Database',
+ 'Topic :: Software Development :: Libraries'],
zip_safe=True)
| 21 | Updates to distribution support files | 3 | .py | py | bsd-3-clause | gmr/queries |
1418 | <NME> setup.py
<BEF> import os
import platform
import setuptools
# PYPY vs cpython
if platform.python_implementation() == 'PyPy':
else:
install_requires = ['psycopg2']
setup(name='pgsql_wrapper',
version='1.1.2',
description="PostgreSQL / psycopg2 caching wrapper class",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
url="http://github.com/MeetMe/pgsql_wrapper",
install_requires=install_requires,
py_modules=['pgsql_wrapper'],
zip_safe=True)
'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> Updates to distribution support files
<DFF> @@ -8,12 +8,30 @@ if target == 'PyPy':
else:
install_requires = ['psycopg2']
+
setup(name='pgsql_wrapper',
- version='1.1.2',
+ version='1.2.0',
description="PostgreSQL / psycopg2 caching wrapper class",
maintainer="Gavin M. Roy",
- maintainer_email="[email protected]",
- url="http://github.com/MeetMe/pgsql_wrapper",
+ maintainer_email="[email protected]",
+ url="https://github.com/gmr/pgsql_wrapper",
install_requires=install_requires,
+ license=open('LICENSE').read(),
+ package_data={'': ['LICENSE', 'README.md']},
py_modules=['pgsql_wrapper'],
+ 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.6',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.2',
+ 'Programming Language :: Python :: 3.3',
+ 'Programming Language :: Python :: 3.4',
+ 'Programming Language :: Python :: Implementation :: CPython',
+ 'Programming Language :: Python :: Implementation :: PyPy',
+ 'Topic :: Database',
+ 'Topic :: Software Development :: Libraries'],
zip_safe=True)
| 21 | Updates to distribution support files | 3 | .py | py | bsd-3-clause | gmr/queries |
1419 | <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 = pool_max_size
self._pool_idle_ttl = pool_idle_ttl
self._uri = uri
def _ensure_pool_exists(self):
"""Create the pool in the pool manager if it does not exist."""
"""
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> Ensure the pool exists on creation too
<DFF> @@ -169,6 +169,7 @@ class TornadoSession(session.Session):
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."""
| 1 | Ensure the pool exists on creation too | 0 | .py | py | bsd-3-clause | gmr/queries |
1420 | <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 = pool_max_size
self._pool_idle_ttl = pool_idle_ttl
self._uri = uri
def _ensure_pool_exists(self):
"""Create the pool in the pool manager if it does not exist."""
"""
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> Ensure the pool exists on creation too
<DFF> @@ -169,6 +169,7 @@ class TornadoSession(session.Session):
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."""
| 1 | Ensure the pool exists on creation too | 0 | .py | py | bsd-3-clause | gmr/queries |
1421 | <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
values = parse_qs(parsed.query)
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]
if kwargs[k].isdigit():
kwargs[k] = int(kwargs[k])
return kwargs
: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
"""
if port:
host = '%s:%s' % (host, port)
if password:
return 'postgresql://%s:%s@%s/%s' % (user, password, host, dbname)
return 'postgresql://%s@%s/%s' % (user, host, dbname)
def uri_to_kwargs(uri):
"""Return a URI as kwargs for connecting to PostgreSQL with psycopg2,
applying default values for non-specified areas of the URI.
:param str uri: The connection URI
:rtype: dict
"""
parsed = urlparse(uri)
default_user = get_current_user()
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> utils.py: fix a bug with lists of things, add test coverage
<DFF> @@ -76,8 +76,11 @@ def uri_to_kwargs(uri):
values = parse_qs(parsed.query)
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]
- if kwargs[k].isdigit():
- kwargs[k] = int(kwargs[k])
+ try:
+ if kwargs[k].isdigit():
+ kwargs[k] = int(kwargs[k])
+ except AttributeError:
+ pass
return kwargs
| 5 | utils.py: fix a bug with lists of things, add test coverage | 2 | .py | py | bsd-3-clause | gmr/queries |
1422 | <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
values = parse_qs(parsed.query)
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]
if kwargs[k].isdigit():
kwargs[k] = int(kwargs[k])
return kwargs
: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
"""
if port:
host = '%s:%s' % (host, port)
if password:
return 'postgresql://%s:%s@%s/%s' % (user, password, host, dbname)
return 'postgresql://%s@%s/%s' % (user, host, dbname)
def uri_to_kwargs(uri):
"""Return a URI as kwargs for connecting to PostgreSQL with psycopg2,
applying default values for non-specified areas of the URI.
:param str uri: The connection URI
:rtype: dict
"""
parsed = urlparse(uri)
default_user = get_current_user()
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> utils.py: fix a bug with lists of things, add test coverage
<DFF> @@ -76,8 +76,11 @@ def uri_to_kwargs(uri):
values = parse_qs(parsed.query)
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]
- if kwargs[k].isdigit():
- kwargs[k] = int(kwargs[k])
+ try:
+ if kwargs[k].isdigit():
+ kwargs[k] = int(kwargs[k])
+ except AttributeError:
+ pass
return kwargs
| 5 | utils.py: fix a bug with lists of things, add test coverage | 2 | .py | py | bsd-3-clause | gmr/queries |
1423 | <NME> tornado_session.rst
<BEF> TornadoSession Asynchronous API
===============================
Use a Queries Session asynchronously within the `Tornado <http://www.tornadoweb.org>`_ framework.
The :py:class:`TornadoSession <queries.TornadoSession>` class is optimized for
asynchronous concurrency. Each call to
:py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or
:py:meth:`TornadoSession.query <queries.TornadoSession.query>` grabs a free
connection from the connection pool and requires that the results that are r
returned as a
:py:class:`Results <queries.tornado_session.Results>` object are freed via the
:py:meth:`Results.free <queries.tornado_session.Results.free>` method. Doing
so will release the free the `Results` object data and release the lock on
the connection so that other queries are able to use the connection.
Example Use
-----------
The following :py:class:`~tornado.web.RequestHandler` example will return a
JSON document containing the query results.
.. code:: python
import queries
from tornado import gen, web
class ExampleHandler(web.RequestHandler):
def initialize(self):
self.session = queries.TornadoSession()
@gen.coroutine
def get(self):
result = yield self.session.query('SELECT * FROM names')
self.finish({'data': result.items()})
result.free()
See the :doc:`examples/index` for more :py:meth:`~queries.TornadoSession` examples.
Class Documentation
-------------------
.. autoclass:: queries.tornado_session.TornadoSession
:members:
:inherited-members:
.. autoclass:: queries.tornado_session.Results
:members:
:inherited-members:
<MSG> Add module directives to fix #35
<DFF> @@ -1,3 +1,5 @@
+.. py:module:: queries.tornado_session
+
TornadoSession Asynchronous API
===============================
Use a Queries Session asynchronously within the `Tornado <http://www.tornadoweb.org>`_ framework.
| 2 | Add module directives to fix #35 | 0 | .rst | rst | bsd-3-clause | gmr/queries |
1424 | <NME> tornado_session.rst
<BEF> TornadoSession Asynchronous API
===============================
Use a Queries Session asynchronously within the `Tornado <http://www.tornadoweb.org>`_ framework.
The :py:class:`TornadoSession <queries.TornadoSession>` class is optimized for
asynchronous concurrency. Each call to
:py:meth:`TornadoSession.callproc <queries.TornadoSession.callproc>` or
:py:meth:`TornadoSession.query <queries.TornadoSession.query>` grabs a free
connection from the connection pool and requires that the results that are r
returned as a
:py:class:`Results <queries.tornado_session.Results>` object are freed via the
:py:meth:`Results.free <queries.tornado_session.Results.free>` method. Doing
so will release the free the `Results` object data and release the lock on
the connection so that other queries are able to use the connection.
Example Use
-----------
The following :py:class:`~tornado.web.RequestHandler` example will return a
JSON document containing the query results.
.. code:: python
import queries
from tornado import gen, web
class ExampleHandler(web.RequestHandler):
def initialize(self):
self.session = queries.TornadoSession()
@gen.coroutine
def get(self):
result = yield self.session.query('SELECT * FROM names')
self.finish({'data': result.items()})
result.free()
See the :doc:`examples/index` for more :py:meth:`~queries.TornadoSession` examples.
Class Documentation
-------------------
.. autoclass:: queries.tornado_session.TornadoSession
:members:
:inherited-members:
.. autoclass:: queries.tornado_session.Results
:members:
:inherited-members:
<MSG> Add module directives to fix #35
<DFF> @@ -1,3 +1,5 @@
+.. py:module:: queries.tornado_session
+
TornadoSession Asynchronous API
===============================
Use a Queries Session asynchronously within the `Tornado <http://www.tornadoweb.org>`_ framework.
| 2 | Add module directives to fix #35 | 0 | .rst | rst | bsd-3-clause | gmr/queries |
1425 | <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
: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.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()]),
:param str pid: The pool ID
:param int idle_ttl: Time in seconds for the idle TTL
:param class pool_type: The pool type to create
:raises: KeyError
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 cls._lock:
return cls._pools[pid].free(connection)
@classmethod
def is_full(cls, pid):
"""Return a bool indicating if the specified pool is full
:param str pid: The pool id
:rtype: bool
"""
cls._ensure_pool_exists(pid)
return cls._pools[pid].is_full
@classmethod
def has_connection(cls, pid, connection):
"""Check to see if a pool has the specified connection
"""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
cls._ensure_pool_exists(pid)
return bool(cls._pools[pid].idle_connections)
@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
"""
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> Move PoolManager.is_full after PoolManager.has_idle_connection
<DFF> @@ -377,6 +377,7 @@ class PoolManager(object):
: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 class pool_type: The pool type to create
:raises: KeyError
@@ -414,17 +415,6 @@ class PoolManager(object):
with cls._lock:
return cls._pools[pid].free(connection)
- @classmethod
- def is_full(cls, pid):
- """Return a bool indicating if the specified pool is full
-
- :param str pid: The pool id
- :rtype: bool
-
- """
- cls._ensure_pool_exists(pid)
- return cls._pools[pid].is_full
-
@classmethod
def has_connection(cls, pid, connection):
"""Check to see if a pool has the specified connection
@@ -449,6 +439,17 @@ class PoolManager(object):
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
+
+ """
+ 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
| 12 | Move PoolManager.is_full after PoolManager.has_idle_connection | 11 | .py | py | bsd-3-clause | gmr/queries |
1426 | <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
: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.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()]),
:param str pid: The pool ID
:param int idle_ttl: Time in seconds for the idle TTL
:param class pool_type: The pool type to create
:raises: KeyError
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 cls._lock:
return cls._pools[pid].free(connection)
@classmethod
def is_full(cls, pid):
"""Return a bool indicating if the specified pool is full
:param str pid: The pool id
:rtype: bool
"""
cls._ensure_pool_exists(pid)
return cls._pools[pid].is_full
@classmethod
def has_connection(cls, pid, connection):
"""Check to see if a pool has the specified connection
"""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
cls._ensure_pool_exists(pid)
return bool(cls._pools[pid].idle_connections)
@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
"""
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> Move PoolManager.is_full after PoolManager.has_idle_connection
<DFF> @@ -377,6 +377,7 @@ class PoolManager(object):
: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 class pool_type: The pool type to create
:raises: KeyError
@@ -414,17 +415,6 @@ class PoolManager(object):
with cls._lock:
return cls._pools[pid].free(connection)
- @classmethod
- def is_full(cls, pid):
- """Return a bool indicating if the specified pool is full
-
- :param str pid: The pool id
- :rtype: bool
-
- """
- cls._ensure_pool_exists(pid)
- return cls._pools[pid].is_full
-
@classmethod
def has_connection(cls, pid, connection):
"""Check to see if a pool has the specified connection
@@ -449,6 +439,17 @@ class PoolManager(object):
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
+
+ """
+ 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
| 12 | Move PoolManager.is_full after PoolManager.has_idle_connection | 11 | .py | py | bsd-3-clause | gmr/queries |
1427 | <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)
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]
self._futures[fd].set_exception(error)
else:
if state == extensions.POLL_OK:
if fd in self._futures:
self._futures[fd].set_result(True)
elif state == extensions.POLL_WRITE:
self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE)
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> Try and work around pypy on travis issue
<DFF> @@ -452,7 +452,7 @@ class TornadoSession(session.Session):
self._futures[fd].set_exception(error)
else:
if state == extensions.POLL_OK:
- if fd in self._futures:
+ 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)
| 1 | Try and work around pypy on travis issue | 1 | .py | py | bsd-3-clause | gmr/queries |
1428 | <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)
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]
self._futures[fd].set_exception(error)
else:
if state == extensions.POLL_OK:
if fd in self._futures:
self._futures[fd].set_result(True)
elif state == extensions.POLL_WRITE:
self._ioloop.update_handler(fd, ioloop.IOLoop.WRITE)
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> Try and work around pypy on travis issue
<DFF> @@ -452,7 +452,7 @@ class TornadoSession(session.Session):
self._futures[fd].set_exception(error)
else:
if state == extensions.POLL_OK:
- if fd in self._futures:
+ 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)
| 1 | Try and work around pypy on travis issue | 1 | .py | py | bsd-3-clause | gmr/queries |
1429 | <NME> session_tests.py
<BEF> """
Tests for functionality in the session module
"""
import hashlib
import mock
import uuid
try:
import unittest2 as unittest
except ImportError:
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_uuid')
@mock.patch('queries.utils.uri_to_kwargs')
def setUp(self, uri_to_kwargs, register_uuid, register_type, connect):
self.conn = mock.Mock()
self.conn.autocommit = False
self.conn.closed = False
self.conn.cursor = mock.Mock()
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_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': 'bar',
'dbname': 'foo'}
self.obj = session.Session(self.URI, pool_max_size=100)
def test_init_sets_uri(self):
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):
self.obj.close()
self.assertNotIn(self.conn,
self.obj._pool_manager._pools[self.obj.pid])
def test_close_unassigns_connection(self):
self.obj.close()
self.assertIsNone(self.obj._conn)
def test_close_unassigns_cursor(self):
self.obj.close()
self.assertIsNone(self.obj._cursor)
def test_connection_property_returns_correct_value(self):
self.assertEqual(self.obj.connection, self.conn)
def test_cursor_property_returns_correct_value(self):
self.assertEqual(self.obj.cursor, self.obj._cursor)
def test_encoding_property_value(self):
self.conn.encoding = 'UTF-8'
self.assertEqual(self.obj.encoding, 'UTF-8')
def test_notices_value(self):
self.conn.notices = [1, 2, 3]
self.assertListEqual(self.obj.notices, [1, 2, 3])
def test_pid_value(self):
expectation = hashlib.md5(
':'.join([self.obj.__class__.__name__,
self.URI]).encode('utf-8')).hexdigest()
self.assertEqual(self.obj.pid, expectation)
def test_query_invokes_cursor_execute(self):
self.obj._cursor.callproc = mock.Mock()
args = ('SELECT * FROM foo', ['bar', 'baz'])
self.obj.query(*args)
self.obj._cursor.execute.assert_called_once_with(*args)
def test_set_encoding_sets_encoding_if_different(self):
self.conn.encoding = 'LATIN-1'
self.conn.set_client_encoding = set_client_encoding = mock.Mock()
self.obj.set_encoding('UTF-8')
set_client_encoding.assert_called_once_with('UTF-8')
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()
self.obj.set_encoding('UTF-8')
self.assertFalse(set_client_encoding.called)
@unittest.skipIf(utils.PYPY,
'PYPY does not invoke object.__del__ synchronously')
def test_del_invokes_cleanup(self):
cleanup = mock.Mock()
with mock.patch.multiple('queries.session.Session',
_cleanup=cleanup,
_connect=mock.Mock(),
_get_cursor=mock.Mock(),
_autocommit=mock.Mock()):
obj = session.Session(self.URI)
del obj
"""Ensure Session._cursor is None after close"""
sess = session.Session('pgsql://foo@bar:9999/baz')
sess.close()
self.assertRaises(AssertionError, 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> Fix the unittest to reflect the new exception type
<DFF> @@ -4,7 +4,6 @@ Tests for the session.Session class
"""
import hashlib
import mock
-import uuid
try:
import unittest2 as unittest
except ImportError:
@@ -154,4 +153,4 @@ class SessionTests(unittest.TestCase):
"""Ensure Session._cursor is None after close"""
sess = session.Session('pgsql://foo@bar:9999/baz')
sess.close()
- self.assertRaises(AssertionError, sess.close)
+ self.assertRaises(psycopg2.InterfaceError, sess.close)
| 1 | Fix the unittest to reflect the new exception type | 2 | .py | py | bsd-3-clause | gmr/queries |
1430 | <NME> session_tests.py
<BEF> """
Tests for functionality in the session module
"""
import hashlib
import mock
import uuid
try:
import unittest2 as unittest
except ImportError:
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_uuid')
@mock.patch('queries.utils.uri_to_kwargs')
def setUp(self, uri_to_kwargs, register_uuid, register_type, connect):
self.conn = mock.Mock()
self.conn.autocommit = False
self.conn.closed = False
self.conn.cursor = mock.Mock()
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_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': 'bar',
'dbname': 'foo'}
self.obj = session.Session(self.URI, pool_max_size=100)
def test_init_sets_uri(self):
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):
self.obj.close()
self.assertNotIn(self.conn,
self.obj._pool_manager._pools[self.obj.pid])
def test_close_unassigns_connection(self):
self.obj.close()
self.assertIsNone(self.obj._conn)
def test_close_unassigns_cursor(self):
self.obj.close()
self.assertIsNone(self.obj._cursor)
def test_connection_property_returns_correct_value(self):
self.assertEqual(self.obj.connection, self.conn)
def test_cursor_property_returns_correct_value(self):
self.assertEqual(self.obj.cursor, self.obj._cursor)
def test_encoding_property_value(self):
self.conn.encoding = 'UTF-8'
self.assertEqual(self.obj.encoding, 'UTF-8')
def test_notices_value(self):
self.conn.notices = [1, 2, 3]
self.assertListEqual(self.obj.notices, [1, 2, 3])
def test_pid_value(self):
expectation = hashlib.md5(
':'.join([self.obj.__class__.__name__,
self.URI]).encode('utf-8')).hexdigest()
self.assertEqual(self.obj.pid, expectation)
def test_query_invokes_cursor_execute(self):
self.obj._cursor.callproc = mock.Mock()
args = ('SELECT * FROM foo', ['bar', 'baz'])
self.obj.query(*args)
self.obj._cursor.execute.assert_called_once_with(*args)
def test_set_encoding_sets_encoding_if_different(self):
self.conn.encoding = 'LATIN-1'
self.conn.set_client_encoding = set_client_encoding = mock.Mock()
self.obj.set_encoding('UTF-8')
set_client_encoding.assert_called_once_with('UTF-8')
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()
self.obj.set_encoding('UTF-8')
self.assertFalse(set_client_encoding.called)
@unittest.skipIf(utils.PYPY,
'PYPY does not invoke object.__del__ synchronously')
def test_del_invokes_cleanup(self):
cleanup = mock.Mock()
with mock.patch.multiple('queries.session.Session',
_cleanup=cleanup,
_connect=mock.Mock(),
_get_cursor=mock.Mock(),
_autocommit=mock.Mock()):
obj = session.Session(self.URI)
del obj
"""Ensure Session._cursor is None after close"""
sess = session.Session('pgsql://foo@bar:9999/baz')
sess.close()
self.assertRaises(AssertionError, 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> Fix the unittest to reflect the new exception type
<DFF> @@ -4,7 +4,6 @@ Tests for the session.Session class
"""
import hashlib
import mock
-import uuid
try:
import unittest2 as unittest
except ImportError:
@@ -154,4 +153,4 @@ class SessionTests(unittest.TestCase):
"""Ensure Session._cursor is None after close"""
sess = session.Session('pgsql://foo@bar:9999/baz')
sess.close()
- self.assertRaises(AssertionError, sess.close)
+ self.assertRaises(psycopg2.InterfaceError, sess.close)
| 1 | Fix the unittest to reflect the new exception type | 2 | .py | py | bsd-3-clause | gmr/queries |
1431 | <NME> utils_tests.py
<BEF> """
Tests for functionality in the utils module
"""
import mock
import platform
import unittest
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 URLParseTestCase(unittest.TestCase):
URI = 'postgresql://foo:bar@baz:5444/qux'
def test_urlparse_hostname(self):
"""hostname should match expectation"""
self.assertEqual(utils.urlparse(self.URI).hostname, 'baz')
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_urlparse_password(self):
"""password should match expectation"""
self.assertEqual(utils.urlparse(self.URI).password, 'bar')
class URIToKWargsTestCase(unittest.TestCase):
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"""
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> More flake8 config and cleanup
<DFF> @@ -2,10 +2,11 @@
Tests for functionality in the utils module
"""
-import mock
import platform
import unittest
+import mock
+
import queries
from queries import utils
| 2 | More flake8 config and cleanup | 1 | .py | py | bsd-3-clause | gmr/queries |
1432 | <NME> utils_tests.py
<BEF> """
Tests for functionality in the utils module
"""
import mock
import platform
import unittest
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 URLParseTestCase(unittest.TestCase):
URI = 'postgresql://foo:bar@baz:5444/qux'
def test_urlparse_hostname(self):
"""hostname should match expectation"""
self.assertEqual(utils.urlparse(self.URI).hostname, 'baz')
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_urlparse_password(self):
"""password should match expectation"""
self.assertEqual(utils.urlparse(self.URI).password, 'bar')
class URIToKWargsTestCase(unittest.TestCase):
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"""
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> More flake8 config and cleanup
<DFF> @@ -2,10 +2,11 @@
Tests for functionality in the utils module
"""
-import mock
import platform
import unittest
+import mock
+
import queries
from queries import utils
| 2 | More flake8 config and cleanup | 1 | .py | py | bsd-3-clause | gmr/queries |
1433 | <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 psycopg2cffi.extensions
except ImportError:
pass
else:
sys.modules['psycopg2'] = psycopg2cffi
sys.modules['psycopg2.extras'] = psycopg2cffi.extras
sys.modules['psycopg2.extensions'] = psycopg2cffi.extensions
from queries.results import Results
from queries.session import Session
try:
from queries.tornado_session import TornadoSession
except ImportError: # pragma: nocover
TornadoSession = None
from queries.utils import uri
# 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
from psycopg2 import InternalError
from psycopg2 import NotSupportedError
from psycopg2 import OperationalError
except ImportError:
TornadoSession = None
# For ease of access to different cursor types
from psycopg2.extras import DictCursor
from psycopg2.extras import NamedTupleCursor
<MSG> Add the uri method back
<DFF> @@ -50,6 +50,24 @@ try:
except ImportError:
TornadoSession = None
+
+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
+
+ """
+ if password:
+ return 'pgsql://%s:%s@%s:%i/%s' % (user, password, host, port, dbname)
+ return 'pgsql://%s@%s:%i/%s' % (user, host, port, dbname)
+
+
# For ease of access to different cursor types
from psycopg2.extras import DictCursor
from psycopg2.extras import NamedTupleCursor
| 18 | Add the uri method back | 0 | .py | py | bsd-3-clause | gmr/queries |
1434 | <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 psycopg2cffi.extensions
except ImportError:
pass
else:
sys.modules['psycopg2'] = psycopg2cffi
sys.modules['psycopg2.extras'] = psycopg2cffi.extras
sys.modules['psycopg2.extensions'] = psycopg2cffi.extensions
from queries.results import Results
from queries.session import Session
try:
from queries.tornado_session import TornadoSession
except ImportError: # pragma: nocover
TornadoSession = None
from queries.utils import uri
# 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
from psycopg2 import InternalError
from psycopg2 import NotSupportedError
from psycopg2 import OperationalError
except ImportError:
TornadoSession = None
# For ease of access to different cursor types
from psycopg2.extras import DictCursor
from psycopg2.extras import NamedTupleCursor
<MSG> Add the uri method back
<DFF> @@ -50,6 +50,24 @@ try:
except ImportError:
TornadoSession = None
+
+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
+
+ """
+ if password:
+ return 'pgsql://%s:%s@%s:%i/%s' % (user, password, host, port, dbname)
+ return 'pgsql://%s@%s:%i/%s' % (user, host, port, dbname)
+
+
# For ease of access to different cursor types
from psycopg2.extras import DictCursor
from psycopg2.extras import NamedTupleCursor
| 18 | Add the uri method back | 0 | .py | py | bsd-3-clause | gmr/queries |
1435 | <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',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Database',
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> Revert explicit Python 3.7 support
<DFF> @@ -22,7 +22,6 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
- 'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Database',
| 0 | Revert explicit Python 3.7 support | 1 | .py | py | bsd-3-clause | gmr/queries |
1436 | <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',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Database',
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> Revert explicit Python 3.7 support
<DFF> @@ -22,7 +22,6 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
- 'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Database',
| 0 | Revert explicit Python 3.7 support | 1 | .py | py | bsd-3-clause | gmr/queries |
1437 | <NME> history.rst
<BEF> Version History
===============
- 1.5.0 2014-10-07
- Handle empty query results in the iterator (#4) - Fix by Den T.
- 1.4.0 2014-09-04
- Address exception handling in tornado_session
- Fix Results iterator for Python 3.7 (#31 - `nvllsvm <https://github.com/nvllsvm>`_)
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
-----------------
- 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 attribution
<DFF> @@ -1,6 +1,6 @@
Version History
===============
- 1.5.0 2014-10-07
- - Handle empty query results in the iterator (#4) - Fix by Den T.
+ - Handle empty query results in the iterator (#4) - Fix by Den Teresh
- 1.4.0 2014-09-04
- Address exception handling in tornado_session
| 1 | Fix attribution | 1 | .rst | rst | bsd-3-clause | gmr/queries |
1438 | <NME> history.rst
<BEF> Version History
===============
- 1.5.0 2014-10-07
- Handle empty query results in the iterator (#4) - Fix by Den T.
- 1.4.0 2014-09-04
- Address exception handling in tornado_session
- Fix Results iterator for Python 3.7 (#31 - `nvllsvm <https://github.com/nvllsvm>`_)
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
-----------------
- 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 attribution
<DFF> @@ -1,6 +1,6 @@
Version History
===============
- 1.5.0 2014-10-07
- - Handle empty query results in the iterator (#4) - Fix by Den T.
+ - Handle empty query results in the iterator (#4) - Fix by Den Teresh
- 1.4.0 2014-09-04
- Address exception handling in tornado_session
| 1 | Fix attribution | 1 | .rst | rst | bsd-3-clause | gmr/queries |
1439 | <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
- Simplified API
- Support of Python 2.6+ and 3.2+
- PyPy support via psycopg2ct
- Internal connection pooling
- Asynchronous support for Tornado_
- Automatic registration of UUIDs, Unicode and Unicode Arrays
- Ability to directly access psycopg2 ``connection`` and ``cursor`` objects
- Connection information provided by URI
- Query results delivered as a generator based iterators
|Version| |Downloads| |Status|
-------------
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> Update features a bit
[ci skip]
<DFF> @@ -15,12 +15,12 @@ Key features include:
- Simplified API
- Support of Python 2.6+ and 3.2+
- PyPy support via psycopg2ct
-- Internal connection pooling
- Asynchronous support for Tornado_
-- Automatic registration of UUIDs, Unicode and Unicode Arrays
-- Ability to directly access psycopg2 ``connection`` and ``cursor`` objects
- 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| |Downloads| |Status|
| 3 | Update features a bit | 3 | .rst | rst | bsd-3-clause | gmr/queries |
1440 | <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
- Simplified API
- Support of Python 2.6+ and 3.2+
- PyPy support via psycopg2ct
- Internal connection pooling
- Asynchronous support for Tornado_
- Automatic registration of UUIDs, Unicode and Unicode Arrays
- Ability to directly access psycopg2 ``connection`` and ``cursor`` objects
- Connection information provided by URI
- Query results delivered as a generator based iterators
|Version| |Downloads| |Status|
-------------
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> Update features a bit
[ci skip]
<DFF> @@ -15,12 +15,12 @@ Key features include:
- Simplified API
- Support of Python 2.6+ and 3.2+
- PyPy support via psycopg2ct
-- Internal connection pooling
- Asynchronous support for Tornado_
-- Automatic registration of UUIDs, Unicode and Unicode Arrays
-- Ability to directly access psycopg2 ``connection`` and ``cursor`` objects
- 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| |Downloads| |Status|
| 3 | Update features a bit | 3 | .rst | rst | bsd-3-clause | gmr/queries |
1441 | <NME> tornado_session_tests.py
<BEF> """
Tests for functionality in the tornado_session module
"""
import mock
import tempfile
import time
try:
import unittest2 as unittest
except ImportError:
import unittest
from psycopg2 import extras
import psycopg2
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> Update PYPY edge case
Since connection.reset() can not be called in psycopg2ct, set the status directly
<DFF> @@ -3,15 +3,12 @@ Tests for functionality in the tornado_session module
"""
import mock
-import tempfile
-import time
try:
import unittest2 as unittest
except ImportError:
import unittest
from psycopg2 import extras
-import psycopg2
from tornado import concurrent
from tornado import gen
| 0 | Update PYPY edge case | 3 | .py | py | bsd-3-clause | gmr/queries |
1442 | <NME> tornado_session_tests.py
<BEF> """
Tests for functionality in the tornado_session module
"""
import mock
import tempfile
import time
try:
import unittest2 as unittest
except ImportError:
import unittest
from psycopg2 import extras
import psycopg2
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> Update PYPY edge case
Since connection.reset() can not be called in psycopg2ct, set the status directly
<DFF> @@ -3,15 +3,12 @@ Tests for functionality in the tornado_session module
"""
import mock
-import tempfile
-import time
try:
import unittest2 as unittest
except ImportError:
import unittest
from psycopg2 import extras
-import psycopg2
from tornado import concurrent
from tornado import gen
| 0 | Update PYPY edge case | 3 | .py | py | bsd-3-clause | gmr/queries |
1443 | <NME> conf.py
<BEF> # -*- coding: utf-8 -*-
import datetime
import sys
sys.path.insert(0, '../')
import queries
extensions = [
'sphinx.ext.autodoc',
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
datetime.date.today().strftime('%Y'))
release = queries.__version__
version = '.'.join(release.split('.')[0:1])
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
htmlhelp_basename = 'Queriesdoc'
latex_elements = {}
latex_documents = [
('index', 'Queries.tex', 'Queries Documentation',
'Gavin M. Roy', 'manual'),
]
man_pages = [
('index', 'queries', 'Queries Documentation',
['Gavin M. Roy'], 1)
]
texinfo_documents = [
('index', 'Queries', 'Queries Documentation',
'Gavin M. Roy', 'Queries', 'PostgreSQL Simplified',
'Miscellaneous'),
]
intersphinx_mapping = {
'psycopg2': ('http://initd.org/psycopg/docs/', None),
'tornado': ('http://www.tornadoweb.org/en/stable', None)
}
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.2'
# The full version, including alpha/beta/rc tags.
release = '1.2.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Queries', u'Queries Documentation',
u'Gavin M. Roy', 'Queries', 'One line description of project.',
'Miscellaneous'),
]
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}
<MSG> Dynamically import the version, use intersphinx for Tornado and psycopg2
<DFF> @@ -11,8 +11,8 @@
#
# All configuration values have a default; values that are commented out
# serve to show the default.
-
import sys
+sys.path.insert(0, '../')
import os
# If extensions (or modules to document with autodoc) are in another directory,
@@ -54,10 +54,9 @@ copyright = u'2014, Gavin M. Roy'
# |version| and |release|, also used in various other places throughout the
# built documents.
#
-# The short X.Y version.
-version = '1.2'
-# The full version, including alpha/beta/rc tags.
-release = '1.2.0'
+import queries
+release = queries.__version__
+version = '.'.join(release.split('.')[0:1])
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@@ -245,7 +244,7 @@ man_pages = [
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Queries', u'Queries Documentation',
- u'Gavin M. Roy', 'Queries', 'One line description of project.',
+ u'Gavin M. Roy', 'Queries', 'PostgreSQL Simplified',
'Miscellaneous'),
]
@@ -261,6 +260,6 @@ texinfo_documents = [
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
-
# Example configuration for intersphinx: refer to the Python standard library.
-intersphinx_mapping = {'http://docs.python.org/': None}
+intersphinx_mapping = {'psycopg2': ('http://initd.org/psycopg/docs/', None),
+ 'tornado': ('http://www.tornadoweb.org/en/stable', None)}
| 7 | Dynamically import the version, use intersphinx for Tornado and psycopg2 | 8 | .py | py | bsd-3-clause | gmr/queries |
1444 | <NME> conf.py
<BEF> # -*- coding: utf-8 -*-
import datetime
import sys
sys.path.insert(0, '../')
import queries
extensions = [
'sphinx.ext.autodoc',
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
datetime.date.today().strftime('%Y'))
release = queries.__version__
version = '.'.join(release.split('.')[0:1])
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
htmlhelp_basename = 'Queriesdoc'
latex_elements = {}
latex_documents = [
('index', 'Queries.tex', 'Queries Documentation',
'Gavin M. Roy', 'manual'),
]
man_pages = [
('index', 'queries', 'Queries Documentation',
['Gavin M. Roy'], 1)
]
texinfo_documents = [
('index', 'Queries', 'Queries Documentation',
'Gavin M. Roy', 'Queries', 'PostgreSQL Simplified',
'Miscellaneous'),
]
intersphinx_mapping = {
'psycopg2': ('http://initd.org/psycopg/docs/', None),
'tornado': ('http://www.tornadoweb.org/en/stable', None)
}
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.2'
# The full version, including alpha/beta/rc tags.
release = '1.2.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Queries', u'Queries Documentation',
u'Gavin M. Roy', 'Queries', 'One line description of project.',
'Miscellaneous'),
]
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}
<MSG> Dynamically import the version, use intersphinx for Tornado and psycopg2
<DFF> @@ -11,8 +11,8 @@
#
# All configuration values have a default; values that are commented out
# serve to show the default.
-
import sys
+sys.path.insert(0, '../')
import os
# If extensions (or modules to document with autodoc) are in another directory,
@@ -54,10 +54,9 @@ copyright = u'2014, Gavin M. Roy'
# |version| and |release|, also used in various other places throughout the
# built documents.
#
-# The short X.Y version.
-version = '1.2'
-# The full version, including alpha/beta/rc tags.
-release = '1.2.0'
+import queries
+release = queries.__version__
+version = '.'.join(release.split('.')[0:1])
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@@ -245,7 +244,7 @@ man_pages = [
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Queries', u'Queries Documentation',
- u'Gavin M. Roy', 'Queries', 'One line description of project.',
+ u'Gavin M. Roy', 'Queries', 'PostgreSQL Simplified',
'Miscellaneous'),
]
@@ -261,6 +260,6 @@ texinfo_documents = [
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
-
# Example configuration for intersphinx: refer to the Python standard library.
-intersphinx_mapping = {'http://docs.python.org/': None}
+intersphinx_mapping = {'psycopg2': ('http://initd.org/psycopg/docs/', None),
+ 'tornado': ('http://www.tornadoweb.org/en/stable', None)}
| 7 | Dynamically import the version, use intersphinx for Tornado and psycopg2 | 8 | .py | py | bsd-3-clause | gmr/queries |
1445 | <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:
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> Fix broken test
<DFF> @@ -117,7 +117,7 @@ class SessionConnectTests(testing.AsyncTestCase):
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})
+ 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:
| 1 | Fix broken test | 1 | .py | py | bsd-3-clause | gmr/queries |
1446 | <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:
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> Fix broken test
<DFF> @@ -117,7 +117,7 @@ class SessionConnectTests(testing.AsyncTestCase):
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})
+ 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:
| 1 | Fix broken test | 1 | .py | py | bsd-3-clause | gmr/queries |
1447 | <NME> bootstrap
<BEF> #!/bin/sh
# vim: set ts=2 sts=2 sw=2 et:
test -n "$SHELLDEBUG" && set -x
if test -e /var/run/docker.sock
then
DOCKER_IP=127.0.0.1
else
echo "Docker environment not detected."
exit 1
fi
set -e
if test -z "$COMPOSE_PROJECT_NAME"
then
CWD=${PWD##*/}
export COMPOSE_PROJECT_NAME=${CWD/_/}
fi
mkdir -p build
get_exposed_port() {
docker-compose port $1 $2 | cut -d: -f2
}
docker-compose down --volumes --remove-orphans
docker-compose pull
docker-compose up -d --no-recreate
PORT=$(get_exposed_port postgres 5432)
printf "Waiting for postgres "
export PG
until docker-compose exec postgres pg_isready -q; do
printf "."
sleep 1
done
echo " done"
cat > build/test-environment<<EOF
export PGHOST=${DOCKER_IP}
export PGPORT=${PORT}
EOF
<MSG> Immediately terminate containers in boostrap down
<DFF> @@ -22,7 +22,7 @@ get_exposed_port() {
docker-compose port $1 $2 | cut -d: -f2
}
-docker-compose down --volumes --remove-orphans
+docker-compose down -t 0 --volumes --remove-orphans
docker-compose pull
docker-compose up -d --no-recreate
| 1 | Immediately terminate containers in boostrap down | 1 | bootstrap | bsd-3-clause | gmr/queries |
|
1448 | <NME> bootstrap
<BEF> #!/bin/sh
# vim: set ts=2 sts=2 sw=2 et:
test -n "$SHELLDEBUG" && set -x
if test -e /var/run/docker.sock
then
DOCKER_IP=127.0.0.1
else
echo "Docker environment not detected."
exit 1
fi
set -e
if test -z "$COMPOSE_PROJECT_NAME"
then
CWD=${PWD##*/}
export COMPOSE_PROJECT_NAME=${CWD/_/}
fi
mkdir -p build
get_exposed_port() {
docker-compose port $1 $2 | cut -d: -f2
}
docker-compose down --volumes --remove-orphans
docker-compose pull
docker-compose up -d --no-recreate
PORT=$(get_exposed_port postgres 5432)
printf "Waiting for postgres "
export PG
until docker-compose exec postgres pg_isready -q; do
printf "."
sleep 1
done
echo " done"
cat > build/test-environment<<EOF
export PGHOST=${DOCKER_IP}
export PGPORT=${PORT}
EOF
<MSG> Immediately terminate containers in boostrap down
<DFF> @@ -22,7 +22,7 @@ get_exposed_port() {
docker-compose port $1 $2 | cut -d: -f2
}
-docker-compose down --volumes --remove-orphans
+docker-compose down -t 0 --volumes --remove-orphans
docker-compose pull
docker-compose up -d --no-recreate
| 1 | Immediately terminate containers in boostrap down | 1 | bootstrap | bsd-3-clause | gmr/queries |
|
1449 | <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_uuid')
@mock.patch('queries.utils.uri_to_kwargs')
def setUp(self, uri_to_kwargs, register_uuid, register_type, connect):
self.conn = mock.Mock()
self.conn.autocommit = False
self.conn.closed = False
self.conn.cursor = mock.Mock()
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_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': 'bar',
'dbname': 'foo'}
self.obj = session.Session(self.URI, pool_max_size=100)
def test_init_sets_uri(self):
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):
self.obj.close()
self.assertNotIn(self.conn,
self.obj._pool_manager._pools[self.obj.pid])
def test_close_unassigns_connection(self):
self.obj.close()
self.assertIsNone(self.obj._conn)
def test_close_unassigns_cursor(self):
self.obj.close()
self.assertIsNone(self.obj._cursor)
def test_connection_property_returns_correct_value(self):
self.assertEqual(self.obj.connection, self.conn)
def test_cursor_property_returns_correct_value(self):
self.assertEqual(self.obj.cursor, self.obj._cursor)
def test_encoding_property_value(self):
self.conn.encoding = 'UTF-8'
self.assertEqual(self.obj.encoding, 'UTF-8')
def test_notices_value(self):
self.conn.notices = [1, 2, 3]
self.assertListEqual(self.obj.notices, [1, 2, 3])
def test_pid_value(self):
expectation = hashlib.md5(
':'.join([self.obj.__class__.__name__,
self.URI]).encode('utf-8')).hexdigest()
self.assertEqual(self.obj.pid, expectation)
def test_query_invokes_cursor_execute(self):
self.obj._cursor.callproc = mock.Mock()
args = ('SELECT * FROM foo', ['bar', 'baz'])
self.obj.query(*args)
self.obj._cursor.execute.assert_called_once_with(*args)
self.conn.set_client_encoding = set_client_encoding = mock.Mock()
self.obj.set_encoding('UTF-8')
self.assertFalse(set_client_encoding.called)
'PYPY does not invoke object.__del__ synchronously')
def test_del_invokes_cleanup(self):
cleanup = mock.Mock()
with mock.patch.multiple('queries.session.Session',
_cleanup=cleanup,
_connect=mock.Mock(),
_get_cursor=mock.Mock(),
_autocommit=mock.Mock()):
obj = session.Session(self.URI)
del obj
cleanup.assert_called_once_with()
def test_exit_invokes_cleanup(self):
cleanup = mock.Mock()
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> Add a __del__ test
I'm worried that this won't work in pypy, so I'm committing to see what travis has to say about the issue.
<DFF> @@ -129,3 +129,14 @@ class SessionTests(unittest.TestCase):
self.conn.set_client_encoding = set_client_encoding = mock.Mock()
self.obj.set_encoding('UTF-8')
self.assertFalse(set_client_encoding.called)
+
+ def test_del_invokes_cleanup(self):
+ cleanup = mock.Mock()
+ with mock.patch.multiple('queries.session.Session',
+ _cleanup=cleanup,
+ _connect=mock.Mock(),
+ _get_cursor=mock.Mock(),
+ _autocommit=mock.Mock()):
+ obj = session.Session(self.URI)
+ del obj
+ cleanup.assert_called_once_with()
| 11 | Add a __del__ test | 0 | .py | py | bsd-3-clause | gmr/queries |
1450 | <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_uuid')
@mock.patch('queries.utils.uri_to_kwargs')
def setUp(self, uri_to_kwargs, register_uuid, register_type, connect):
self.conn = mock.Mock()
self.conn.autocommit = False
self.conn.closed = False
self.conn.cursor = mock.Mock()
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_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': 'bar',
'dbname': 'foo'}
self.obj = session.Session(self.URI, pool_max_size=100)
def test_init_sets_uri(self):
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):
self.obj.close()
self.assertNotIn(self.conn,
self.obj._pool_manager._pools[self.obj.pid])
def test_close_unassigns_connection(self):
self.obj.close()
self.assertIsNone(self.obj._conn)
def test_close_unassigns_cursor(self):
self.obj.close()
self.assertIsNone(self.obj._cursor)
def test_connection_property_returns_correct_value(self):
self.assertEqual(self.obj.connection, self.conn)
def test_cursor_property_returns_correct_value(self):
self.assertEqual(self.obj.cursor, self.obj._cursor)
def test_encoding_property_value(self):
self.conn.encoding = 'UTF-8'
self.assertEqual(self.obj.encoding, 'UTF-8')
def test_notices_value(self):
self.conn.notices = [1, 2, 3]
self.assertListEqual(self.obj.notices, [1, 2, 3])
def test_pid_value(self):
expectation = hashlib.md5(
':'.join([self.obj.__class__.__name__,
self.URI]).encode('utf-8')).hexdigest()
self.assertEqual(self.obj.pid, expectation)
def test_query_invokes_cursor_execute(self):
self.obj._cursor.callproc = mock.Mock()
args = ('SELECT * FROM foo', ['bar', 'baz'])
self.obj.query(*args)
self.obj._cursor.execute.assert_called_once_with(*args)
self.conn.set_client_encoding = set_client_encoding = mock.Mock()
self.obj.set_encoding('UTF-8')
self.assertFalse(set_client_encoding.called)
'PYPY does not invoke object.__del__ synchronously')
def test_del_invokes_cleanup(self):
cleanup = mock.Mock()
with mock.patch.multiple('queries.session.Session',
_cleanup=cleanup,
_connect=mock.Mock(),
_get_cursor=mock.Mock(),
_autocommit=mock.Mock()):
obj = session.Session(self.URI)
del obj
cleanup.assert_called_once_with()
def test_exit_invokes_cleanup(self):
cleanup = mock.Mock()
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> Add a __del__ test
I'm worried that this won't work in pypy, so I'm committing to see what travis has to say about the issue.
<DFF> @@ -129,3 +129,14 @@ class SessionTests(unittest.TestCase):
self.conn.set_client_encoding = set_client_encoding = mock.Mock()
self.obj.set_encoding('UTF-8')
self.assertFalse(set_client_encoding.called)
+
+ def test_del_invokes_cleanup(self):
+ cleanup = mock.Mock()
+ with mock.patch.multiple('queries.session.Session',
+ _cleanup=cleanup,
+ _connect=mock.Mock(),
+ _get_cursor=mock.Mock(),
+ _autocommit=mock.Mock()):
+ obj = session.Session(self.URI)
+ del obj
+ cleanup.assert_called_once_with()
| 11 | Add a __del__ test | 0 | .py | py | bsd-3-clause | gmr/queries |
1451 | <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
: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:
except KeyError:
raise ConnectionNotFoundError(self.id, id(connection))
if self.idle_connections == self.connections.values():
with self._lock:
self.idle_start = time.time()
LOGGER.debug('Pool %s freed 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> Fix a Python3 compatibility issue
<DFF> @@ -170,7 +170,7 @@ class Pool(object):
except KeyError:
raise ConnectionNotFoundError(self.id, id(connection))
- if self.idle_connections == self.connections.values():
+ if self.idle_connections == list(self.connections.values()):
with self._lock:
self.idle_start = time.time()
LOGGER.debug('Pool %s freed connection %s', self.id, id(connection))
| 1 | Fix a Python3 compatibility issue | 1 | .py | py | bsd-3-clause | gmr/queries |
1452 | <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
: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:
except KeyError:
raise ConnectionNotFoundError(self.id, id(connection))
if self.idle_connections == self.connections.values():
with self._lock:
self.idle_start = time.time()
LOGGER.debug('Pool %s freed 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> Fix a Python3 compatibility issue
<DFF> @@ -170,7 +170,7 @@ class Pool(object):
except KeyError:
raise ConnectionNotFoundError(self.id, id(connection))
- if self.idle_connections == self.connections.values():
+ if self.idle_connections == list(self.connections.values()):
with self._lock:
self.idle_start = time.time()
LOGGER.debug('Pool %s freed connection %s', self.id, id(connection))
| 1 | Fix a Python3 compatibility issue | 1 | .py | py | bsd-3-clause | gmr/queries |
1453 | <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| |License|
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)
...
**Using queries.Session.callproc**
This example uses :py:meth:`queries.Session.callproc` to execute a stored
procedure and then pretty-prints the single row results as a dictionary:
.. code:: python
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> Update README
<DFF> @@ -101,7 +101,7 @@ as a context manager to query the database table:
**Using queries.Session.callproc**
-This example uses :py:meth:`queries.Session.callproc` to execute a stored
+This example uses ``queries.Session.callproc`` to execute a stored
procedure and then pretty-prints the single row results as a dictionary:
.. code:: python
| 1 | Update README | 1 | .rst | rst | bsd-3-clause | gmr/queries |
1454 | <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| |License|
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)
...
**Using queries.Session.callproc**
This example uses :py:meth:`queries.Session.callproc` to execute a stored
procedure and then pretty-prints the single row results as a dictionary:
.. code:: python
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> Update README
<DFF> @@ -101,7 +101,7 @@ as a context manager to query the database table:
**Using queries.Session.callproc**
-This example uses :py:meth:`queries.Session.callproc` to execute a stored
+This example uses ``queries.Session.callproc`` to execute a stored
procedure and then pretty-prints the single row results as a dictionary:
.. code:: python
| 1 | Update README | 1 | .rst | rst | bsd-3-clause | gmr/queries |
1455 | <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.0',
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.0',
+ version='1.7.1',
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 |
1456 | <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.0',
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.0',
+ version='1.7.1',
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 |
1457 | <NME> setup.py
<BEF> import os
import platform
import setuptools
# PYPY vs cpython
if platform.python_implementation() == 'PyPy':
else:
install_requires = ['psycopg2']
setup(name='queries',
version='1.2.0',
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> Update setup.py for readthedocs
<DFF> @@ -8,6 +8,9 @@ if target == 'PyPy':
else:
install_requires = ['psycopg2']
+# Install tornado if generating docs on readthedocs
+if os.environ.get('READTHEDOCS', None) == 'True':
+ install_requires.append('tornado')
setup(name='queries',
version='1.2.0',
| 3 | Update setup.py for readthedocs | 0 | .py | py | bsd-3-clause | gmr/queries |
1458 | <NME> setup.py
<BEF> import os
import platform
import setuptools
# PYPY vs cpython
if platform.python_implementation() == 'PyPy':
else:
install_requires = ['psycopg2']
setup(name='queries',
version='1.2.0',
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> Update setup.py for readthedocs
<DFF> @@ -8,6 +8,9 @@ if target == 'PyPy':
else:
install_requires = ['psycopg2']
+# Install tornado if generating docs on readthedocs
+if os.environ.get('READTHEDOCS', None) == 'True':
+ install_requires.append('tornado')
setup(name='queries',
version='1.2.0',
| 3 | Update setup.py for readthedocs | 0 | .py | py | bsd-3-clause | gmr/queries |
1459 | <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
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: pypy
- python: pypy3
- stage: coverage
if: repo = gmr/queries
services: []
python: 3.6
install:
- pip install awscli coverage codecov
script:
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> Add 3.8 to test matrix
<DFF> @@ -35,12 +35,13 @@ jobs:
- python: 3.5
- python: 3.6
- python: 3.7
+ - python: 3.8
- python: pypy
- python: pypy3
- stage: coverage
if: repo = gmr/queries
services: []
- python: 3.6
+ python: 3.7
install:
- pip install awscli coverage codecov
script:
| 2 | Add 3.8 to test matrix | 1 | .yml | travis | bsd-3-clause | gmr/queries |
1460 | <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
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: pypy
- python: pypy3
- stage: coverage
if: repo = gmr/queries
services: []
python: 3.6
install:
- pip install awscli coverage codecov
script:
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> Add 3.8 to test matrix
<DFF> @@ -35,12 +35,13 @@ jobs:
- python: 3.5
- python: 3.6
- python: 3.7
+ - python: 3.8
- python: pypy
- python: pypy3
- stage: coverage
if: repo = gmr/queries
services: []
- python: 3.6
+ python: 3.7
install:
- pip install awscli coverage codecov
script:
| 2 | Add 3.8 to test matrix | 1 | .yml | travis | bsd-3-clause | gmr/queries |
1461 | <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.0',
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
<DFF> @@ -14,7 +14,7 @@ if os.environ.get('READTHEDOCS', None) == 'True':
install_requires.append('tornado')
setup(name='queries',
- version='1.2.0',
+ version='1.2.1',
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 |
1462 | <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.0',
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
<DFF> @@ -14,7 +14,7 @@ if os.environ.get('READTHEDOCS', None) == 'True':
install_requires.append('tornado')
setup(name='queries',
- version='1.2.0',
+ version='1.2.1',
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 |
1463 | <NME> setup.py
<BEF> import os
import platform
# 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':
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',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Database',
'Topic :: Software Development :: Libraries']
setup(name='queries',
version='2.0.0',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
'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> Narrow the psycopg2 pin, bump version
<DFF> @@ -4,9 +4,9 @@ import platform
# PYPY vs cpython
if platform.python_implementation() == 'PyPy':
- install_requires = ['psycopg2cffi>=2.7.2,<3']
+ install_requires = ['psycopg2cffi>=2.7.2,<2.8']
else:
- install_requires = ['psycopg2>=2.5.1,<3']
+ install_requires = ['psycopg2>=2.5.1,<2.8']
# Install tornado if generating docs on readthedocs
if os.environ.get('READTHEDOCS', None) == 'True':
@@ -22,13 +22,14 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Database',
'Topic :: Software Development :: Libraries']
setup(name='queries',
- version='2.0.0',
+ version='2.0.1',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
| 4 | Narrow the psycopg2 pin, bump version | 3 | .py | py | bsd-3-clause | gmr/queries |
1464 | <NME> setup.py
<BEF> import os
import platform
# 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':
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',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Database',
'Topic :: Software Development :: Libraries']
setup(name='queries',
version='2.0.0',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
'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> Narrow the psycopg2 pin, bump version
<DFF> @@ -4,9 +4,9 @@ import platform
# PYPY vs cpython
if platform.python_implementation() == 'PyPy':
- install_requires = ['psycopg2cffi>=2.7.2,<3']
+ install_requires = ['psycopg2cffi>=2.7.2,<2.8']
else:
- install_requires = ['psycopg2>=2.5.1,<3']
+ install_requires = ['psycopg2>=2.5.1,<2.8']
# Install tornado if generating docs on readthedocs
if os.environ.get('READTHEDOCS', None) == 'True':
@@ -22,13 +22,14 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Database',
'Topic :: Software Development :: Libraries']
setup(name='queries',
- version='2.0.0',
+ version='2.0.1',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
| 4 | Narrow the psycopg2 pin, bump version | 3 | .py | py | bsd-3-clause | gmr/queries |
1465 | <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
self._fd = fd
self._freed = False
@gen.coroutine
def free(self):
"""Release the results and connection lock from the TornadoSession
object. This **must** be called after you finish processing the results
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
def __del__(self):
if not self._freed:
LOGGER.warning('%s not freed - %r', self.__class__.__name__, self)
class TornadoSession(session.Session):
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._connections = dict()
self._futures = dict()
self._cursor_factory = cursor_factory
self._ioloop = io_loop or ioloop.IOLoop.instance()
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)
@property
def connection(self):
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)
self._pool_manager.free(self.pid, self._connections[fd])
self._ioloop.remove_handler(fd)
if fd in self._connections:
del self._connections[fd]
if fd in self._futures:
: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> Auto-clean a sessions pool
<DFF> @@ -109,7 +109,6 @@ class Results(results.Results):
self._fd = fd
self._freed = False
- @gen.coroutine
def free(self):
"""Release the results and connection lock from the TornadoSession
object. This **must** be called after you finish processing the results
@@ -124,7 +123,8 @@ class Results(results.Results):
def __del__(self):
if not self._freed:
- LOGGER.warning('%s not freed - %r', self.__class__.__name__, self)
+ LOGGER.warning('Auto-freeing result on deletion')
+ self.free()
class TornadoSession(session.Session):
@@ -162,15 +162,18 @@ 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._ioloop = io_loop or ioloop.IOLoop.instance()
+ 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._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size,
+ self._ioloop.time)
@property
def connection(self):
@@ -438,6 +441,14 @@ class TornadoSession(session.Session):
self._pool_manager.free(self.pid, self._connections[fd])
self._ioloop.remove_handler(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._pool_idle_ttl + 1, self._pool_manager.clean, self.pid)
+
if fd in self._connections:
del self._connections[fd]
if fd in self._futures:
| 15 | Auto-clean a sessions pool | 4 | .py | py | bsd-3-clause | gmr/queries |
1466 | <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
self._fd = fd
self._freed = False
@gen.coroutine
def free(self):
"""Release the results and connection lock from the TornadoSession
object. This **must** be called after you finish processing the results
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
def __del__(self):
if not self._freed:
LOGGER.warning('%s not freed - %r', self.__class__.__name__, self)
class TornadoSession(session.Session):
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._connections = dict()
self._futures = dict()
self._cursor_factory = cursor_factory
self._ioloop = io_loop or ioloop.IOLoop.instance()
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)
@property
def connection(self):
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)
self._pool_manager.free(self.pid, self._connections[fd])
self._ioloop.remove_handler(fd)
if fd in self._connections:
del self._connections[fd]
if fd in self._futures:
: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> Auto-clean a sessions pool
<DFF> @@ -109,7 +109,6 @@ class Results(results.Results):
self._fd = fd
self._freed = False
- @gen.coroutine
def free(self):
"""Release the results and connection lock from the TornadoSession
object. This **must** be called after you finish processing the results
@@ -124,7 +123,8 @@ class Results(results.Results):
def __del__(self):
if not self._freed:
- LOGGER.warning('%s not freed - %r', self.__class__.__name__, self)
+ LOGGER.warning('Auto-freeing result on deletion')
+ self.free()
class TornadoSession(session.Session):
@@ -162,15 +162,18 @@ 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._ioloop = io_loop or ioloop.IOLoop.instance()
+ 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._pool_manager.create(self.pid, pool_idle_ttl, pool_max_size,
+ self._ioloop.time)
@property
def connection(self):
@@ -438,6 +441,14 @@ class TornadoSession(session.Session):
self._pool_manager.free(self.pid, self._connections[fd])
self._ioloop.remove_handler(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._pool_idle_ttl + 1, self._pool_manager.clean, self.pid)
+
if fd in self._connections:
del self._connections[fd]
if fd in self._futures:
| 15 | Auto-clean a sessions pool | 4 | .py | py | bsd-3-clause | gmr/queries |
1467 | <NME> setup.py
<BEF> import os
import platform
import setuptools
# PYPY vs cpython
if target == 'PyPy':
install_requires = ['psycopg2ct']
else:
install_requires = ['psycopg2']
# 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> Set a minimum pin on psycopg2
There is a bug in psycopg2==2.4.5 where it raises a `TypeError` if the
`name` parameter passed to the `connection.cursor` method is None,
despite the fact the default argument is `None`. When queries creates
a new Session it passes `None` to the cursor function and explodes.
This behavior is fixed in versions later than 2.5.1.
<DFF> @@ -7,7 +7,7 @@ target = platform.python_implementation()
if target == 'PyPy':
install_requires = ['psycopg2ct']
else:
- install_requires = ['psycopg2']
+ install_requires = ['psycopg2>=2.5.1']
# Install tornado if generating docs on readthedocs
if os.environ.get('READTHEDOCS', None) == 'True':
| 1 | Set a minimum pin on psycopg2 | 1 | .py | py | bsd-3-clause | gmr/queries |
1468 | <NME> setup.py
<BEF> import os
import platform
import setuptools
# PYPY vs cpython
if target == 'PyPy':
install_requires = ['psycopg2ct']
else:
install_requires = ['psycopg2']
# 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> Set a minimum pin on psycopg2
There is a bug in psycopg2==2.4.5 where it raises a `TypeError` if the
`name` parameter passed to the `connection.cursor` method is None,
despite the fact the default argument is `None`. When queries creates
a new Session it passes `None` to the cursor function and explodes.
This behavior is fixed in versions later than 2.5.1.
<DFF> @@ -7,7 +7,7 @@ target = platform.python_implementation()
if target == 'PyPy':
install_requires = ['psycopg2ct']
else:
- install_requires = ['psycopg2']
+ install_requires = ['psycopg2>=2.5.1']
# Install tornado if generating docs on readthedocs
if os.environ.get('READTHEDOCS', None) == 'True':
| 1 | Set a minimum pin on psycopg2 | 1 | .py | py | bsd-3-clause | gmr/queries |
1469 | <NME> .travis.yml
<BEF> ADDFILE
<MSG> Initial travis-ci configuration
<DFF> @@ -0,0 +1,19 @@
+language: python
+
+python:
+ - 2.6
+ - 2.7
+ - pypy
+ - 3.2
+ - 3.3
+ - 3.4
+
+install:
+ - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install psycopg2ct; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install psycopg2 unittest2; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install psycopg2; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install psycopg2; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install psycopg2; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '3.4' ]]; then pip install psycopg2; fi
+
+script: nosetests
| 19 | Initial travis-ci configuration | 0 | .yml | travis | bsd-3-clause | gmr/queries |
1470 | <NME> .travis.yml
<BEF> ADDFILE
<MSG> Initial travis-ci configuration
<DFF> @@ -0,0 +1,19 @@
+language: python
+
+python:
+ - 2.6
+ - 2.7
+ - pypy
+ - 3.2
+ - 3.3
+ - 3.4
+
+install:
+ - if [[ $TRAVIS_PYTHON_VERSION == 'pypy' ]]; then pip install psycopg2ct; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '2.6' ]]; then pip install psycopg2 unittest2; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '2.7' ]]; then pip install psycopg2; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '3.2' ]]; then pip install psycopg2; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '3.3' ]]; then pip install psycopg2; fi
+ - if [[ $TRAVIS_PYTHON_VERSION == '3.4' ]]; then pip install psycopg2; fi
+
+script: nosetests
| 19 | Initial travis-ci configuration | 0 | .yml | travis | bsd-3-clause | gmr/queries |
1471 | <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 = []
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._futures)
class SessionPublicMethodTests(testing.AsyncTestCase):
_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> Propagate exceptions from PoolManager.add.
<DFF> @@ -175,6 +175,27 @@ class SessionConnectTests(testing.AsyncTestCase):
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):
| 21 | Propagate exceptions from PoolManager.add. | 0 | .py | py | bsd-3-clause | gmr/queries |
1472 | <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 = []
self.obj._exec_cleanup(mock.Mock(), 14)
self.assertNotIn(14, self.obj._futures)
class SessionPublicMethodTests(testing.AsyncTestCase):
_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> Propagate exceptions from PoolManager.add.
<DFF> @@ -175,6 +175,27 @@ class SessionConnectTests(testing.AsyncTestCase):
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):
| 21 | Propagate exceptions from PoolManager.add. | 0 | .py | py | bsd-3-clause | gmr/queries |
1473 | <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
if: tag IS present
services:
- postgres
install:
- pip install awscli
- 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> Fix travis service reference
<DFF> @@ -15,7 +15,7 @@ stages:
if: tag IS present
services:
-- postgres
+- postgresql
install:
- pip install awscli
| 1 | Fix travis service reference | 1 | .yml | travis | bsd-3-clause | gmr/queries |
1474 | <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
if: tag IS present
services:
- postgres
install:
- pip install awscli
- 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> Fix travis service reference
<DFF> @@ -15,7 +15,7 @@ stages:
if: tag IS present
services:
-- postgres
+- postgresql
install:
- pip install awscli
| 1 | Fix travis service reference | 1 | .yml | travis | bsd-3-clause | gmr/queries |
1475 | <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| |License|
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
{'id': 2, 'name': u'Mason'}
{'id': 3, 'name': u'Ethan'}
History
-------
Queries is a fork and enhancement of `pgsql_wrapper <https://pypi.python.org/pypi/pgsql_wrapper`_,
which can be found in the main GitHub repository of Queries as tags prior to version 1.2.0.
.. |Version| image:: https://badge.fury.io/py/queries.svg?
:target: http://badge.fury.io/py/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> Add inspiration note
[ci skip]
<DFF> @@ -79,11 +79,17 @@ Using the Session object as a context manager:
{'id': 2, 'name': u'Mason'}
{'id': 3, 'name': u'Ethan'}
+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 <https://pypi.python.org/pypi/pgsql_wrapper`_,
-which can be found in the main GitHub repository of Queries as tags prior to version 1.2.0.
+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.
+.. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper
.. |Version| image:: https://badge.fury.io/py/queries.svg?
:target: http://badge.fury.io/py/queries
| 8 | Add inspiration note | 2 | .rst | rst | bsd-3-clause | gmr/queries |
1476 | <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| |License|
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
{'id': 2, 'name': u'Mason'}
{'id': 3, 'name': u'Ethan'}
History
-------
Queries is a fork and enhancement of `pgsql_wrapper <https://pypi.python.org/pypi/pgsql_wrapper`_,
which can be found in the main GitHub repository of Queries as tags prior to version 1.2.0.
.. |Version| image:: https://badge.fury.io/py/queries.svg?
:target: http://badge.fury.io/py/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> Add inspiration note
[ci skip]
<DFF> @@ -79,11 +79,17 @@ Using the Session object as a context manager:
{'id': 2, 'name': u'Mason'}
{'id': 3, 'name': u'Ethan'}
+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 <https://pypi.python.org/pypi/pgsql_wrapper`_,
-which can be found in the main GitHub repository of Queries as tags prior to version 1.2.0.
+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.
+.. _pgsql_wrapper: https://pypi.python.org/pypi/pgsql_wrapper
.. |Version| image:: https://badge.fury.io/py/queries.svg?
:target: http://badge.fury.io/py/queries
| 8 | Add inspiration note | 2 | .rst | rst | bsd-3-clause | gmr/queries |
1477 | <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)
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:
# Create a new cleanup callback to clean the pool of idle connections
self._cleanup_callback = self._ioloop.add_timeout(
self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid)
if fd in self._connections:
del self._connections[fd]
: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> IOLoop.add_timeout uses an absolute/epoch time.
<DFF> @@ -447,7 +447,8 @@ class TornadoSession(session.Session):
# Create a new cleanup callback to clean the pool of idle connections
self._cleanup_callback = self._ioloop.add_timeout(
- self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid)
+ self._ioloop.time() + self._pool_idle_ttl + 1,
+ self._pool_manager.clean, self.pid)
if fd in self._connections:
del self._connections[fd]
| 2 | IOLoop.add_timeout uses an absolute/epoch time. | 1 | .py | py | bsd-3-clause | gmr/queries |
1478 | <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)
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:
# Create a new cleanup callback to clean the pool of idle connections
self._cleanup_callback = self._ioloop.add_timeout(
self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid)
if fd in self._connections:
del self._connections[fd]
: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> IOLoop.add_timeout uses an absolute/epoch time.
<DFF> @@ -447,7 +447,8 @@ class TornadoSession(session.Session):
# Create a new cleanup callback to clean the pool of idle connections
self._cleanup_callback = self._ioloop.add_timeout(
- self._pool_idle_ttl + 1, self._pool_manager.clean, self.pid)
+ self._ioloop.time() + self._pool_idle_ttl + 1,
+ self._pool_manager.clean, self.pid)
if fd in self._connections:
del self._connections[fd]
| 2 | IOLoop.add_timeout uses an absolute/epoch time. | 1 | .py | py | bsd-3-clause | gmr/queries |
1479 | <NME> session.py
<BEF> """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` connection and cursor objects to
provide ultimate flexibility in how you use the 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 Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
: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
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""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
"""
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._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit(autocommit)
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.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
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.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
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self, autocommit):
if self._conn:
try:
self._pool_manager.free(self.pid, self._conn)
except (pool.ConnectionNotFoundError, KeyError):
pass
self._conn = None
try:
self._pool_manager.clean(self.pid)
except KeyError:
pass
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
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
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct 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.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
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
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Free a connection prior to trying to remove it
Remove exception edge cases that shouldnt be needed
<DFF> @@ -137,6 +137,7 @@ class Session(object):
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
+ self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
@@ -255,14 +256,11 @@ class Session(object):
if self._conn:
try:
self._pool_manager.free(self.pid, self._conn)
- except (pool.ConnectionNotFoundError, KeyError):
+ except pool.ConnectionNotFoundError:
pass
self._conn = None
- try:
- self._pool_manager.clean(self.pid)
- except KeyError:
- pass
+ self._pool_manager.clean(self.pid)
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
| 3 | Free a connection prior to trying to remove it | 5 | .py | py | bsd-3-clause | gmr/queries |
1480 | <NME> session.py
<BEF> """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` connection and cursor objects to
provide ultimate flexibility in how you use the 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 Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
: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
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""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
"""
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._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit(autocommit)
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.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
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.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
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self, autocommit):
if self._conn:
try:
self._pool_manager.free(self.pid, self._conn)
except (pool.ConnectionNotFoundError, KeyError):
pass
self._conn = None
try:
self._pool_manager.clean(self.pid)
except KeyError:
pass
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
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
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct 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.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
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
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Free a connection prior to trying to remove it
Remove exception edge cases that shouldnt be needed
<DFF> @@ -137,6 +137,7 @@ class Session(object):
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
+ self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
@@ -255,14 +256,11 @@ class Session(object):
if self._conn:
try:
self._pool_manager.free(self.pid, self._conn)
- except (pool.ConnectionNotFoundError, KeyError):
+ except pool.ConnectionNotFoundError:
pass
self._conn = None
- try:
- self._pool_manager.clean(self.pid)
- except KeyError:
- pass
+ self._pool_manager.clean(self.pid)
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
| 3 | Free a connection prior to trying to remove it | 5 | .py | py | bsd-3-clause | gmr/queries |
1481 | <NME> session.py
<BEF> """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` connection and cursor objects to
provide ultimate flexibility in how you use the 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 Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
: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
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""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
"""
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._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit(autocommit)
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.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
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
LOGGER.info('Closing connection %r in %s', self._conn, self.pid)
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.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
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
@property
def status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit or not after every query
:param autocommit: Boolean (Default - True)
"""
self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
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
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct 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.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Make Session.status private (Session._status)
<DFF> @@ -216,23 +216,6 @@ class Session(object):
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
- @property
- def status(self):
- """Return the current connection status as an integer value.
-
- The status should match one of the following constants:
-
- - queries.Session.INTRANS: Connection established, in transaction
- - queries.Session.PREPARED: Prepared for second phase of transaction
- - queries.Session.READY: Connected, no active transaction
-
- :rtype: int
-
- """
- if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
- return self.READY
- return self._conn.status
-
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
@@ -347,3 +330,20 @@ class Session(object):
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
+
+ @property
+ def _status(self):
+ """Return the current connection status as an integer value.
+
+ The status should match one of the following constants:
+
+ - queries.Session.INTRANS: Connection established, in transaction
+ - queries.Session.PREPARED: Prepared for second phase of transaction
+ - queries.Session.READY: Connected, no active transaction
+
+ :rtype: int
+
+ """
+ if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
+ return self.READY
+ return self._conn.status
\ No newline at end of file
| 17 | Make Session.status private (Session._status) | 17 | .py | py | bsd-3-clause | gmr/queries |
1482 | <NME> session.py
<BEF> """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` connection and cursor objects to
provide ultimate flexibility in how you use the 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 Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
: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
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""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
"""
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._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit(autocommit)
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.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
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
LOGGER.info('Closing connection %r in %s', self._conn, self.pid)
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.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
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
@property
def status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit or not after every query
:param autocommit: Boolean (Default - True)
"""
self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
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
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct 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.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Make Session.status private (Session._status)
<DFF> @@ -216,23 +216,6 @@ class Session(object):
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
- @property
- def status(self):
- """Return the current connection status as an integer value.
-
- The status should match one of the following constants:
-
- - queries.Session.INTRANS: Connection established, in transaction
- - queries.Session.PREPARED: Prepared for second phase of transaction
- - queries.Session.READY: Connected, no active transaction
-
- :rtype: int
-
- """
- if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
- return self.READY
- return self._conn.status
-
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
@@ -347,3 +330,20 @@ class Session(object):
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
+
+ @property
+ def _status(self):
+ """Return the current connection status as an integer value.
+
+ The status should match one of the following constants:
+
+ - queries.Session.INTRANS: Connection established, in transaction
+ - queries.Session.PREPARED: Prepared for second phase of transaction
+ - queries.Session.READY: Connected, no active transaction
+
+ :rtype: int
+
+ """
+ if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
+ return self.READY
+ return self._conn.status
\ No newline at end of file
| 17 | Make Session.status private (Session._status) | 17 | .py | py | bsd-3-clause | gmr/queries |
1483 | <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'
as a list. If no results are returned, the method will return None
instead.
Example:
.. code:: python
data = yield session.callproc('char', [65])
:param str name: The stored procedure name
:param list args: An optional list of procedure arguments
:rtype: list | None
"""
# Grab a connection, either new or out of the pool
"""
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
"""Listen for notifications from PostgreSQL on the specified channel,
passing in a callback to receive the notifications.
Example:
.. code:: python
class ListenHandler(web.RequestHandler):
def initialize(self):
self.channel = 'example'
self.session = queries.TornadoSession()
@gen.coroutine
def get(self, *args, **kwargs):
yield self.session.listen(self.channel,
self.on_notification)
self.finish()
def on_connection_close(self):
if self.channel:
self.session.unlisten(self.channel)
self.channel = None
@gen.coroutine
def on_notification(self, channel, pid, payload):
self.write('Payload: %s\\n' % payload)
yield gen.Task(self.flush)
:param str channel: The channel to stop listening on
:param method callback: The method to call on each notification
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):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results as list.
Example:
.. code:: python
data = yield session.query('SELECT * FROM foo WHERE bar=%(bar)s',
{'bar': 'baz'}):
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: list
"""
# Grab a connection, either new or out of the pool
: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)
@gen.coroutine
def unlisten(self, channel):
"""Cancel a listening on a channel.
Example:
.. code:: python
yield self.session.unlisten('channel-name')
:param str channel: The channel to stop listening on
: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()
LOGGER.debug('Error')
self._ioloop.remove_handler(fd)
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
: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> Additional document updates
<DFF> @@ -86,15 +86,9 @@ class TornadoSession(session.Session):
as a list. If no results are returned, the method will return None
instead.
- Example:
-
- .. code:: python
-
- data = yield session.callproc('char', [65])
-
:param str name: The stored procedure name
:param list args: An optional list of procedure arguments
- :rtype: list | None
+ :rtype: list or None
"""
# Grab a connection, either new or out of the pool
@@ -141,32 +135,6 @@ class TornadoSession(session.Session):
"""Listen for notifications from PostgreSQL on the specified channel,
passing in a callback to receive the notifications.
- Example:
-
- .. code:: python
-
- class ListenHandler(web.RequestHandler):
-
- def initialize(self):
- self.channel = 'example'
- self.session = queries.TornadoSession()
-
- @gen.coroutine
- def get(self, *args, **kwargs):
- yield self.session.listen(self.channel,
- self.on_notification)
- self.finish()
-
- def on_connection_close(self):
- if self.channel:
- self.session.unlisten(self.channel)
- self.channel = None
-
- @gen.coroutine
- def on_notification(self, channel, pid, payload):
- self.write('Payload: %s\\n' % payload)
- yield gen.Task(self.flush)
-
:param str channel: The channel to stop listening on
:param method callback: The method to call on each notification
@@ -216,16 +184,9 @@ class TornadoSession(session.Session):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results as list.
- Example:
-
- .. code:: python
-
- data = yield session.query('SELECT * FROM foo WHERE bar=%(bar)s',
- {'bar': 'baz'}):
-
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
- :rtype: list
+ :rtype: list or None
"""
# Grab a connection, either new or out of the pool
@@ -269,13 +230,8 @@ class TornadoSession(session.Session):
@gen.coroutine
def unlisten(self, channel):
- """Cancel a listening on a channel.
-
- Example:
-
- .. code:: python
-
- yield self.session.unlisten('channel-name')
+ """Cancel a listening to notifications on a PostgreSQL notification
+ channel.
:param str channel: The channel to stop listening on
@@ -375,6 +331,26 @@ class TornadoSession(session.Session):
LOGGER.debug('Error')
self._ioloop.remove_handler(fd)
+ @property
+ def connection(self):
+ """The connection property is not supported in
+ :py:class:`~queries.TornadoSession`.
+
+ :rtype: None
+
+ """
+ return None
+
+ @property
+ def cursor(self):
+ """The cursor property is not supported in
+ :py:class:`~queries.TornadoSession`.
+
+ :rtype: None
+
+ """
+ return None
+
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
| 24 | Additional document updates | 48 | .py | py | bsd-3-clause | gmr/queries |
1484 | <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'
as a list. If no results are returned, the method will return None
instead.
Example:
.. code:: python
data = yield session.callproc('char', [65])
:param str name: The stored procedure name
:param list args: An optional list of procedure arguments
:rtype: list | None
"""
# Grab a connection, either new or out of the pool
"""
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
"""Listen for notifications from PostgreSQL on the specified channel,
passing in a callback to receive the notifications.
Example:
.. code:: python
class ListenHandler(web.RequestHandler):
def initialize(self):
self.channel = 'example'
self.session = queries.TornadoSession()
@gen.coroutine
def get(self, *args, **kwargs):
yield self.session.listen(self.channel,
self.on_notification)
self.finish()
def on_connection_close(self):
if self.channel:
self.session.unlisten(self.channel)
self.channel = None
@gen.coroutine
def on_notification(self, channel, pid, payload):
self.write('Payload: %s\\n' % payload)
yield gen.Task(self.flush)
:param str channel: The channel to stop listening on
:param method callback: The method to call on each notification
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):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results as list.
Example:
.. code:: python
data = yield session.query('SELECT * FROM foo WHERE bar=%(bar)s',
{'bar': 'baz'}):
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: list
"""
# Grab a connection, either new or out of the pool
: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)
@gen.coroutine
def unlisten(self, channel):
"""Cancel a listening on a channel.
Example:
.. code:: python
yield self.session.unlisten('channel-name')
:param str channel: The channel to stop listening on
: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()
LOGGER.debug('Error')
self._ioloop.remove_handler(fd)
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
: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> Additional document updates
<DFF> @@ -86,15 +86,9 @@ class TornadoSession(session.Session):
as a list. If no results are returned, the method will return None
instead.
- Example:
-
- .. code:: python
-
- data = yield session.callproc('char', [65])
-
:param str name: The stored procedure name
:param list args: An optional list of procedure arguments
- :rtype: list | None
+ :rtype: list or None
"""
# Grab a connection, either new or out of the pool
@@ -141,32 +135,6 @@ class TornadoSession(session.Session):
"""Listen for notifications from PostgreSQL on the specified channel,
passing in a callback to receive the notifications.
- Example:
-
- .. code:: python
-
- class ListenHandler(web.RequestHandler):
-
- def initialize(self):
- self.channel = 'example'
- self.session = queries.TornadoSession()
-
- @gen.coroutine
- def get(self, *args, **kwargs):
- yield self.session.listen(self.channel,
- self.on_notification)
- self.finish()
-
- def on_connection_close(self):
- if self.channel:
- self.session.unlisten(self.channel)
- self.channel = None
-
- @gen.coroutine
- def on_notification(self, channel, pid, payload):
- self.write('Payload: %s\\n' % payload)
- yield gen.Task(self.flush)
-
:param str channel: The channel to stop listening on
:param method callback: The method to call on each notification
@@ -216,16 +184,9 @@ class TornadoSession(session.Session):
"""Issue a query asynchronously on the server, mogrifying the
parameters against the sql statement and yielding the results as list.
- Example:
-
- .. code:: python
-
- data = yield session.query('SELECT * FROM foo WHERE bar=%(bar)s',
- {'bar': 'baz'}):
-
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
- :rtype: list
+ :rtype: list or None
"""
# Grab a connection, either new or out of the pool
@@ -269,13 +230,8 @@ class TornadoSession(session.Session):
@gen.coroutine
def unlisten(self, channel):
- """Cancel a listening on a channel.
-
- Example:
-
- .. code:: python
-
- yield self.session.unlisten('channel-name')
+ """Cancel a listening to notifications on a PostgreSQL notification
+ channel.
:param str channel: The channel to stop listening on
@@ -375,6 +331,26 @@ class TornadoSession(session.Session):
LOGGER.debug('Error')
self._ioloop.remove_handler(fd)
+ @property
+ def connection(self):
+ """The connection property is not supported in
+ :py:class:`~queries.TornadoSession`.
+
+ :rtype: None
+
+ """
+ return None
+
+ @property
+ def cursor(self):
+ """The cursor property is not supported in
+ :py:class:`~queries.TornadoSession`.
+
+ :rtype: None
+
+ """
+ return None
+
def _psycopg2_connect(self, kwargs):
"""Return a psycopg2 connection for the specified kwargs. Extend for
use in async session adapters.
| 24 | Additional document updates | 48 | .py | py | bsd-3-clause | gmr/queries |
1485 | <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
import psycopg2
from queries import pool
from queries import session
from queries import DEFAULT_URI
LOGGER = logging.getLogger(__name__)
class TornadoSession(session.Session):
"""Session class for Tornado asynchronous applications. Uses
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
:py:meth:`cursor.fetchall`.
:param str uri: PostgreSQL connection URI
:param psycopg2.cursor: The cursor type to use
:param bool use_pool: Use the connection pool
:param int max_pool_size: Maximum number of connections for a single URI
"""
def __init__(self,
uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
use_pool=True,
max_pool_size=pool.MAX_SIZE):
"""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 bool use_pool: Use the connection pool
:param int max_pool_size: Max number of connections for a single URI
"""
self._callbacks = dict()
self._listeners = dict()
self._connections = dict()
self._commands = dict()
self._cursor_factory = cursor_factory
self._exceptions = dict()
self._ioloop = ioloop.IOLoop.instance()
self._uri = uri
self._use_pool = use_pool
@gen.coroutine
def callproc(self, name, args=None):
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()
:raises: queries.ProgrammingError
"""
# Grab a connection, either new or out of the pool
connection, fd, status = self._connect()
# Add a callback for either connecting or waiting for the query
self._callbacks[fd] = yield gen.Callback((self, fd))
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(), self._on_io_events,
ioloop.IOLoop.WRITE)
# Maybe wait for the connection
if status == self.SETUP and connection.poll() != extensions.POLL_OK:
yield gen.Wait((self, fd))
# Setup the callback for the actual query
self._callbacks[fd] = yield gen.Callback((self, fd))
# Get the cursor, execute the query and wait for the result
cursor = self._get_cursor(connection)
cursor.callproc(name, args)
yield gen.Wait((self, fd))
# If there was an exception, cleanup, then raise it
if fd in self._exceptions and self._exceptions[fd]:
error = self._exceptions[fd]
self._exec_cleanup(cursor, fd)
raise error
# Attempt to get any result that's pending for the query
try:
result = cursor.fetchall()
except psycopg2.ProgrammingError:
result = []
# Close the cursor and cleanup the references for this request
self._exec_cleanup(cursor, fd)
# Return the result if there are any
raise gen.Return(result)
@gen.coroutine
def listen(self, channel, callback):
: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 method callback: The method to call on each notification
"""
# Grab a connection, either new or out of the pool
connection, fd, status = self._connect()
# Add a callback for either connecting or waiting for the query
self._callbacks[fd] = yield gen.Callback((self, fd))
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(), self._on_io_events,
ioloop.IOLoop.WRITE)
# Maybe wait for the connection
if status == self.SETUP and connection.poll() != extensions.POLL_OK:
yield gen.Wait((self, fd))
# Setup the callback for the actual query
self._callbacks[fd] = yield gen.Callback((self, fd))
# Get the cursor
cursor = self._get_cursor(connection)
# Add the channel and callback to the class level listeners
self._listeners[channel] = (fd, cursor)
# Send the LISTEN to PostgreSQL
cursor.execute("LISTEN %s" % channel)
self._ensure_pool_exists()
while channel in self._listeners and self._listeners[channel]:
# Wait for an event on that FD
yield gen.Wait((self, fd))
# Iterate through all of the notifications
while connection.notifies:
notify = connection.notifies.pop()
callback(channel, notify.pid, notify.payload)
# Set a new callback for the fd if we're not exiting
if channel in self._listeners:
self._callbacks[fd] = yield gen.Callback((self, fd))
@gen.coroutine
def query(self, sql, parameters=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.ProgrammingError
"""
# Grab a connection, either new or out of the pool
connection, fd, status = self._connect()
# Add a callback for either connecting or waiting for the query
self._callbacks[fd] = yield gen.Callback((self, fd))
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(), self._on_io_events,
ioloop.IOLoop.WRITE)
# Maybe wait for the connection
if status == self.SETUP and connection.poll() != extensions.POLL_OK:
yield gen.Wait((self, fd))
# Setup the callback for the actual query
self._callbacks[fd] = yield gen.Callback((self, fd))
# Get the cursor, execute the query and wait for the result
cursor = self._get_cursor(connection)
cursor.execute(sql, parameters)
yield gen.Wait((self, fd))
# If there was an exception, cleanup, then raise it
if fd in self._exceptions and self._exceptions[fd]:
error = self._exceptions[fd]
self._exec_cleanup(cursor, fd)
raise error
# Carry the row count to return to the caller
row_count = cursor.rowcount
# Attempt to get any result that's pending for the query
try:
result = cursor.fetchall()
except psycopg2.ProgrammingError:
result = []
# Close the cursor and cleanup the references for this request
self._exec_cleanup(cursor, fd)
# Return the result if there are any
raise gen.Return((row_count, result))
@gen.coroutine
def unlisten(self, channel):
: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)
# Close the cursor and cleanup the references for this request
self._exec_cleanup(cursor, fd)
def _connect(self):
"""Connect to PostgreSQL and setup a few variables and data structures
to reduce code in the coroutine methods.
:return tuple: psycopg2.extensions.connection, int, int
"""
connection = super(TornadoSession, self)._connect()
fd, status = connection.fileno(), connection.status
# Add the connection for use in _poll_connection
self._connections[fd] = connection
return connection, fd, status
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.
# connection in a weird state: consts.STATUS_DATESTYLE,
# returning from Connection._setup without setting the state
# as const.STATUS_OK
"""
cursor.close()
if fd in self._exceptions:
del self._exceptions[fd]
if fd in self._callbacks:
del self._callbacks[fd]
if fd in self._connections:
del self._connections[fd]
self._ioloop.remove_handler(fd)
def _get_cursor(self, connection):
"""Return a cursor for the given connection.
:param psycopg2.extensions.connection connection: The connection to use
:rtype: psycopg2.extensions.cursor
"""
return connection.cursor(cursor_factory=self._cursor_factory)
@gen.coroutine
def _on_io_events(self, fd=None, events=None):
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> Refactor WIP commit, will break tests, just saying.
- Refactor pooling internals considerably
- New Results object for returning results from query and callproc
- Refactor Session and TornadoSession to use Results and new pooling behaviors
<DFF> @@ -28,11 +28,29 @@ from tornado import stack_context
import psycopg2
from queries import pool
+from queries import results
from queries import session
+from queries import utils
from queries import DEFAULT_URI
+from queries import PYPY
LOGGER = logging.getLogger(__name__)
+class Results(results.Results):
+ """Class that is created for each query that allows for the use of query
+ results...
+
+ """
+ def __init__(self, cursor, cleanup, fd):
+ self.cursor = cursor
+ self._cleanup = cleanup
+ self._fd = fd
+
+ @gen.coroutine
+ def release(self):
+ yield self._cleanup(self.cursor, self._fd)
+
+
class TornadoSession(session.Session):
"""Session class for Tornado asynchronous applications. Uses
@@ -50,34 +68,37 @@ class TornadoSession(session.Session):
:py:meth:`cursor.fetchall`.
:param str uri: PostgreSQL connection URI
- :param psycopg2.cursor: The cursor type to use
- :param bool use_pool: Use the connection pool
- :param int max_pool_size: Maximum number of connections for a single 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=DEFAULT_URI,
+ def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
- use_pool=True,
- max_pool_size=pool.MAX_SIZE):
+ pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
+ pool_max_size=pool.DEFAULT_MAX_SIZE):
"""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 bool use_pool: Use the connection pool
- :param int max_pool_size: Max number of connections for a single URI
+ :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
"""
self._callbacks = dict()
- self._listeners = dict()
self._connections = dict()
- self._commands = dict()
- self._cursor_factory = cursor_factory
self._exceptions = dict()
+ self._listeners = dict()
+
+ self._cursor_factory = cursor_factory
self._ioloop = ioloop.IOLoop.instance()
+ self._pool_manager = pool.PoolManager.instance()
self._uri = uri
- self._use_pool = use_pool
+
+ # 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)
@gen.coroutine
def callproc(self, name, args=None):
@@ -98,44 +119,27 @@ class TornadoSession(session.Session):
:raises: queries.ProgrammingError
"""
- # Grab a connection, either new or out of the pool
- connection, fd, status = self._connect()
+ conn = yield self._connect()
- # Add a callback for either connecting or waiting for the query
- self._callbacks[fd] = yield gen.Callback((self, fd))
-
- # Add the connection to the IOLoop
- self._ioloop.add_handler(connection.fileno(), self._on_io_events,
- ioloop.IOLoop.WRITE)
-
- # Maybe wait for the connection
- if status == self.SETUP and connection.poll() != extensions.POLL_OK:
- yield gen.Wait((self, fd))
- # Setup the callback for the actual query
- self._callbacks[fd] = yield gen.Callback((self, fd))
+ # Setup a callback to wait on the query result
+ self._callbacks[conn.fileno()] = yield gen.Callback((self,
+ conn.fileno()))
# Get the cursor, execute the query and wait for the result
- cursor = self._get_cursor(connection)
+ cursor = self._get_cursor(conn)
cursor.callproc(name, args)
- yield gen.Wait((self, fd))
+ yield gen.Wait((self, conn.fileno()))
# If there was an exception, cleanup, then raise it
- if fd in self._exceptions and self._exceptions[fd]:
- error = self._exceptions[fd]
- self._exec_cleanup(cursor, fd)
+ if (conn.fileno() in self._exceptions and
+ self._exceptions[conn.fileno()]):
+ error = self._exceptions[conn.fileno()]
+ self._exec_cleanup(cursor, conn.fileno())
raise error
- # Attempt to get any result that's pending for the query
- try:
- result = cursor.fetchall()
- except psycopg2.ProgrammingError:
- result = []
-
- # Close the cursor and cleanup the references for this request
- self._exec_cleanup(cursor, fd)
-
# Return the result if there are any
- raise gen.Return(result)
+ cleanup = yield gen.Callback((self, self._exec_cleanup))
+ raise gen.Return(Results(cursor, cleanup, conn.fileno()))
@gen.coroutine
def listen(self, channel, callback):
@@ -146,27 +150,13 @@ class TornadoSession(session.Session):
:param method callback: The method to call on each notification
"""
- # Grab a connection, either new or out of the pool
- connection, fd, status = self._connect()
-
- # Add a callback for either connecting or waiting for the query
- self._callbacks[fd] = yield gen.Callback((self, fd))
-
- # Add the connection to the IOLoop
- self._ioloop.add_handler(connection.fileno(), self._on_io_events,
- ioloop.IOLoop.WRITE)
-
- # Maybe wait for the connection
- if status == self.SETUP and connection.poll() != extensions.POLL_OK:
- yield gen.Wait((self, fd))
- # Setup the callback for the actual query
- self._callbacks[fd] = yield gen.Callback((self, fd))
+ conn = yield self._connect()
# Get the cursor
- cursor = self._get_cursor(connection)
+ cursor = self._get_cursor(conn)
# Add the channel and callback to the class level listeners
- self._listeners[channel] = (fd, cursor)
+ self._listeners[channel] = (conn.fileno(), cursor)
# Send the LISTEN to PostgreSQL
cursor.execute("LISTEN %s" % channel)
@@ -175,16 +165,17 @@ class TornadoSession(session.Session):
while channel in self._listeners and self._listeners[channel]:
# Wait for an event on that FD
- yield gen.Wait((self, fd))
+ yield gen.Wait((self, conn.fileno()))
# Iterate through all of the notifications
- while connection.notifies:
- notify = connection.notifies.pop()
+ while conn.notifies:
+ notify = conn.notifies.pop()
callback(channel, notify.pid, notify.payload)
# Set a new callback for the fd if we're not exiting
if channel in self._listeners:
- self._callbacks[fd] = yield gen.Callback((self, fd))
+ self._callbacks[conn.fileno()] = \
+ yield gen.Callback((self, conn.fileno()))
@gen.coroutine
def query(self, sql, parameters=None):
@@ -205,47 +196,27 @@ class TornadoSession(session.Session):
:raises: queries.ProgrammingError
"""
- # Grab a connection, either new or out of the pool
- connection, fd, status = self._connect()
-
- # Add a callback for either connecting or waiting for the query
- self._callbacks[fd] = yield gen.Callback((self, fd))
-
- # Add the connection to the IOLoop
- self._ioloop.add_handler(connection.fileno(), self._on_io_events,
- ioloop.IOLoop.WRITE)
+ conn = yield self._connect()
- # Maybe wait for the connection
- if status == self.SETUP and connection.poll() != extensions.POLL_OK:
- yield gen.Wait((self, fd))
- # Setup the callback for the actual query
- self._callbacks[fd] = yield gen.Callback((self, fd))
+ # Setup a callback to wait on the query result
+ self._callbacks[conn.fileno()] = yield gen.Callback((self,
+ conn.fileno()))
# Get the cursor, execute the query and wait for the result
- cursor = self._get_cursor(connection)
+ cursor = self._get_cursor(conn)
cursor.execute(sql, parameters)
- yield gen.Wait((self, fd))
+ yield gen.Wait((self, conn.fileno()))
+ del self._callbacks[conn.fileno()]
# If there was an exception, cleanup, then raise it
- if fd in self._exceptions and self._exceptions[fd]:
- error = self._exceptions[fd]
- self._exec_cleanup(cursor, fd)
+ if (conn.fileno() in self._exceptions and
+ self._exceptions[conn.fileno()]):
+ error = self._exceptions[conn.fileno()]
+ self._exec_cleanup(cursor, conn.fileno())
raise error
- # Carry the row count to return to the caller
- row_count = cursor.rowcount
-
- # Attempt to get any result that's pending for the query
- try:
- result = cursor.fetchall()
- except psycopg2.ProgrammingError:
- result = []
-
- # Close the cursor and cleanup the references for this request
- self._exec_cleanup(cursor, fd)
-
# Return the result if there are any
- raise gen.Return((row_count, result))
+ raise gen.Return(Results(cursor, self._exec_cleanup, conn.fileno()))
@gen.coroutine
def unlisten(self, channel):
@@ -273,21 +244,72 @@ class TornadoSession(session.Session):
# Close the cursor and cleanup the references for this request
self._exec_cleanup(cursor, fd)
+ @gen.coroutine
def _connect(self):
- """Connect to PostgreSQL and setup a few variables and data structures
- to reduce code in the coroutine methods.
+ """Connect to PostgreSQL, either by reusing a connection from the pool
+ if possible, or by creating the new connection.
- :return tuple: psycopg2.extensions.connection, int, int
+ :rtype: psycopg2.extensions.connection
+ :raises: pool.NoIdleConnectionsError
"""
- connection = super(TornadoSession, self)._connect()
- fd, status = connection.fileno(), connection.status
+ # Attempt to get a cached connection from the connection pool
+ try:
+ connection = self._pool_manager.get(self.pid, self)
+
+ self._connections[connection.fileno()] = connection
+ self._callbacks[connection.fileno()] = None
+ self._exceptions[connection.fileno()] = None
+
+ # Add the connection to the IOLoop
+ self._ioloop.add_handler(connection.fileno(), self._on_io_events,
+ ioloop.IOLoop.WRITE)
+
+ except pool.NoIdleConnectionsError:
+ # "Block" while the pool is full
+ while self._pool_manager.is_full(self.pid):
+ LOGGER.warning('Pool %s is full, waiting 100ms', self.pid)
+ timeout = yield gen.Callback((self, 'connect'))
+ self._ioloop.add_timeout(100, timeout)
+ yield gen.Wait((self, 'connect'))
+
+ # Create a new PostgreSQL connection
+ kwargs = utils.uri_to_kwargs(self._uri)
+ connection = self._psycopg2_connect(kwargs)
+ fd = connection.fileno()
+
+ # Add the connection for use in _poll_connection
+ self._connections[fd] = connection
+ self._exceptions[fd] = None
+
+ # Add a callback for either connecting or waiting for the query
+ self._callbacks[fd] = yield gen.Callback((self, fd))
+
+ # Add the connection to the IOLoop
+ self._ioloop.add_handler(connection.fileno(), self._on_io_events,
+ ioloop.IOLoop.WRITE)
+
+ # Wait for the connection
+ yield gen.Wait((self, fd))
+ del self._callbacks[fd]
+
+ # Add the connection to the pool
+ self._pool_manager.add(self.pid, connection)
+ self._pool_manager.lock(self.pid, connection, self)
- # Add the connection for use in _poll_connection
- self._connections[fd] = connection
+ # Added in because psycopg2ct 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 PYPY:
+ connection.reset()
- return connection, fd, status
+ # Register the custom data types
+ self._register_unicode(connection)
+ self._register_uuid(connection)
+ raise gen.Return(connection)
+
+ @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.
@@ -297,22 +319,17 @@ class TornadoSession(session.Session):
"""
cursor.close()
+ self._pool_manager.free(self.pid, self._connections[fd])
+
if fd in self._exceptions:
del self._exceptions[fd]
if fd in self._callbacks:
del self._callbacks[fd]
if fd in self._connections:
del self._connections[fd]
- self._ioloop.remove_handler(fd)
-
- def _get_cursor(self, connection):
- """Return a cursor for the given connection.
- :param psycopg2.extensions.connection connection: The connection to use
- :rtype: psycopg2.extensions.cursor
-
- """
- return connection.cursor(cursor_factory=self._cursor_factory)
+ self._ioloop.remove_handler(fd)
+ raise gen.Return()
@gen.coroutine
def _on_io_events(self, fd=None, events=None):
| 129 | Refactor WIP commit, will break tests, just saying. | 112 | .py | py | bsd-3-clause | gmr/queries |
1486 | <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
import psycopg2
from queries import pool
from queries import session
from queries import DEFAULT_URI
LOGGER = logging.getLogger(__name__)
class TornadoSession(session.Session):
"""Session class for Tornado asynchronous applications. Uses
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
:py:meth:`cursor.fetchall`.
:param str uri: PostgreSQL connection URI
:param psycopg2.cursor: The cursor type to use
:param bool use_pool: Use the connection pool
:param int max_pool_size: Maximum number of connections for a single URI
"""
def __init__(self,
uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
use_pool=True,
max_pool_size=pool.MAX_SIZE):
"""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 bool use_pool: Use the connection pool
:param int max_pool_size: Max number of connections for a single URI
"""
self._callbacks = dict()
self._listeners = dict()
self._connections = dict()
self._commands = dict()
self._cursor_factory = cursor_factory
self._exceptions = dict()
self._ioloop = ioloop.IOLoop.instance()
self._uri = uri
self._use_pool = use_pool
@gen.coroutine
def callproc(self, name, args=None):
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()
:raises: queries.ProgrammingError
"""
# Grab a connection, either new or out of the pool
connection, fd, status = self._connect()
# Add a callback for either connecting or waiting for the query
self._callbacks[fd] = yield gen.Callback((self, fd))
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(), self._on_io_events,
ioloop.IOLoop.WRITE)
# Maybe wait for the connection
if status == self.SETUP and connection.poll() != extensions.POLL_OK:
yield gen.Wait((self, fd))
# Setup the callback for the actual query
self._callbacks[fd] = yield gen.Callback((self, fd))
# Get the cursor, execute the query and wait for the result
cursor = self._get_cursor(connection)
cursor.callproc(name, args)
yield gen.Wait((self, fd))
# If there was an exception, cleanup, then raise it
if fd in self._exceptions and self._exceptions[fd]:
error = self._exceptions[fd]
self._exec_cleanup(cursor, fd)
raise error
# Attempt to get any result that's pending for the query
try:
result = cursor.fetchall()
except psycopg2.ProgrammingError:
result = []
# Close the cursor and cleanup the references for this request
self._exec_cleanup(cursor, fd)
# Return the result if there are any
raise gen.Return(result)
@gen.coroutine
def listen(self, channel, callback):
: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 method callback: The method to call on each notification
"""
# Grab a connection, either new or out of the pool
connection, fd, status = self._connect()
# Add a callback for either connecting or waiting for the query
self._callbacks[fd] = yield gen.Callback((self, fd))
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(), self._on_io_events,
ioloop.IOLoop.WRITE)
# Maybe wait for the connection
if status == self.SETUP and connection.poll() != extensions.POLL_OK:
yield gen.Wait((self, fd))
# Setup the callback for the actual query
self._callbacks[fd] = yield gen.Callback((self, fd))
# Get the cursor
cursor = self._get_cursor(connection)
# Add the channel and callback to the class level listeners
self._listeners[channel] = (fd, cursor)
# Send the LISTEN to PostgreSQL
cursor.execute("LISTEN %s" % channel)
self._ensure_pool_exists()
while channel in self._listeners and self._listeners[channel]:
# Wait for an event on that FD
yield gen.Wait((self, fd))
# Iterate through all of the notifications
while connection.notifies:
notify = connection.notifies.pop()
callback(channel, notify.pid, notify.payload)
# Set a new callback for the fd if we're not exiting
if channel in self._listeners:
self._callbacks[fd] = yield gen.Callback((self, fd))
@gen.coroutine
def query(self, sql, parameters=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.ProgrammingError
"""
# Grab a connection, either new or out of the pool
connection, fd, status = self._connect()
# Add a callback for either connecting or waiting for the query
self._callbacks[fd] = yield gen.Callback((self, fd))
# Add the connection to the IOLoop
self._ioloop.add_handler(connection.fileno(), self._on_io_events,
ioloop.IOLoop.WRITE)
# Maybe wait for the connection
if status == self.SETUP and connection.poll() != extensions.POLL_OK:
yield gen.Wait((self, fd))
# Setup the callback for the actual query
self._callbacks[fd] = yield gen.Callback((self, fd))
# Get the cursor, execute the query and wait for the result
cursor = self._get_cursor(connection)
cursor.execute(sql, parameters)
yield gen.Wait((self, fd))
# If there was an exception, cleanup, then raise it
if fd in self._exceptions and self._exceptions[fd]:
error = self._exceptions[fd]
self._exec_cleanup(cursor, fd)
raise error
# Carry the row count to return to the caller
row_count = cursor.rowcount
# Attempt to get any result that's pending for the query
try:
result = cursor.fetchall()
except psycopg2.ProgrammingError:
result = []
# Close the cursor and cleanup the references for this request
self._exec_cleanup(cursor, fd)
# Return the result if there are any
raise gen.Return((row_count, result))
@gen.coroutine
def unlisten(self, channel):
: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)
# Close the cursor and cleanup the references for this request
self._exec_cleanup(cursor, fd)
def _connect(self):
"""Connect to PostgreSQL and setup a few variables and data structures
to reduce code in the coroutine methods.
:return tuple: psycopg2.extensions.connection, int, int
"""
connection = super(TornadoSession, self)._connect()
fd, status = connection.fileno(), connection.status
# Add the connection for use in _poll_connection
self._connections[fd] = connection
return connection, fd, status
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.
# connection in a weird state: consts.STATUS_DATESTYLE,
# returning from Connection._setup without setting the state
# as const.STATUS_OK
"""
cursor.close()
if fd in self._exceptions:
del self._exceptions[fd]
if fd in self._callbacks:
del self._callbacks[fd]
if fd in self._connections:
del self._connections[fd]
self._ioloop.remove_handler(fd)
def _get_cursor(self, connection):
"""Return a cursor for the given connection.
:param psycopg2.extensions.connection connection: The connection to use
:rtype: psycopg2.extensions.cursor
"""
return connection.cursor(cursor_factory=self._cursor_factory)
@gen.coroutine
def _on_io_events(self, fd=None, events=None):
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> Refactor WIP commit, will break tests, just saying.
- Refactor pooling internals considerably
- New Results object for returning results from query and callproc
- Refactor Session and TornadoSession to use Results and new pooling behaviors
<DFF> @@ -28,11 +28,29 @@ from tornado import stack_context
import psycopg2
from queries import pool
+from queries import results
from queries import session
+from queries import utils
from queries import DEFAULT_URI
+from queries import PYPY
LOGGER = logging.getLogger(__name__)
+class Results(results.Results):
+ """Class that is created for each query that allows for the use of query
+ results...
+
+ """
+ def __init__(self, cursor, cleanup, fd):
+ self.cursor = cursor
+ self._cleanup = cleanup
+ self._fd = fd
+
+ @gen.coroutine
+ def release(self):
+ yield self._cleanup(self.cursor, self._fd)
+
+
class TornadoSession(session.Session):
"""Session class for Tornado asynchronous applications. Uses
@@ -50,34 +68,37 @@ class TornadoSession(session.Session):
:py:meth:`cursor.fetchall`.
:param str uri: PostgreSQL connection URI
- :param psycopg2.cursor: The cursor type to use
- :param bool use_pool: Use the connection pool
- :param int max_pool_size: Maximum number of connections for a single 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=DEFAULT_URI,
+ def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
- use_pool=True,
- max_pool_size=pool.MAX_SIZE):
+ pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
+ pool_max_size=pool.DEFAULT_MAX_SIZE):
"""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 bool use_pool: Use the connection pool
- :param int max_pool_size: Max number of connections for a single URI
+ :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
"""
self._callbacks = dict()
- self._listeners = dict()
self._connections = dict()
- self._commands = dict()
- self._cursor_factory = cursor_factory
self._exceptions = dict()
+ self._listeners = dict()
+
+ self._cursor_factory = cursor_factory
self._ioloop = ioloop.IOLoop.instance()
+ self._pool_manager = pool.PoolManager.instance()
self._uri = uri
- self._use_pool = use_pool
+
+ # 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)
@gen.coroutine
def callproc(self, name, args=None):
@@ -98,44 +119,27 @@ class TornadoSession(session.Session):
:raises: queries.ProgrammingError
"""
- # Grab a connection, either new or out of the pool
- connection, fd, status = self._connect()
+ conn = yield self._connect()
- # Add a callback for either connecting or waiting for the query
- self._callbacks[fd] = yield gen.Callback((self, fd))
-
- # Add the connection to the IOLoop
- self._ioloop.add_handler(connection.fileno(), self._on_io_events,
- ioloop.IOLoop.WRITE)
-
- # Maybe wait for the connection
- if status == self.SETUP and connection.poll() != extensions.POLL_OK:
- yield gen.Wait((self, fd))
- # Setup the callback for the actual query
- self._callbacks[fd] = yield gen.Callback((self, fd))
+ # Setup a callback to wait on the query result
+ self._callbacks[conn.fileno()] = yield gen.Callback((self,
+ conn.fileno()))
# Get the cursor, execute the query and wait for the result
- cursor = self._get_cursor(connection)
+ cursor = self._get_cursor(conn)
cursor.callproc(name, args)
- yield gen.Wait((self, fd))
+ yield gen.Wait((self, conn.fileno()))
# If there was an exception, cleanup, then raise it
- if fd in self._exceptions and self._exceptions[fd]:
- error = self._exceptions[fd]
- self._exec_cleanup(cursor, fd)
+ if (conn.fileno() in self._exceptions and
+ self._exceptions[conn.fileno()]):
+ error = self._exceptions[conn.fileno()]
+ self._exec_cleanup(cursor, conn.fileno())
raise error
- # Attempt to get any result that's pending for the query
- try:
- result = cursor.fetchall()
- except psycopg2.ProgrammingError:
- result = []
-
- # Close the cursor and cleanup the references for this request
- self._exec_cleanup(cursor, fd)
-
# Return the result if there are any
- raise gen.Return(result)
+ cleanup = yield gen.Callback((self, self._exec_cleanup))
+ raise gen.Return(Results(cursor, cleanup, conn.fileno()))
@gen.coroutine
def listen(self, channel, callback):
@@ -146,27 +150,13 @@ class TornadoSession(session.Session):
:param method callback: The method to call on each notification
"""
- # Grab a connection, either new or out of the pool
- connection, fd, status = self._connect()
-
- # Add a callback for either connecting or waiting for the query
- self._callbacks[fd] = yield gen.Callback((self, fd))
-
- # Add the connection to the IOLoop
- self._ioloop.add_handler(connection.fileno(), self._on_io_events,
- ioloop.IOLoop.WRITE)
-
- # Maybe wait for the connection
- if status == self.SETUP and connection.poll() != extensions.POLL_OK:
- yield gen.Wait((self, fd))
- # Setup the callback for the actual query
- self._callbacks[fd] = yield gen.Callback((self, fd))
+ conn = yield self._connect()
# Get the cursor
- cursor = self._get_cursor(connection)
+ cursor = self._get_cursor(conn)
# Add the channel and callback to the class level listeners
- self._listeners[channel] = (fd, cursor)
+ self._listeners[channel] = (conn.fileno(), cursor)
# Send the LISTEN to PostgreSQL
cursor.execute("LISTEN %s" % channel)
@@ -175,16 +165,17 @@ class TornadoSession(session.Session):
while channel in self._listeners and self._listeners[channel]:
# Wait for an event on that FD
- yield gen.Wait((self, fd))
+ yield gen.Wait((self, conn.fileno()))
# Iterate through all of the notifications
- while connection.notifies:
- notify = connection.notifies.pop()
+ while conn.notifies:
+ notify = conn.notifies.pop()
callback(channel, notify.pid, notify.payload)
# Set a new callback for the fd if we're not exiting
if channel in self._listeners:
- self._callbacks[fd] = yield gen.Callback((self, fd))
+ self._callbacks[conn.fileno()] = \
+ yield gen.Callback((self, conn.fileno()))
@gen.coroutine
def query(self, sql, parameters=None):
@@ -205,47 +196,27 @@ class TornadoSession(session.Session):
:raises: queries.ProgrammingError
"""
- # Grab a connection, either new or out of the pool
- connection, fd, status = self._connect()
-
- # Add a callback for either connecting or waiting for the query
- self._callbacks[fd] = yield gen.Callback((self, fd))
-
- # Add the connection to the IOLoop
- self._ioloop.add_handler(connection.fileno(), self._on_io_events,
- ioloop.IOLoop.WRITE)
+ conn = yield self._connect()
- # Maybe wait for the connection
- if status == self.SETUP and connection.poll() != extensions.POLL_OK:
- yield gen.Wait((self, fd))
- # Setup the callback for the actual query
- self._callbacks[fd] = yield gen.Callback((self, fd))
+ # Setup a callback to wait on the query result
+ self._callbacks[conn.fileno()] = yield gen.Callback((self,
+ conn.fileno()))
# Get the cursor, execute the query and wait for the result
- cursor = self._get_cursor(connection)
+ cursor = self._get_cursor(conn)
cursor.execute(sql, parameters)
- yield gen.Wait((self, fd))
+ yield gen.Wait((self, conn.fileno()))
+ del self._callbacks[conn.fileno()]
# If there was an exception, cleanup, then raise it
- if fd in self._exceptions and self._exceptions[fd]:
- error = self._exceptions[fd]
- self._exec_cleanup(cursor, fd)
+ if (conn.fileno() in self._exceptions and
+ self._exceptions[conn.fileno()]):
+ error = self._exceptions[conn.fileno()]
+ self._exec_cleanup(cursor, conn.fileno())
raise error
- # Carry the row count to return to the caller
- row_count = cursor.rowcount
-
- # Attempt to get any result that's pending for the query
- try:
- result = cursor.fetchall()
- except psycopg2.ProgrammingError:
- result = []
-
- # Close the cursor and cleanup the references for this request
- self._exec_cleanup(cursor, fd)
-
# Return the result if there are any
- raise gen.Return((row_count, result))
+ raise gen.Return(Results(cursor, self._exec_cleanup, conn.fileno()))
@gen.coroutine
def unlisten(self, channel):
@@ -273,21 +244,72 @@ class TornadoSession(session.Session):
# Close the cursor and cleanup the references for this request
self._exec_cleanup(cursor, fd)
+ @gen.coroutine
def _connect(self):
- """Connect to PostgreSQL and setup a few variables and data structures
- to reduce code in the coroutine methods.
+ """Connect to PostgreSQL, either by reusing a connection from the pool
+ if possible, or by creating the new connection.
- :return tuple: psycopg2.extensions.connection, int, int
+ :rtype: psycopg2.extensions.connection
+ :raises: pool.NoIdleConnectionsError
"""
- connection = super(TornadoSession, self)._connect()
- fd, status = connection.fileno(), connection.status
+ # Attempt to get a cached connection from the connection pool
+ try:
+ connection = self._pool_manager.get(self.pid, self)
+
+ self._connections[connection.fileno()] = connection
+ self._callbacks[connection.fileno()] = None
+ self._exceptions[connection.fileno()] = None
+
+ # Add the connection to the IOLoop
+ self._ioloop.add_handler(connection.fileno(), self._on_io_events,
+ ioloop.IOLoop.WRITE)
+
+ except pool.NoIdleConnectionsError:
+ # "Block" while the pool is full
+ while self._pool_manager.is_full(self.pid):
+ LOGGER.warning('Pool %s is full, waiting 100ms', self.pid)
+ timeout = yield gen.Callback((self, 'connect'))
+ self._ioloop.add_timeout(100, timeout)
+ yield gen.Wait((self, 'connect'))
+
+ # Create a new PostgreSQL connection
+ kwargs = utils.uri_to_kwargs(self._uri)
+ connection = self._psycopg2_connect(kwargs)
+ fd = connection.fileno()
+
+ # Add the connection for use in _poll_connection
+ self._connections[fd] = connection
+ self._exceptions[fd] = None
+
+ # Add a callback for either connecting or waiting for the query
+ self._callbacks[fd] = yield gen.Callback((self, fd))
+
+ # Add the connection to the IOLoop
+ self._ioloop.add_handler(connection.fileno(), self._on_io_events,
+ ioloop.IOLoop.WRITE)
+
+ # Wait for the connection
+ yield gen.Wait((self, fd))
+ del self._callbacks[fd]
+
+ # Add the connection to the pool
+ self._pool_manager.add(self.pid, connection)
+ self._pool_manager.lock(self.pid, connection, self)
- # Add the connection for use in _poll_connection
- self._connections[fd] = connection
+ # Added in because psycopg2ct 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 PYPY:
+ connection.reset()
- return connection, fd, status
+ # Register the custom data types
+ self._register_unicode(connection)
+ self._register_uuid(connection)
+ raise gen.Return(connection)
+
+ @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.
@@ -297,22 +319,17 @@ class TornadoSession(session.Session):
"""
cursor.close()
+ self._pool_manager.free(self.pid, self._connections[fd])
+
if fd in self._exceptions:
del self._exceptions[fd]
if fd in self._callbacks:
del self._callbacks[fd]
if fd in self._connections:
del self._connections[fd]
- self._ioloop.remove_handler(fd)
-
- def _get_cursor(self, connection):
- """Return a cursor for the given connection.
- :param psycopg2.extensions.connection connection: The connection to use
- :rtype: psycopg2.extensions.cursor
-
- """
- return connection.cursor(cursor_factory=self._cursor_factory)
+ self._ioloop.remove_handler(fd)
+ raise gen.Return()
@gen.coroutine
def _on_io_events(self, fd=None, events=None):
| 129 | Refactor WIP commit, will break tests, just saying. | 112 | .py | py | bsd-3-clause | gmr/queries |
1487 | <NME> history.rst
<BEF> Version History
===============
- Next Release
- 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
- Dont raise NotImplementedError in Results.free for synchronous use, just treat as a noop
- Fix Results iterator for Python 3.7 (#31 - `nvllsvm <https://github.com/nvllsvm>`_)
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
-----------------
- 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> docs/history: Add 1.10.0
<DFF> @@ -1,6 +1,6 @@
Version History
===============
-- Next Release
+- 1.10.0 2016-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
- Dont raise NotImplementedError in Results.free for synchronous use, just treat as a noop
| 1 | docs/history: Add 1.10.0 | 1 | .rst | rst | bsd-3-clause | gmr/queries |
1488 | <NME> history.rst
<BEF> Version History
===============
- Next Release
- 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
- Dont raise NotImplementedError in Results.free for synchronous use, just treat as a noop
- Fix Results iterator for Python 3.7 (#31 - `nvllsvm <https://github.com/nvllsvm>`_)
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
-----------------
- 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> docs/history: Add 1.10.0
<DFF> @@ -1,6 +1,6 @@
Version History
===============
-- Next Release
+- 1.10.0 2016-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
- Dont raise NotImplementedError in Results.free for synchronous use, just treat as a noop
| 1 | docs/history: Add 1.10.0 | 1 | .rst | rst | bsd-3-clause | gmr/queries |
1489 | <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',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Database',
'Topic :: Software Development :: Libraries']
setup(name='queries',
version='1.9.1',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
'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 version
<DFF> @@ -20,16 +20,15 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.3',
- 'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
+ 'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Database',
'Topic :: Software Development :: Libraries']
setup(name='queries',
- version='1.9.1',
+ version='1.10.0',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
| 2 | Bump version | 3 | .py | py | bsd-3-clause | gmr/queries |
1490 | <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',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Database',
'Topic :: Software Development :: Libraries']
setup(name='queries',
version='1.9.1',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
'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 version
<DFF> @@ -20,16 +20,15 @@ classifiers = ['Development Status :: 5 - Production/Stable',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.3',
- 'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
+ 'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Database',
'Topic :: Software Development :: Libraries']
setup(name='queries',
- version='1.9.1',
+ version='1.10.0',
description="Simplified PostgreSQL client built upon Psycopg2",
maintainer="Gavin M. Roy",
maintainer_email="[email protected]",
| 2 | Bump version | 3 | .py | py | bsd-3-clause | gmr/queries |
1491 | <NME> session.py
<BEF> """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` connection and cursor objects to
provide ultimate flexibility in how you use the 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 Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
: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
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""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
"""
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._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit(autocommit)
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.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
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
LOGGER.info('Closing connection %r in %s', self._conn, self.pid)
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
# Querying, executing, copying, etc
def callproc(self, name, parameters=None):
"""Call a stored procedure on the server returning all of the rows
returned by the server.
:rtype: list
"""
self._cursor.callproc(name, parameters)
try:
return self._cursor.fetchall()
except psycopg2.ProgrammingError:
return
def callproc_results(self, name, parameters=None):
"""Call a stored procedure on the server and return an iterator of the
result set for easy access to the data.
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
for row in session.callproc('now'):
print row
:param str name: The procedure name
:param list parameters: The list of parameters to pass in
:return: iterator
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
return
def query(self, sql, parameters=None):
"""Issue a query on the server mogrifying the parameters against the
sql statement and returning the entire result set as a list.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: list
"""
self._cursor.execute(sql, parameters or {})
try:
return self._cursor.fetchall()
except psycopg2.ProgrammingError as error:
return
def query_results(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement and returning the results as an
iterator.
"""
self._cleanup()
{'bar': 'baz'}):
print row
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: iterator
"""
self._cleanup()
def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit or not after every query
:param autocommit: Boolean (Default - True)
"""
self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
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
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct 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.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
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
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Simplify the API even more, add more examples in docs and README
<DFF> @@ -201,19 +201,6 @@ class Session(object):
# Querying, executing, copying, etc
def callproc(self, name, parameters=None):
- """Call a stored procedure on the server returning all of the rows
- returned by the server.
-
- :rtype: list
-
- """
- self._cursor.callproc(name, parameters)
- try:
- return self._cursor.fetchall()
- except psycopg2.ProgrammingError:
- return
-
- def callproc_results(self, name, parameters=None):
"""Call a stored procedure on the server and return an iterator of the
result set for easy access to the data.
@@ -222,6 +209,13 @@ class Session(object):
for row in session.callproc('now'):
print row
+ To return the full set of rows in a single call, wrap the method with
+ list:
+
+ .. code:: python
+
+ rows = list(session.callproc('now'))
+
:param str name: The procedure name
:param list parameters: The list of parameters to pass in
:return: iterator
@@ -235,21 +229,6 @@ class Session(object):
return
def query(self, sql, parameters=None):
- """Issue a query on the server mogrifying the parameters against the
- sql statement and returning the entire result set as a list.
-
- :param str sql: The SQL statement
- :param dict parameters: A dictionary of query parameters
- :rtype: list
-
- """
- self._cursor.execute(sql, parameters or {})
- try:
- return self._cursor.fetchall()
- except psycopg2.ProgrammingError as error:
- return
-
- def query_results(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement and returning the results as an
iterator.
@@ -260,6 +239,13 @@ class Session(object):
{'bar': 'baz'}):
print row
+ To return the full set of rows in a single call, wrap the method with
+ list:
+
+ .. code:: python
+
+ rows = list(session.query('SELECT * FROM foo'))
+
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: iterator
| 14 | Simplify the API even more, add more examples in docs and README | 28 | .py | py | bsd-3-clause | gmr/queries |
1492 | <NME> session.py
<BEF> """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` connection and cursor objects to
provide ultimate flexibility in how you use the 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 Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
: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
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE,
autocommit=True):
"""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
"""
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._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit(autocommit)
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.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
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
LOGGER.info('Closing connection %r in %s', self._conn, self.pid)
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
# Querying, executing, copying, etc
def callproc(self, name, parameters=None):
"""Call a stored procedure on the server returning all of the rows
returned by the server.
:rtype: list
"""
self._cursor.callproc(name, parameters)
try:
return self._cursor.fetchall()
except psycopg2.ProgrammingError:
return
def callproc_results(self, name, parameters=None):
"""Call a stored procedure on the server and return an iterator of the
result set for easy access to the data.
:raises: queries.InterfaceError
:raises: queries.NotSupportedError
for row in session.callproc('now'):
print row
:param str name: The procedure name
:param list parameters: The list of parameters to pass in
:return: iterator
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
return
def query(self, sql, parameters=None):
"""Issue a query on the server mogrifying the parameters against the
sql statement and returning the entire result set as a list.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: list
"""
self._cursor.execute(sql, parameters or {})
try:
return self._cursor.fetchall()
except psycopg2.ProgrammingError as error:
return
def query_results(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement and returning the results as an
iterator.
"""
self._cleanup()
{'bar': 'baz'}):
print row
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: iterator
"""
self._cleanup()
def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit or not after every query
:param autocommit: Boolean (Default - True)
"""
self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
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
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct 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.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
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
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Simplify the API even more, add more examples in docs and README
<DFF> @@ -201,19 +201,6 @@ class Session(object):
# Querying, executing, copying, etc
def callproc(self, name, parameters=None):
- """Call a stored procedure on the server returning all of the rows
- returned by the server.
-
- :rtype: list
-
- """
- self._cursor.callproc(name, parameters)
- try:
- return self._cursor.fetchall()
- except psycopg2.ProgrammingError:
- return
-
- def callproc_results(self, name, parameters=None):
"""Call a stored procedure on the server and return an iterator of the
result set for easy access to the data.
@@ -222,6 +209,13 @@ class Session(object):
for row in session.callproc('now'):
print row
+ To return the full set of rows in a single call, wrap the method with
+ list:
+
+ .. code:: python
+
+ rows = list(session.callproc('now'))
+
:param str name: The procedure name
:param list parameters: The list of parameters to pass in
:return: iterator
@@ -235,21 +229,6 @@ class Session(object):
return
def query(self, sql, parameters=None):
- """Issue a query on the server mogrifying the parameters against the
- sql statement and returning the entire result set as a list.
-
- :param str sql: The SQL statement
- :param dict parameters: A dictionary of query parameters
- :rtype: list
-
- """
- self._cursor.execute(sql, parameters or {})
- try:
- return self._cursor.fetchall()
- except psycopg2.ProgrammingError as error:
- return
-
- def query_results(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement and returning the results as an
iterator.
@@ -260,6 +239,13 @@ class Session(object):
{'bar': 'baz'}):
print row
+ To return the full set of rows in a single call, wrap the method with
+ list:
+
+ .. code:: python
+
+ rows = list(session.query('SELECT * FROM foo'))
+
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: iterator
| 14 | Simplify the API even more, add more examples in docs and README | 28 | .py | py | bsd-3-clause | gmr/queries |
1493 | <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 psycopg2
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
PostgreSQL. As of ``1.10.3``
.. deprecated:: 1.10.3
As of 1.10.3, this method only raises a
:py:exception:`DeprecationWarning`.
:rtype: bool
:raises: DeprecationWarning
"""
raise DeprecationWarning('All functionality removed from this method')
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
"""
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> Dont raise DeprecationWarning, use warning.warn
<DFF> @@ -24,6 +24,7 @@ Example Use:
"""
import logging
import socket
+import warnings
import psycopg2
from psycopg2 import extras, extensions
@@ -237,14 +238,13 @@ class TornadoSession(session.Session):
PostgreSQL. As of ``1.10.3``
.. deprecated:: 1.10.3
- As of 1.10.3, this method only raises a
- :py:exception:`DeprecationWarning`.
+ As of 1.10.3, this method only warns about Deprecation
:rtype: bool
- :raises: DeprecationWarning
"""
- raise DeprecationWarning('All functionality removed from this method')
+ warnings.warn(
+ 'All functionality removed from this method', DeprecationWarning)
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
| 4 | Dont raise DeprecationWarning, use warning.warn | 4 | .py | py | bsd-3-clause | gmr/queries |
1494 | <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 psycopg2
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
PostgreSQL. As of ``1.10.3``
.. deprecated:: 1.10.3
As of 1.10.3, this method only raises a
:py:exception:`DeprecationWarning`.
:rtype: bool
:raises: DeprecationWarning
"""
raise DeprecationWarning('All functionality removed from this method')
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
"""
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> Dont raise DeprecationWarning, use warning.warn
<DFF> @@ -24,6 +24,7 @@ Example Use:
"""
import logging
import socket
+import warnings
import psycopg2
from psycopg2 import extras, extensions
@@ -237,14 +238,13 @@ class TornadoSession(session.Session):
PostgreSQL. As of ``1.10.3``
.. deprecated:: 1.10.3
- As of 1.10.3, this method only raises a
- :py:exception:`DeprecationWarning`.
+ As of 1.10.3, this method only warns about Deprecation
:rtype: bool
- :raises: DeprecationWarning
"""
- raise DeprecationWarning('All functionality removed from this method')
+ warnings.warn(
+ 'All functionality removed from this method', DeprecationWarning)
def _connect(self):
"""Connect to PostgreSQL, either by reusing a connection from the pool
| 4 | Dont raise DeprecationWarning, use warning.warn | 4 | .py | py | bsd-3-clause | gmr/queries |
1495 | <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
from queries import results
from queries import session
class SessionTests(unittest.TestCase):
@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):
self.conn = mock.Mock()
self.conn.autocommit = False
self.conn.closed = False
self.conn.cursor = mock.Mock()
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_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': 'bar',
'dbname': 'foo'}
self.obj = session.Session(self.URI, pool_max_size=100)
def test_init_sets_uri(self):
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):
self.obj.close()
self.assertNotIn(self.conn,
self.obj._pool_manager._pools[self.obj.pid])
def test_close_unassigns_connection(self):
self.obj.close()
self.assertIsNone(self.obj._conn)
def test_close_unassigns_cursor(self):
self.obj.close()
self.assertIsNone(self.obj._cursor)
def test_connection_property_returns_correct_value(self):
self.assertEqual(self.obj.connection, self.conn)
def test_cursor_property_returns_correct_value(self):
self.assertEqual(self.obj.cursor, self.obj._cursor)
def test_encoding_property_value(self):
self.conn.encoding = 'UTF-8'
self.assertEqual(self.obj.encoding, 'UTF-8')
def test_notices_value(self):
self.conn.notices = [1, 2, 3]
self.assertListEqual(self.obj.notices, [1, 2, 3])
def test_pid_value(self):
expectation = hashlib.md5(
':'.join([self.obj.__class__.__name__,
self.URI]).encode('utf-8')).hexdigest()
self.assertEqual(self.obj.pid, expectation)
def test_query_invokes_cursor_execute(self):
self.obj._cursor.callproc = mock.Mock()
args = ('SELECT * FROM foo', ['bar', 'baz'])
self.obj.query(*args)
self.obj._cursor.execute.assert_called_once_with(*args)
def test_set_encoding_sets_encoding_if_different(self):
self.conn.encoding = 'LATIN-1'
self.obj.set_encoding('UTF-8')
self.assertFalse(set_client_encoding.called)
def test_del_invokes_cleanup(self):
cleanup = mock.Mock()
with mock.patch.multiple('queries.session.Session',
self.obj.set_encoding('UTF-8')
self.assertFalse(set_client_encoding.called)
@unittest.skipIf(utils.PYPY,
obj = session.Session(self.URI)
del obj
cleanup.assert_called_once_with()
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> Add skipIf for PYPY, additional tests
<DFF> @@ -16,6 +16,8 @@ from queries import pool
from queries import results
from queries import session
+from queries import PYPY
+
class SessionTests(unittest.TestCase):
@@ -130,6 +132,7 @@ class SessionTests(unittest.TestCase):
self.obj.set_encoding('UTF-8')
self.assertFalse(set_client_encoding.called)
+ @unittest.skipIf(PYPY, 'PYPY does not invoke object.__del__ synchronously')
def test_del_invokes_cleanup(self):
cleanup = mock.Mock()
with mock.patch.multiple('queries.session.Session',
@@ -140,3 +143,45 @@ class SessionTests(unittest.TestCase):
obj = session.Session(self.URI)
del obj
cleanup.assert_called_once_with()
+
+ def test_exit_invokes_cleanup(self):
+ cleanup = mock.Mock()
+ with mock.patch.multiple('queries.session.Session',
+ _cleanup=cleanup,
+ _connect=mock.Mock(),
+ _get_cursor=mock.Mock(),
+ _autocommit=mock.Mock()):
+ with session.Session(self.URI) as sess:
+ pass
+ cleanup.assert_called_once_with()
+
+ def test_autocommit_sets_attribute(self):
+ self.conn.autocommit = False
+ self.obj._autocommit()
+ self.assertTrue(self.conn.autocommit)
+
+ def test_cleanup_closes_cursor(self):
+ self.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.cursor.close = mock.Mock()
+ self.conn = None
+ self.obj._cleanup()
+ self.assertIsNone(self.obj._cursor)
+
+ def test_cleanup_frees_connection(self):
+ pool.PoolManager.free = free = mock.Mock()
+ self.obj._cleanup()
+ free.assert_called_once_with(self.obj.pid, self.conn)
+
+ def test_cleanup_sets_connecto_to_none(self):
+ self.obj._cleanup()
+ self.assertIsNone(self.obj._conn)
+
+ def test_cleanup_cleans_pool_manager(self):
+ pool.PoolManager.clean = clean = mock.Mock()
+ self.obj._cleanup()
+ clean.assert_called_once_with(self.obj.pid)
| 45 | Add skipIf for PYPY, additional tests | 0 | .py | py | bsd-3-clause | gmr/queries |
1496 | <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
from queries import results
from queries import session
class SessionTests(unittest.TestCase):
@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):
self.conn = mock.Mock()
self.conn.autocommit = False
self.conn.closed = False
self.conn.cursor = mock.Mock()
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_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': 'bar',
'dbname': 'foo'}
self.obj = session.Session(self.URI, pool_max_size=100)
def test_init_sets_uri(self):
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):
self.obj.close()
self.assertNotIn(self.conn,
self.obj._pool_manager._pools[self.obj.pid])
def test_close_unassigns_connection(self):
self.obj.close()
self.assertIsNone(self.obj._conn)
def test_close_unassigns_cursor(self):
self.obj.close()
self.assertIsNone(self.obj._cursor)
def test_connection_property_returns_correct_value(self):
self.assertEqual(self.obj.connection, self.conn)
def test_cursor_property_returns_correct_value(self):
self.assertEqual(self.obj.cursor, self.obj._cursor)
def test_encoding_property_value(self):
self.conn.encoding = 'UTF-8'
self.assertEqual(self.obj.encoding, 'UTF-8')
def test_notices_value(self):
self.conn.notices = [1, 2, 3]
self.assertListEqual(self.obj.notices, [1, 2, 3])
def test_pid_value(self):
expectation = hashlib.md5(
':'.join([self.obj.__class__.__name__,
self.URI]).encode('utf-8')).hexdigest()
self.assertEqual(self.obj.pid, expectation)
def test_query_invokes_cursor_execute(self):
self.obj._cursor.callproc = mock.Mock()
args = ('SELECT * FROM foo', ['bar', 'baz'])
self.obj.query(*args)
self.obj._cursor.execute.assert_called_once_with(*args)
def test_set_encoding_sets_encoding_if_different(self):
self.conn.encoding = 'LATIN-1'
self.obj.set_encoding('UTF-8')
self.assertFalse(set_client_encoding.called)
def test_del_invokes_cleanup(self):
cleanup = mock.Mock()
with mock.patch.multiple('queries.session.Session',
self.obj.set_encoding('UTF-8')
self.assertFalse(set_client_encoding.called)
@unittest.skipIf(utils.PYPY,
obj = session.Session(self.URI)
del obj
cleanup.assert_called_once_with()
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> Add skipIf for PYPY, additional tests
<DFF> @@ -16,6 +16,8 @@ from queries import pool
from queries import results
from queries import session
+from queries import PYPY
+
class SessionTests(unittest.TestCase):
@@ -130,6 +132,7 @@ class SessionTests(unittest.TestCase):
self.obj.set_encoding('UTF-8')
self.assertFalse(set_client_encoding.called)
+ @unittest.skipIf(PYPY, 'PYPY does not invoke object.__del__ synchronously')
def test_del_invokes_cleanup(self):
cleanup = mock.Mock()
with mock.patch.multiple('queries.session.Session',
@@ -140,3 +143,45 @@ class SessionTests(unittest.TestCase):
obj = session.Session(self.URI)
del obj
cleanup.assert_called_once_with()
+
+ def test_exit_invokes_cleanup(self):
+ cleanup = mock.Mock()
+ with mock.patch.multiple('queries.session.Session',
+ _cleanup=cleanup,
+ _connect=mock.Mock(),
+ _get_cursor=mock.Mock(),
+ _autocommit=mock.Mock()):
+ with session.Session(self.URI) as sess:
+ pass
+ cleanup.assert_called_once_with()
+
+ def test_autocommit_sets_attribute(self):
+ self.conn.autocommit = False
+ self.obj._autocommit()
+ self.assertTrue(self.conn.autocommit)
+
+ def test_cleanup_closes_cursor(self):
+ self.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.cursor.close = mock.Mock()
+ self.conn = None
+ self.obj._cleanup()
+ self.assertIsNone(self.obj._cursor)
+
+ def test_cleanup_frees_connection(self):
+ pool.PoolManager.free = free = mock.Mock()
+ self.obj._cleanup()
+ free.assert_called_once_with(self.obj.pid, self.conn)
+
+ def test_cleanup_sets_connecto_to_none(self):
+ self.obj._cleanup()
+ self.assertIsNone(self.obj._conn)
+
+ def test_cleanup_cleans_pool_manager(self):
+ pool.PoolManager.clean = clean = mock.Mock()
+ self.obj._cleanup()
+ clean.assert_called_once_with(self.obj.pid)
| 45 | Add skipIf for PYPY, additional tests | 0 | .py | py | bsd-3-clause | gmr/queries |
1497 | <NME> requirements.txt
<BEF> ADDFILE
<MSG> Update to use coveralls for test coverage monitoring/reporting
<DFF> @@ -0,0 +1,3 @@
+psycopg2
+tornado
+python-coveralls
\ No newline at end of file
| 3 | Update to use coveralls for test coverage monitoring/reporting | 0 | .txt | txt | bsd-3-clause | gmr/queries |
1498 | <NME> requirements.txt
<BEF> ADDFILE
<MSG> Update to use coveralls for test coverage monitoring/reporting
<DFF> @@ -0,0 +1,3 @@
+psycopg2
+tornado
+python-coveralls
\ No newline at end of file
| 3 | Update to use coveralls for test coverage monitoring/reporting | 0 | .txt | txt | bsd-3-clause | gmr/queries |
1499 | <NME> session.py
<BEF> """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` connection and cursor objects to
provide ultimate flexibility in how you use the 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 Session.connection or Session.cursor properties to gain access to
either object just as you would in a program using psycopg2 directly.
Example usage:
.. code:: python
import queries
with queries.Session('pgsql://postgres@localhost/postgres') as session:
for row in session.Query('SELECT * FROM table'):
print row
"""
import hashlib
import logging
import psycopg2
from psycopg2 import extensions, extras
from queries import pool, results, utils
LOGGER = logging.getLogger(__name__)
DEFAULT_ENCODING = 'UTF8'
DEFAULT_URI = 'postgresql://localhost:5432'
class Session(object):
"""The Session class allows for a unified (and simplified) view of
interfacing with a PostgreSQL database server. The Session object can
act as a context manager, providing automated cleanup and simple, Pythonic
way of interacting with the object.
: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
"""
_conn = None
_cursor = None
_tpc_id = None
_uri = None
# Connection status constants
INTRANS = extensions.STATUS_IN_TRANSACTION
PREPARED = extensions.STATUS_PREPARED
READY = extensions.STATUS_READY
SETUP = extensions.STATUS_SETUP
# Transaction status constants
TX_ACTIVE = extensions.TRANSACTION_STATUS_ACTIVE
TX_IDLE = extensions.TRANSACTION_STATUS_IDLE
TX_INERROR = extensions.TRANSACTION_STATUS_INERROR
TX_INTRANS = extensions.TRANSACTION_STATUS_INTRANS
TX_UNKNOWN = extensions.TRANSACTION_STATUS_UNKNOWN
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
pool_max_size=pool.DEFAULT_MAX_SIZE):
"""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
"""
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._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
self._autocommit()
@property
def backend_pid(self):
"""Return the backend process ID of the PostgreSQL server that this
session is connected to.
:rtype: int
"""
return self._conn.get_backend_pid()
def callproc(self, name, args=None):
"""Call a stored procedure on the server, returning the results in a
:py:class:`queries.Results` instance.
:param str name: The procedure name
:param list args: The list of arguments to pass in
:rtype: queries.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
"""
try:
self._cursor.callproc(name, args)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def close(self):
"""Explicitly close the connection and remove it from the connection
pool if pooling is enabled. If the connection is already closed
:raises: psycopg2.InterfaceError
"""
if not self._conn:
raise psycopg2.InterfaceError('Connection not open')
LOGGER.info('Closing connection %r in %s', self._conn, self.pid)
self._pool_manager.free(self.pid, self._conn)
self._pool_manager.remove_connection(self.pid, self._conn)
# Un-assign the connection and cursor
self._conn, self._cursor = None, None
@property
def connection(self):
"""Return the current open connection to PostgreSQL.
:rtype: psycopg2.extensions.connection
"""
return self._conn
@property
def cursor(self):
"""Return the current, active cursor for the open connection.
:rtype: psycopg2.extensions.cursor
"""
return self._cursor
@property
def encoding(self):
"""Return the current client encoding value.
:rtype: str
"""
return self._conn.encoding
@property
def notices(self):
"""Return a list of up to the last 50 server notices sent to the client.
:rtype: list
"""
return self._conn.notices
@property
def pid(self):
"""Return the pool ID used for connection pooling.
:rtype: str
"""
return hashlib.md5(':'.join([self.__class__.__name__,
self._uri]).encode('utf-8')).hexdigest()
def query(self, sql, parameters=None):
"""A generator to issue a query on the server, mogrifying the
parameters against the sql statement. Results are returned as a
:py:class:`queries.Results` object which can act as an iterator and
has multiple ways to access the result data.
:param str sql: The SQL statement
:param dict parameters: A dictionary of query parameters
:rtype: queries.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
"""
try:
self._cursor.execute(sql, parameters)
except psycopg2.Error as err:
self._incr_exceptions()
raise err
finally:
self._incr_executions()
return results.Results(self._cursor)
def set_encoding(self, value=DEFAULT_ENCODING):
"""Set the client encoding for the session if the value specified
is different than the current client encoding.
:param str value: The encoding value to use
"""
if self._conn.encoding != value:
self._conn.set_client_encoding(value)
def __del__(self):
"""When deleting the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def __enter__(self):
"""For use as a context manager, return a handle to this object
instance.
:rtype: Session
"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""When leaving the context, ensure the instance is removed from
caches, etc.
"""
self._cleanup()
def _autocommit(self):
"""Set the isolation level automatically to commit after every query"""
self._conn.autocommit = True
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool', self.pid)
try:
pool.PoolManager.instance().free(self.pid, self._conn)
except pool.ConnectionNotFoundError:
pass
self._conn = None
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
"""
# Attempt to get a cached connection from the connection pool
try:
connection = self._pool_manager.get(self.pid, self)
LOGGER.debug("Re-using connection for %s", self.pid)
except pool.NoIdleConnectionsError:
if self._pool_manager.is_full(self.pid):
raise
# Create a new PostgreSQL connection
kwargs = utils.uri_to_kwargs(self._uri)
LOGGER.debug("Creating a new connection for %s", self.pid)
connection = self._psycopg2_connect(kwargs)
self._pool_manager.add(self.pid, connection)
self._pool_manager.lock(self.pid, connection, self)
# Added in because psycopg2ct 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.reset()
# Register the custom data types
self._register_unicode(connection)
self._register_uuid(connection)
return connection
def _get_cursor(self, connection, name=None):
"""Return a cursor for the given cursor_factory. Specify a name to
use server-side cursors.
:param connection: The connection to create a cursor on
:type connection: psycopg2.extensions.connection
:param str name: A cursor name for a server side cursor
:rtype: psycopg2.extensions.cursor
"""
cursor = connection.cursor(name=name,
cursor_factory=self._cursor_factory)
if name is not None:
cursor.scrollable = True
cursor.withhold = True
return cursor
def _incr_exceptions(self):
"""Increment the number of exceptions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).exceptions += 1
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1
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
"""
return psycopg2.connect(**kwargs)
@staticmethod
def _register_unicode(connection):
"""Register the cursor to be able to receive Unicode string.
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE,
connection)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY,
connection)
@staticmethod
def _register_uuid(connection):
"""Register the UUID extension from the psycopg2.extra module
:type connection: psycopg2.extensions.connection
:param connection: Where to register things
"""
psycopg2.extras.register_uuid(conn_or_curs=connection)
@property
def _status(self):
"""Return the current connection status as an integer value.
The status should match one of the following constants:
- queries.Session.INTRANS: Connection established, in transaction
- queries.Session.PREPARED: Prepared for second phase of transaction
- queries.Session.READY: Connected, no active transaction
:rtype: int
"""
if self._conn.status == psycopg2.extensions.STATUS_BEGIN:
return self.READY
return self._conn.status
<MSG> Add ability to override autocommit option for the session.
There could be cases when someone wants to execute multiple write queries and run it entirely as a transaction (as opposed to each query being committed).
In its current implementation, you cannot override the session's autocommit policy without having to access private attributes.
<DFF> @@ -70,7 +70,8 @@ class Session(object):
def __init__(self, uri=DEFAULT_URI,
cursor_factory=extras.RealDictCursor,
pool_idle_ttl=pool.DEFAULT_IDLE_TTL,
- pool_max_size=pool.DEFAULT_MAX_SIZE):
+ pool_max_size=pool.DEFAULT_MAX_SIZE
+ autocommit=True):
"""Connect to a PostgreSQL server using the module wide connection and
set the isolation level.
@@ -90,7 +91,7 @@ class Session(object):
self._conn = self._connect()
self._cursor_factory = cursor_factory
self._cursor = self._get_cursor(self._conn)
- self._autocommit()
+ self._autocommit(autocommit)
@property
def backend_pid(self):
@@ -251,9 +252,9 @@ class Session(object):
"""
self._cleanup()
- def _autocommit(self):
+ def _autocommit(self, autocommit):
"""Set the isolation level automatically to commit after every query"""
- self._conn.autocommit = True
+ self._conn.autocommit = autocommit
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
| 5 | Add ability to override autocommit option for the session. | 4 | .py | py | bsd-3-clause | gmr/queries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.